16 Replies Latest reply on Jan 4, 2017 4:58 AM by Kasyan Servetsky

    Adding hyperlinks and text anchors using Grep

    JulianFT Level 1

      Dear all,

       

      I've been trying to add both a hyperlink text source and destination withing my document using Grep, but I can't seem to get it right. I'm looking find the source text which has the paragraph style "1HD" and starts with the word "Historical", then turn that into the source text for the hyperlink. Second, I'd like the text "References" later on to become the text anchor for the link destination. As a reference, here's what's defined:

       

      var myHeader = app.findGrepPreferences.appliedParagraphStyle = "1HD";
      var myHeader = app.findGrepPreferences.findWhat = "Historical \w*";
      

       

      as well as

       

      var myAnchor = app.findGrepPreferences.appliedParagraphStyle = "";
      var myAnchor = app.findGrepPreferences.findWhat = "References";
      

       

      I've been experimenting with any information I could get my hands on online, but I always seem to get one error or another. Any directions would be greatly appreciated!

       

      Kind regards and thanks in advance,

       

      Julian

        • 1. Re: Adding hyperlinks and text anchors using Grep
          JulianFT Level 1

          Anyone who can nudge me in the right direction? As far as I can assess this shouldn't be too complicated, but frustratingly, I just can't seem to get it right. Much appreciated!

          • 2. Re: Adding hyperlinks and text anchors using Grep
            JulianFT Level 1

            So I've been messing around with this some more, but after having stored the GREP search in a variable and then attempting to add a hyperlink to it, all I get is the following message:

            "Invalid value for parameter 'hyperlinkSource' of method 'add'. Expected HyperlinkTextSource or CrossReferenceSource, but received InsertionPoint." I get the idea that not the result of my search is assigned to the variable, but rather something else. Could someone please confirm or explain?

            • 3. Re: Adding hyperlinks and text anchors using Grep
              Laubender Adobe Community Professional & MVP

              @Julian – as you can see in the DOM documentation, you cannot add a hyperlink to text. You can add a hyperlink to a document with the add() method:

               

              Adobe InDesign CS6 (8.0) Object Model JS: Hyperlink

              Adobe InDesign CS6 (8.0) Object Model JS: Hyperlinks

               

              The add() method has three arguments. None of them is optional:


              1. Source

              2. Destination

              3. Object (for setting the properties with their values of the hyperlink)

               

              Since you want to work with found text the source will be a HyperlinkTextSource that is also added to the document:

               

              Adobe InDesign CS6 (8.0) Object Model JS: HyperlinkTextSource

              Adobe InDesign CS6 (8.0) Object Model JS: HyperlinkTextSources

               

              Same goes with the destination. You could use a destination already in the document or create a new one by adding it to the document. There are various kinds of destinations. You did not tell the destination. So I'm not clear what to suggest here. Look your options up in the DOM documentation:

               

              Adobe InDesign CS6 (8.0) Object Model JS: Table of Contents, Hyperlinks Suite

               

              Or download the chm file version of the documentation at:

               

              Indesign JavaScript Help

               

              Uwe

              • 4. Re: Adding hyperlinks and text anchors using Grep
                JulianFT Level 1

                Dear Uwe,

                 

                first of all, thank you so much for your extensive post!

                 

                I have indeed been trying to add a hyperlink to the document, using the aforementioned GREP search results as a HyperlinkTextSource and HyperlinkTextDestination, respectively - pardon my confusing phrasing. I've tried storing the search results in a variable and then using myDocument.hyperlinkTextSources.add (/hyperLinkTextDestinations) to add them to the document, but whenever I try to use these variables in myDocument.hyperlinks.add I get the error mentioned above. Am I using an incorrect method completely or am I simply making a mistake?

                 

                Thanks in advance,

                 

                Julian

                • 5. Re: Re: Adding hyperlinks and text anchors using Grep
                  Laubender Adobe Community Professional & MVP

                  @Julian – we cannot know. You did not post that part of your script.
                  And your snippets in post #1 are a bit obscure.

                  You are assigning a GREP preference to the variable myHeader and then redefine that same variable to a new value, a GREP expression. ?! That cannot work…

                   

                  Without seeing the full code we cannot help…
                  If you will post it, I suggest you are making comments on every line showing what you think it is supposed to do.

                   

                  Like:

                   

                  //Set the GREP prefs for finding texts formatted with paragraph style named "1HD":
                  var myHeader = app.findGrepPreferences.appliedParagraphStyle = "1HD";
                  

                   

                  Why this variable?

                   

                  In the moment that line is executed, your GREP preferences in the UI of InDesign are populated like this, if the paragraph style is available (sorry, German UI):

                   

                  DefinedGREPprefs.png

                  And then you are overwriting the variable for doing that:

                   

                  DefinedGREPexpression.png

                   

                  What would you like to do with your variable further down the road?

                   

                  Uwe

                  • 6. Re: Adding hyperlinks and text anchors using Grep
                    JulianFT Level 1

                    Right, I think I might see the confusion. The GREP search (the one searching for the 'Historical w*' string with paragraph style '1HD') finds the heading I want to use (I've checked this both manually and by adding a character style to the myHeader variable, which was properly applied to the intended text). Now, I would like use that text (in this case, a heading saying "Historical Background") as a HyperlinkTextSource. It is the search result text I was attempting to store to the variable, not the search preferences itself.

                    • 7. Re: Adding hyperlinks and text anchors using Grep
                      Laubender Adobe Community Professional & MVP

                      @Julian – as I already said: Without posting the full code of your GREP search together with your attempts to create a hyperlink that uses the found texts as the source we can hardly help you…

                       

                      Regarding the error message you get, it seems that you are assigning an insertion point as source instead of a HyperlinkTextSource.sourceText. But since there is no code from your side, I cannot know…

                       

                      Two ways to do this:

                       

                      1. Before adding a new hyperlink to the document you can add a new hyperlinkTextSource and a destination to the document assigned to two different variables. Then using these variables in your add()-method for the hyperlink creation.

                       

                      2. You can add a new hyperlinkTextSource and a approriate destination while using the add()-method for the hyperlink.

                       

                      You cannot do it after adding the hyperlink, because source and destination are required and not optional.

                       

                      Also: you should be aware that you should find a method to make the name of a new hyperlink unique in your document.

                       

                      Uwe

                      • 8. Re: Re: Adding hyperlinks and text anchors using Grep
                        BEGINNER_X Level 3

                        Hi Julian,

                         

                        May the below code helpful,

                         

                        1. Edit the Line 5 as per your request paragraph Style

                         

                        var myDoc = app.activeDocument;
                        app.findGrepPreferences = app.changeGrepPreferences = null;
                        
                        app.findGrepPreferences.findWhat = ".+";
                        app.findGrepPreferences.appliedParagraphStyle = "MN_first";
                        var myFound1 = myDoc.findGrep();
                        
                        count = 0
                        for(k=0; k<myFound1.length; k++)
                        {
                        try{
                            var myFind = myFound1[k];
                            var myHyperlinkSource = app.activeDocument.hyperlinkTextSources.add(myFound1[k])
                            var myHyperlinkURLDestination = app.activeDocument.hyperlinkURLDestinations.add(myFound1[k].contents)
                            var myHyperlink = app.activeDocument.hyperlinks.add(myHyperlinkSource, myHyperlinkURLDestination, {name: myFound1[k].contents+count++})
                            count++
                        }catch(e){}
                        }
                        
                        alert(count/2 + " occurencces is changed")
                        
                        

                         

                         

                        For Text Anchor, use the below code:

                         

                        var myDoc = app.activeDocument;
                        app.findGrepPreferences = app.changeGrepPreferences = null;
                        
                        app.findGrepPreferences.findWhat = ".+";
                        app.findGrepPreferences.appliedParagraphStyle = "MN_first";
                        var myFound1 = myDoc.findGrep();
                        
                        count = 0
                        for(k=0; k<myFound1.length; k++)
                        {
                        try{
                            var myFind = myFound1[k];
                            var myHyperlinkSource = app.activeDocument.hyperlinkTextSources.add(myFound1[k]);
                            var myTextAnchor = app.activeDocument.hyperlinkTextDestinations.add(myFound1[k], {name: myFound1[k].contents });
                            var myHyperlink = app.activeDocument.hyperlinks.add(myHyperlinkSource, myTextAnchor, {name: myFound1[k].contents+count++})
                            count++
                         }catch(e){}
                        }
                        
                        alert(count/2 + " occurencces is changed")
                        

                         

                        Regards

                        Siraj

                        • 9. Re: Re: Adding hyperlinks and text anchors using Grep
                          JulianFT Level 1

                          Sorry to have carried this over the weekend. To both of you, thank you so much for your kind help.

                           

                          @Uwe: you're absolutely right, of course. The main reason I was reluctant to post the full code is because it's horifically multi-purpose, and because of all the experimenting I'd done along the way turned into a near-incomprehensible mess that would most likely only raise more questions. Thanks so much for the guidance though, it was a massive help!

                           

                          @Siraj: worked like an absolute charm, thank you immensely. The 'var myFound1 = myDoc.findGrep()" part is where I went wrong; with this missing link I was finally able to fix it completely. You're a life saver!

                          • 10. Re: Re: Adding hyperlinks and text anchors using Grep
                            johnpredmore

                            Hi I'm having a similar challenge in having to create many cross-references in a script. This base has been great to help me down the right path; I'm just wondering if I can use the same method outlined above but changing the type of Hyperlink from URL to Text Anchor?

                            • 11. Re: Adding hyperlinks and text anchors using Grep
                              keyank99503373

                              I’m trying to add hyperlink for the paragraphs in the document. The script is running very slow and taking more time because the file has more than 1000 occurance.

                               

                              Please advise how to overcome this issue.

                               

                              I have used the below  method

                               

                              Grep to find all paragraphs 

                              • 12. Re: Adding hyperlinks and text anchors using Grep
                                Laubender Adobe Community Professional & MVP

                                Hard to give advice here.
                                The longer a story is, the more paragraphs are visited by a loop advancing through a long, long story, the more time it takes to visit and change text or text formatting.

                                 

                                Btw. What do you mean by "very slow"?
                                How long does it take to work through the 1,000 instances?

                                 

                                Seconds?
                                Minutes?

                                Hours?

                                 

                                A way around all this would be to export to IDML and change the IDML and open it again.

                                But this could have other consequences one does not like:

                                1. Also that takes its time.

                                2. There are some nasty bugs with IDML roundtripping.

                                Even with the same InDesign version.

                                 

                                Or maybe you are able to cut the long stories into shorter ones, run your function on more shorter stories and assemble the pieces later again to one big story.

                                 

                                Regards,
                                Uwe

                                • 13. Re: Adding hyperlinks and text anchors using Grep
                                  keyank99503373 Level 1

                                  I my document have 9000 paragraphs its taking 4 hours to complete the task. First 1000 paragraphs take 1 minutes. after that it's getting very slow complete rest of the paragraphs

                                  • 14. Re: Adding hyperlinks and text anchors using Grep
                                    Vamitul Level 4

                                    After each 1000 paragraphs processed do a myDoc.save(myDoc.fullName).

                                    That will clear indesign's undo stack and result in a nice performance boost.

                                    • 15. Re: Adding hyperlinks and text anchors using Grep
                                      keyank99503373 Level 1

                                      Thanks for this. i will check and revert.

                                      • 16. Re: Adding hyperlinks and text anchors using Grep
                                        Kasyan Servetsky Level 5

                                        Here's how I solved this problem.

                                        In brief, if you already have, say, 10,000 hyperlinks in the document, it would take long -- a couple of minutes -- to create only one hyperlink: no matter if you do this manually in InDesign or by script. And you can do nothing with this: that's the way InDesign works.

                                         

                                        But you can:

                                        • Save the document (by script) after every XXX hyperlinks were created so if InDesign crashes, you won't loose your work
                                        • Process the text by chunks (by selected text) instead of the whole file at once
                                        • Calculate how much time left to the completing the script and display this in the progress bar

                                         

                                        Hope this helps.

                                        — Kas

                                        1 person found this helpful