3 Replies Latest reply on Sep 8, 2013 5:34 PM by cotcodac

    Adding cross reference with find text

    Kel Dugal

      As titled. Could someone help me if this could be done automatically.

       

      thanks,

        • 1. Re: Adding cross reference with find text
          John Hawkinson Level 5

          Can you perhaps give us about five  paragraphs of detail on your problem and a screenshot?

          • 2. Re: Adding cross reference with find text
            Kasyan Servetsky Level 5

            Recently I wrote a script that creates x-refs in the indd-files located in the selected folder. You can't use it as it is since it was written according to my client's specific requirements, but it can give you idea how to write your own script. Or you can rework it to your needs.

             

            Regards,

            Kas

             

            // Written by Kasyan Servetsky
            // May 16, 2011
            // http://www.kasyan.ho.com.ua
            // e-mail: askoldich@yahoo.com
            //=========================================================================================================================
            const gScriptName = "Create Cross-References"; // Name of the script
            const gScriptVersion = "3.0"; // Version
            
            var gAppVersion = Number(String(app.version).split(".")[0]);
            if (gAppVersion < 6) ErrorExit("This script requires InDesign CS4 or CS5.", true);
            
            var gDoc, gStory, gHighligh, gBorderColor, gWidth, gBorderStyle;
            var gBorderColDesList = ["Black", "Blue", "Brick red", "Brown", "Burgundy", "Charcoal", "Cute teal", "Cyan", "Dark blue", "Dark green", "Fiesta", "Gold", "Grass green", "Gray", "Green", "Grid blue", "Grid green", "Grid orange", "Lavender", "Light blue", "Light gray", "Light olive", "Lipstick", "Magenta", "Ochre", "Olive green", "Orange", "Peach", "Pink", "Purple", "Red", "Sulphur", "Tan", "Teal", "Violet", "White", "Yellow"];
            
            var gSet = GetSettings();
            CreateDialog();
            
            //======================================================== FUNCTIONS  =====================================================
            function Main() {
                 var firstFrame;
                 var highlightEnumList = ["NONE", "INVERT", "OUTLINE", "INVERT"];
                 var widthEnumList = ["THIN", "MEDIUM", "THICK"];
                 var styleEnumList = ["SOLID", "DASHED"];
            
                 gHighligh = eval("HyperlinkAppearanceHighlight." + highlightEnumList[gSet.dll3Sel]);
                 gBorderColor = eval("UIColors." + gBorderColDesList[gSet.dll4Sel].toUpperCase().replace(" ", "_"));
                 gWidth = eval("HyperlinkAppearanceWidth." + widthEnumList[gSet.dll5Sel]);
                 gBorderStyle = eval("HyperlinkAppearanceStyle." + styleEnumList[gSet.dll6Sel]);
                 
                 var docFolder = Folder.selectDialog("Select a folder with InDesign files");
                 if (docFolder == null) exit();
                 var imagesFolder = new Folder(docFolder.fullName + "/images/");
                 if (!imagesFolder.exists) ErrorExit("\"Images\" folder doesn't exist in the \"" + docFolder.name + "\" folder", true);
                 var filelist = [];
                 var allFilesList = docFolder.getFiles();
            
                 for (var f = 0; f < allFilesList.length; f++) {
                      var file = allFilesList[f];
                      if (file instanceof File && file.name.match(/\.indd$/i)) {
                           filelist.push(file);
                      }
                 }
            
                 if (filelist.length == 0) {
                      ErrorExit("The selected folder contains no InDesign files.", true);
                 }
            
                 var counter = 1;
                 
                 if (gSet.checkBoxValue) WriteToFile("\r--------------------- Script started -- " + GetDate() + " ---------------------\n");
                 
                 app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT;
                 
                 // Progress bar -----------------------------------------------------------------------------------
                 var progressWin = new Window ( "window", gScriptName + " - " + gScriptVersion );
                 var progressBar = progressWin.add ("progressbar", [12, 12, 420, 24], 0, filelist.length);
                 var progressTxt = progressWin.add("statictext", undefined, "Creating Cross-References");
                 progressTxt.bounds = [0, 0, 410, 20];
                 progressTxt.alignment = "left";
                 progressWin.show();
                 // Progress bar -----------------------------------------------------------------------------------
                 
                 for (var d = 0; d < filelist.length; d++) {
                      var currentFile = filelist[d];
                      //$.writeln(d + "/currentFile.name" + currentFile.name);
                      if (gSet.checkBoxValue) WriteToFile("\r----------------------------------------------------\rFile: " + currentFile.name + "\n");
                      
                      try {
                           gDoc = app.open(currentFile, true);
                           
                           // Progress bar -----------------------------------------------------------------------------------
                           progressBar.value = counter;
                           progressTxt.text = String("Processing file - " + gDoc.name + " (" + counter + " of " + filelist.length + ")");
                           // Progress bar -----------------------------------------------------------------------------------
                           
                           //$.writeln(d + "/gDoc.name - " + gDoc.name);
                           // Get 'main' text frame
                           if (gAppVersion == 7) { // CS5
                                firstFrame = GetItemFromCollection("main", gDoc.textFrames);
                           }
                           else { // CS4
                                firstFrame = gDoc.pages[0].textFrames.item("main");
                           }
                      
                           if (firstFrame == undefined) ErrorExit("Can't find the text frame labeled as \"main\"", true);
                           gStory = firstFrame.parentStory;
                           if (gStory == undefined) ErrorExit("Can't find the story", true);
                      }
                      catch(err) {
                           $.writeln(gDoc.name + "/" + err);
                      }
                 
                      GetList();
                      CreateDestinations();
                      CreateHyperlinks();
                      
                      // Place the image
                      var paragraphs = gStory.paragraphs;
                      if (gStory.paragraphs[0].contents != "") gStory.insertionPoints[0].contents = "\r";
                      var baseName = GetFileNameOnly(gDoc.name);
                      var imageName = baseName + "_r1.jpg";
                      var imageFile = new File(docFolder.fullName + "/images/" + imageName);
                      
                      if (imageFile.exists) {
                           var image = gStory.insertionPoints[0].place(imageFile);
                           gStory.recompose();
                      }
                           
                      gDoc.close(SaveOptions.YES); // SaveOptions.YES // SaveOptions.NO
                      counter++;
                 }
            
                 // Progress bar -----------------------------------------------------------------------------------
                 progressWin.close();
                 // Progress bar -----------------------------------------------------------------------------------
                 
                 app.scriptPreferences.userInteractionLevel = UserInteractionLevels.INTERACT_WITH_ALL;
                 
                 if (gSet.checkBoxValue) WriteToFile("\r--------------------- Script finished -- " + GetDate() + " ---------------------\r\r");
            
                 alert("Done.", gScriptName + " - " + gScriptVersion);
            }          
            //--------------------------------------------------------------------------------------------------------------------------------------------------------
            function CreateDestinations() {
                 app.findGrepPreferences = app.changeGrepPreferences = NothingEnum.nothing;
                 app.findGrepPreferences.findWhat = ".+";
                 app.findGrepPreferences.appliedParagraphStyle = gDoc.paragraphStyles.item("H2");
                 var finds = gDoc.findGrep();
                 
                 var destCounter = 1;
                 if (gSet.checkBoxValue) WriteToFile("\rCreating destinations:\n"); 
                 if (finds.length == 0 && gSet.checkBoxValue) WriteToFile("No destination tags have been found.\r");
            
                 for ( var j = finds.length-1; j >= 0; j-- ) {
                      var found = finds[j];
                      if (found.constructor.name != "Character") {
                           try {
                                var hypTextDest = gDoc.paragraphDestinations.add(found);
                                hypTextDest.name = found.contents;
                                //$.writeln("Destination - " + found.contents + " -- Ok");
                                if (gSet.checkBoxValue) WriteToFile( ((destCounter < 10) ? (" " + destCounter) : destCounter) + " - " + found.contents + " -- Ok\n" );
                           }
                           catch(e) {
                                $.writeln(e);
                                if (gSet.checkBoxValue) WriteToFile( ((destCounter < 10) ? (" " + destCounter) : destCounter) + " - ERROR  -- Can't create destination \"" + found.contents + "\"\n");
                           }
                           destCounter++;
                      }
                 }
            }
            //--------------------------------------------------------------------------------------------------------------------------------------------------------
            function CreateHyperlinks() {
                 var xRefFormat = gDoc.crossReferenceFormats.item("Full Paragraph");
                 var des = gDoc.paragraphDestinations;
                 if (gSet.checkBoxValue) WriteToFile("\rCreating sources and cross-references:\n");
                 var sourceCounter = 1;
                 var hyperLinkCounter = 1
                           
                 for (var d = des.length-1; d >= 0; d--) {
                      //$.writeln(d + " -des- " + des[d].name);
                      app.findGrepPreferences = app.changeGrepPreferences = NothingEnum.nothing;
                      app.findGrepPreferences.findWhat = des[d].name;
                      app.findGrepPreferences.appliedParagraphStyle = gDoc.paragraphStyles.item("tx1");
                      var finds = gStory.paragraphs[0].findGrep();
                      var found = finds[0];
                      var sourceText = found;
                      var sourceName = found.contents;
                      try {
                           var source = gDoc.crossReferenceSources.add(sourceText, xRefFormat);
                           source.name = sourceName;
                           //$.writeln("Source - " + found.contents + " -- Ok");
                           if (gSet.checkBoxValue) WriteToFile(((sourceCounter < 10) ? (" " + sourceCounter) : sourceCounter) + " - Source - " + found.contents + " -- Ok\n");
                      }
                      catch(e) {
                           $.writeln(e);
                           if (gSet.checkBoxValue) WriteToFile( ((sourceCounter < 10) ? (" " + sourceCounter) : sourceCounter) + " - ERROR -- Can't create source \"" + found.contents + "\"\n");
                      }
                      
                      var parDest = gDoc.paragraphDestinations.itemByName(sourceName);
                      if (parDest.isValid) {
                           var hyperLink = gDoc.hyperlinks.add(source, parDest);
                           hyperLink.visible = (gSet.dll2Sel == 1) ? false : true;
                           hyperLink.highlight = gHighligh;
                           hyperLink.borderColor = gBorderColor;
                           hyperLink.width = gWidth;
                           hyperLink.borderStyle = gBorderStyle;
                           if (hyperLink.isValid) {
                                //$.writeln("Cross-reference - " + sourceName + " -- Ok");
                                if (gSet.checkBoxValue) WriteToFile(((hyperLinkCounter < 10) ? (" " + hyperLinkCounter) : hyperLinkCounter) + " - Cross-reference - " + sourceName + " -- Ok\n");
                                hyperLinkCounter++;
                           }
                           
                           try{
                                //$.writeln("1 - " + gDoc.hyperlinks.length);
                                //$.writeln("2 - " + gDoc.hyperlinks.itemByName(sourceName).isValid);
                                hyperLink.name = sourceName;
                           }
                           catch(e) {
                                $.writeln(" - " + e);
                           }
                      }
                      else {
                           $.writeln(" - parDest - " + sourceName + " - is Not Valid");
                      }
                      sourceCounter++;
                 }
            
            }
            //--------------------------------------------------------------------------------------------------------------------------------------------------------
            function ErrorExit(error, icon) {
                 alert(error, gScriptName + " - " + gScriptVersion, icon);
                 exit();
            }
            //--------------------------------------------------------------------------------------------------------------------------------------------------------
            function WriteToFile(text) {
                 //$.writeln("text = " + text);
                 file = new File("~/Desktop/Create X-refs Report.txt");
                 if (file.exists) {
                      file.open("e");
                      file.seek(0, 2);
                 }
                 else {
                      file.open("w");
                      file.encoding = "UTF-8";
                 }
                 file.write(text); 
                 file.close();
            }
            //--------------------------------------------------------------------------------------------------------------------------------------------------------
            function GetDate() {
                 var date = new Date();
                 if ((date.getYear() - 100) < 10) {
                      var year = "0" + new String((date.getYear() - 100));
                 } else {
                      var year = new String ((date.getYear() - 100));
                 }
                 var dateString = (date.getMonth() + 1) + "/" + date.getDate() + "/" + year + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                 return dateString;
             }
            //--------------------------------------------------------------------------------------------------------------------------------------------------------
            function GetList() {
                 var list = [];
                 app.findGrepPreferences = app.changeGrepPreferences = NothingEnum.nothing;
                 app.findGrepPreferences.findWhat = ".+";
                 app.findGrepPreferences.appliedParagraphStyle = gDoc.paragraphStyles.item("H2");
                 var finds = gDoc.findGrep();
                 
                 if (finds.length > 0) {
                      for (var i = 0; i < finds.length; i++) {
                           if (finds[i].constructor.name != "Character") {
                                //$.writeln(i + " - " + finds[i].contents);
                                list.push(finds[i].contents);
                           }
                      }
            
                      InsertList(list.join(" | "));
                 }
            }
            //--------------------------------------------------------------------------------------------------------------------------------------------------------
            function InsertList(list) {
                 var header;
                 app.findGrepPreferences = app.changeGrepPreferences = NothingEnum.nothing;
                 app.findGrepPreferences.findWhat = ".+";
                 app.findGrepPreferences.appliedParagraphStyle = gDoc.paragraphStyles.item("H1");
                 var finds = gDoc.findGrep();
                 
                 if (finds.length > 0) {
                      for (var i = 0; i < finds.length; i++) {
                           if (finds[i].constructor.name != "Character") {
                                //$.writeln(i + " - H1 - " + finds[i].contents);
                                header = finds[i];
                                header.insertionPoints[0].contents = list + "\r";
                                gStory.paragraphs[0].appliedParagraphStyle = gDoc.paragraphStyles.item("tx1");
                           }
                      }
                      
                 }
            }
            //--------------------------------------------------------------------------------------------------------------------------------------------------------
            function GetItemFromCollection(label, collection) {
                 for (var i = 0; i < collection.length; i++) {
                      if (label == collection[i].label) return collection[i];
                 }
                 return null;
            }
            //--------------------------------------------------------------------------------------------------------------------------------------------------------
            function GetFileNameOnly(fileName) {
                 var string = "";
                 var result = fileName.lastIndexOf(".");
                 if (result == -1) {
                      string = fileName;
                 }
                 else {
                      string = fileName.substr(0, result);
                 }
                 return string;
            }
            //--------------------------------------------------------------------------------------------------------------
            function CreateDialog() {
                 var crossRefFormats = ["Full Paragraph & Page Number", "Full Paragraph", "Paragraph Text & Page Number", "Paragraph Text", "Paragraph Number & Page Number", "Paragraph Number", "Text Anchor Name & Page Number", "Text Anchor Name", "Page Number"];
                 var typeList = ["Visible Rectangle", "Invisible Rectangle"];
                 var highlightList = ["None", "Invert", "Outline", "Inset"];
                 var widthList = ["Thin", "Medium", "Thick"];
                 var styleList = ["Solid", "Dashed"];
            
                 var dialog = new Window("dialog", gScriptName + " - " + gScriptVersion);
                 dialog.orientation = "column";
                 dialog.alignChildren = "fill";
                 
                 var xrefPanel = dialog.add("panel", undefined, "Cross-Reference Format");
                 xrefPanel.orientation = "column";
                 xrefPanel.alignChildren = "right";
                 
                 var group1 = xrefPanel.add("group");
                 group1.orientation = "row";
                 var stTxt1 = group1.add("statictext", undefined, "Format:");
                 var dropDownList1 = group1.add("dropdownlist", undefined, crossRefFormats);
                 dropDownList1.selection = gSet.dll1Sel;
                 
                 var panel = dialog.add("panel", undefined, "Appearance");
                 panel.orientation = "row";
                 
                 var leftGroup = panel.add("group");
                 leftGroup.orientation = "column";
                 leftGroup.alignChildren = "right";
                 
                 var rightGroup = panel.add("group");
                 rightGroup.orientation = "column";
                 rightGroup.alignChildren = "right";
                      
                 var group2 = leftGroup.add("group");
                 group2.orientation = "row";
                 var stTxt2 = group2.add("statictext", undefined, "Type:");
                 stTxt2.justify = "right";
                 var dropDownList2 = group2.add("dropdownlist", undefined, typeList);
                 dropDownList2.selection = gSet.dll2Sel;
                 dropDownList2.onChange = TypeOnChange;
            
                 var group3 = leftGroup.add("group");
                 group3.orientation = "row";
                 var stTxt3 = group3.add("statictext", undefined, "Highlight:");
                 stTxt3.justify = "right";
                 var dropDownList3 = group3.add("dropdownlist", undefined, highlightList);
                 dropDownList3.selection = gSet.dll3Sel;
                 
                 var group4 = leftGroup.add("group");
                 group4.orientation = "row";
                 var stTxt4 = group4.add("statictext", undefined, "Colour:");
                 stTxt4.justify = "right";
                 var dropDownList4 = group4.add("dropdownlist", undefined, gBorderColDesList);
                 dropDownList4.selection = gSet.dll4Sel;
            
                 var group5 = rightGroup.add("group");
                 group5.orientation = "row";
                 var stTxt5 = group5.add("statictext", undefined, "Width:");
                 stTxt5.justify = "right";
                 var dropDownList5 = group5.add("dropdownlist", undefined, widthList);
                 dropDownList5.selection = gSet.dll5Sel;
                 
                 var group6 = rightGroup.add("group");
                 group6.orientation = "row";
                 var stTxt6 = group6.add("statictext", undefined, "Style:");
                 stTxt6.justify = "right";
                 var dropDownList6 = group6.add("dropdownlist", undefined, styleList);
                 dropDownList6.selection = gSet.dll6Sel;
                 
                 var checkBox = dialog.add("checkbox", undefined, "Create a log file");
                 checkBox.value = gSet.checkBoxValue;
                 
                 var okCancelGroup = dialog.add("group");
                 okCancelGroup.orientation = "row";
                 okCancelGroup.alignment = "center";
                 var okBtn = okCancelGroup.add("button", undefined, "Ok", {name:"ok"});
                 var cancelBtn = okCancelGroup.add("button", undefined, "Cancel", {name:"cancel"});
                 
                 if (gSet.dll2Sel == 1) {
                      dropDownList4.enabled = false;
                      dropDownList5.enabled = false;
                      dropDownList6.enabled = false;
                      stTxt4.enabled = false;
                      stTxt5.enabled = false;
                      stTxt6.enabled = false;
                 }
                 
                 function TypeOnChange() {
                      if (this.selection.index == 0) {
                           dropDownList4.enabled = true;
                           dropDownList5.enabled = true;
                           dropDownList6.enabled = true;
                           stTxt4.enabled = true;
                           stTxt5.enabled = true;
                           stTxt6.enabled = true;
                      }
                      else if (this.selection.index == 1) {
                           dropDownList4.enabled = false;
                           dropDownList5.enabled = false;
                           dropDownList6.enabled = false;
                           stTxt4.enabled = false;
                           stTxt5.enabled = false;
                           stTxt6.enabled = false;
                      }
                 }
                 
                 var showDialog = dialog.show();
                 
                 if (showDialog== 1) {
                      gSet.dll1Sel = dropDownList1.selection.index;
                      gSet.dll2Sel = dropDownList2.selection.index;
                      gSet.dll3Sel = dropDownList3.selection.index;
                      gSet.dll4Sel = dropDownList4.selection.index;          
                      gSet.dll5Sel = dropDownList5.selection.index;
                      gSet.dll6Sel = dropDownList6.selection.index;
                      gSet.checkBoxValue = checkBox.value;
                      app.insertLabel("Kas_" + gScriptName + gScriptVersion, gSet.toSource());
                      Main();
                 }
            }
            //--------------------------------------------------------------------------------------------------------------
            function GetSettings() {
                 var set = eval(app.extractLabel("Kas_" + gScriptName + gScriptVersion));
                 if (set == undefined) {
                      set = { dll1Sel:1, dll2Sel:1, dll3Sel:0, dll4Sel:0, dll5Sel:0, dll6Sel:0, checkBoxValue:false }
                 }
                 return set;
            }
            //--------------------------------------------------------------------------------------------------------------
            
            • 3. Re: Adding cross reference with find text
              cotcodac Level 1

              Hi

              I learn by using samples found here on this forum. Unfortunately I cant find a simple  example on adding a cross-reference. I found one that links to another file, with very helpful input from Peter Kahrel, I just cant get it to work for me. He mentions at some point that you can reference to an anchor or a paragraph.

              This is my code: (TF is a textframe selected)

               

               

              -------------------------------------------------------------------

              app.findGrepPreferences = app.changeGrepPreferences = null;
               app.findGrepPreferences.appliedParagraphStyle = "_0_body";
               app.findGrepPreferences.findWhat = tf.parentStory.paragraphs.item(0).contents;
              
               found = app.findGrep();
              
              
              if (found.length > 0)
              
              target_text = found[0].paragraphs[0];
              
              
              myDoc.hyperlinkTextDestinations.add(target_text, {name: 'myAnchor2'});
              
                  
              target_text = myDoc.hyperlinkTextDestinations.item('myAnchor2').destinationText;
              destination = myDoc.paragraphDestinations.add (target_text);
              
              // Create a cross-reference
              source_text = tf.insertionPoints[-1];
              xRefForm = myDoc.crossReferenceFormats.item("Page Number");
              source = myDoc.crossReferenceSources.add (source_text, xRefForm);
              
              myDoc.hyperlinks.add (source, destination);
              

               

               

              I have two problems with this script:

              1. How do I make it simpler, without using anchors, referencing to paragraph directly.

              2. This script works by adding the page number of the found text at the end of the textframe selected. As soon as I change the line

              source_text = tf.insertionPoints[-1]; to anything else it give me an error "The object you have chosen is already in use by another hiperlink". I want to insert the page number at the end of the first paragraph in the TF.

               

              Kassians script is a bit too complex for me...

              Thank you.