19 Replies Latest reply on Dec 4, 2012 6:00 AM by Harbs.

    Where are txt.characters[-1] etc documented?

    SLTyPete Level 1

      I'm continuing to explore what is needed to solve my challenge.

       

      I've seen examples using things like:

       

         txt.characters[-1] -- apparently refers to the last character in something

        txt.characters[-2] -- no idea what this is

       

      Heeelp! Where are these kinds of things documented? I obviously need a tutorial on selections, ranges, and conversion between different ways of pointing at places in a document.

       

      Thanks muchly,

      Pete

        • 1. Re: Where are txt.characters[-1] etc documented?
          Kasyan Servetsky Level 5

          Where are these kinds of things documented?

          Scripting InDesign CS3/4 with JavaScript by Peter Kahrel. See "Collections of Objects" on pages 12-13

           

          In brief, positive numbers refer to the items in a collection from the beginning:

          txt.characters[0] -- the 1st (the same as txt.characters.firstItem() but the latter works much slower so avoid using it)

          txt.characters[1] -- the 2nd

          and so on

           

          negative -- from the end:

          txt.characters[-1] -- the last (the same as txt.characters.lastItem() but the latter works much slower)

          txt.characters[-2] -- the 2nd from the end

          and so on

           

          Here is a list of resources that might be useful for you.

          • 2. Re: Where are txt.characters[-1] etc documented?
            [Jongware] Most Valuable Participant

            That's weird -- it seems this is not mentioned anywhere in Adobe's scripting resources, except for a single example in the CS6 Scripting Tutorial:

             

            //Display a standard open file dialog box to select a text file.
            var myTextFile = File.openDialog("Choose a text file");
            //If a text file was selected, and if you didn't press Cancel,
            //place the text file at the first insertion point after the headline.
            if((myTextFile != "")&&(myTextFile != null)){
            myTextFrame.insertionPoints.item(-1).place(myTextFile);
            }
            

             

            where it's not commented any more verbose than "the first insertion point after the headline" without going any deeper into the meaning of "-1".

             

            [Edit] Oh, it gets used in the Javascript Scripting Guide as well;

             

            //Now add text at the end of the text frame.
            myTextFrame3.insertionPoints.item(-1).contents = ..
            

             

            -- still without any further description.

             

            [Further edit] .. except for this oblique line in "Referring to layers by layer index":

             

            Note that you can use negative numbers to refer to the layers in the layers collection of a document. Layer -1 refers to the last (bottom) layer in the collection.

            • 3. Re: Where are txt.characters[-1] etc documented?
              SLTyPete Level 1

              Thanks!

               

              As far as I can tell, here are some related bits. Please tell me if I've understood these correctly:

               

              • genericMultiArray[n] is the same as genericMultiArray.item(n)
              • 0 is always the first element
              • array.length is the number of elements in an array (normal javascript) but not everything one might expect has a length property.
              • textObject.index == storyObject.index == the character offset in the story (starting at zero?)
                but
                charObject.index is one-based (?) offset within an enclosing text string
              • object.hasOwnProperty(propname) is a good way to test for presence of propname in a "fake associative array" (which is actually an object with unique property names... must be careful to use only valid names)
              • (Added 12/2/2012) Normally but not always, scripting is limited to functionality that's available in the user interface. In other words, normally one can only script functions that can be accomplished in the regular user interface. There are ver few exceptions to this.

               

              As you can imagine, after spending $$$ on a product, it sure would be nice if these basic elements of the scripting language were documented and/or tutorial'd somewhere

               

              As an experienced developer but total noob to InDesign Scripting, I would be glad to make this part of my contribution to the community. I will try hard to record the things that are opaque to noobs... and experienced folks find so obvious. (It's called "The Curse of Knowledge" in one of my favorite books -- Made To Stick)

               

              I'll start another thread with my next question.

              • 4. Re: Where are txt.characters[-1] etc documented?
                Peter Kahrel Adobe Community Professional & MVP

                > genericMultiArray[n] is the same as genericMultiArray.item(n)

                 

                In collections, yes, in arrays, no. Example:

                 

                myFrames = myDoc.textFrames;

                myFrames[n] == myFrames.item(n) // true: myFrames is a collection

                 

                myFrames = myStory.textContainers;

                myFrames[n] == myFrames.item(n)  // error: textContainers is an array

                 

                > 0 is always the first element

                 

                Correct. Actually 'The first element is 0' would be better.

                 

                > array.length is the number of elements in an array (normal javascript) but not everything one might expect has a length property.

                 

                Not sure what you mean here.

                 

                > textObject.index == storyObject.index == the character offset in the story (starting at zero?)

                > but

                > charObject.index is one-based (?) offset within an enclosing text string

                 

                textObject.index is the index/position of the textObject in its parent story. storyObject.index is the index of myStory in the document. A charObject is a textObject, and its index is its position in its parent story.

                What do you mean by 'one-based offset'?

                 

                > object.hasOwnProperty(propname) is a good way to test for presence of propname in a "fake associative array"

                 

                Correct.

                 

                > Normally but not always, scripting is limited to functionality that's available in the user interface. In other words, normally one can only script functions that can be accomplished in the regular user interface. There are ver few exceptions to this.

                 

                Wrong. There are many, many, exceptions to this. There are hordes of scripts out there that do things that you couldn't do in the UI. Sorters, database functions, etc. You can extend the functionality of footnotes, endnotes, indexes, tables.

                 

                > it sure would be nice if these basic elements of the scripting language were documented and/or tutorial'd somewhere

                 

                Don't confuse general JavaScript features with InDesign-specific function. E.g.

                object.hasOwnProperty(propname) is a general JS function.

                 

                 

                Peter

                • 5. Re: Where are txt.characters[-1] etc documented?
                  SLTyPete Level 1

                  Thanks for the corrections, Peter. A few quick responses...

                   

                  You're not sure what I meant about *.length occasionally being missing. I could easily be wrong but I believe as I wandered through various tutorials and docs, sometimes I was surprised to find that certain situations there's no "length" property when I would have expected it, at least as a noob

                   

                  charObject -- on further inspection I was just confused. It looks nice and straightforward: *.index is the offset in the parentStory, period. Quite nice! Possibly my confusion came from buggy samples "out there"... or perhaps did the object model get cleaned up between CS and CS2, and/or CS3 -> CS4?

                   

                  My statement about script capabilities is/was perhaps pedantic and quite possibly very very wrong. What I am thinking is that 99% of scriptable actions are simply a (fast, ordered, logic-driven, maybe even external data-driven etc) sequence of actions and settings already available in the UI. First, a couple of potential examples, then a couple of examples that illustrate what I believe are real scripting limitations because of this:

                  * "Sorting" for example is simply rearranging things automatically... could painfully be done by hand in the UI.

                  * Database functions -- are there none in the user interface?

                   

                  Certainly it is true that a script can ask for additional information from the user or an external file. But when it comes to InDD related functionality, my starting place will normally be what the UI offers. For example:

                  * I would love to do regexp/wildcard searches for paragraph styles. But AFAIK the UI only supports regexp on text not styles. And so likewise with script.

                  * I would love to have context-driven style->tag mapping (use tag X.A for style A within page type X, and tag Y.A for style A within page type Y), attributes in style->tag maps, etc. But those are not available in the UI and hence not in scripting.

                   

                  I can in theory put those pieces together via a complex script, but my starting place will normally be limited to what the UI offers, plus any additional javascript constructs.

                   

                  A very nice exception to the above is the discovery of override highlighting. That's a feature not exposed in the UI but available via scripting. Are there really a ton of such things? I'd love to see a list somewhere

                   

                  Thanks again... VERY VERY much. People here are incredibly helpful. I hope to return the favor as I learn more...

                   

                  Blessings,

                  Pete

                  • 6. Re: Where are txt.characters[-1] etc documented?
                    Laubender Adobe Community Professional & MVP

                    A very nice exception to the above is the discovery of override highlighting. That's a feature not exposed in the UI but available via scripting. Are there really a ton of such things? I'd love to see a list somewhere

                    @Pete – not a ton, but quite a few ;-)
                    Most of us scripters found out by experimenting and reading the documentation from A to Z ("Cough!")…

                     

                    One example what you cannot do without scripting (it might be not a useful one for you):
                    You can construct a Group with only ONE element.

                     

                    Take a Group object in the UI, select one of the two objects inside the group and run this code:

                     

                    app.selection[0].remove();
                    

                     

                    The result is an object which you never are able to get in the UI. If you remove one object of a two-object group, the groupness of the one object will simply vanish.

                     

                    And for the [-1] notation in arrays or collections:
                    Sometimes, I cannot provide an example ad hoc, [-1] will fail to address the last object.

                    Alternatively I used the lengthy [objects.length-1] notation and that worked instead.

                     

                    Uwe

                    • 7. Re: Where are txt.characters[-1] etc documented?
                      Peter Kahrel Adobe Community Professional & MVP

                      > I was surprised to find that certain situations there's no "length" property when I would have expected it

                       

                      Can you give some examples?

                       

                      > perhaps did the object model get cleaned up between CS and CS2, and/or CS3 -> CS4?

                       

                      I don't think so.

                       

                      > What I am thinking is that 99% of scriptable actions are simply a sequence of actions and settings already available in the UI.

                       

                      It's a bit more complicated than that (and that figure would be lower than 99%). Scriptable actions are limited to what InDesign has to offer. That not all those actions are exposed in the UI (such as showing override highlighting) follows by definition, but scripting is more than executing actions. Those actions can be combined in ways that aren't possible in the UI. For example, InDesign doesn't have paragraph frames, but it's easy to use existing ID functionality (graphic lines) to add paragraph-frame functionality by script. Database functions aren't present in the UI (discounting data merge, which is), but you can script them.

                       

                      > I would love to do regexp/wildcard searches for paragraph styles.

                       

                      Could you elaborate? ID's regexp searches are pretty good, and you can confine searches to certain paragraph styles (though unfortunately not to groups of paragraph styles -- not in the UI anyway) and you can apply paragraph style using regexps.

                       

                      > But those are not available in the UI and hence not in scripting.

                       

                      This is a big mistake: to assume that if it's not in the interface you can't script it. To earlier example could be added that spreadsheet functionality is not present in InDesign, but it's possible to script it. And it's not even that difficult. Jongware, among several others, has shown scripts that do amazing things such as creating an Open Type font from a character drawn in InDesign and his wondrous Spirograph (http://forums.adobe.com/thread/668082). His What-the-Grep should be built into InDesign's interface. Likewise Marc Autret (www.indiscripts.com) has written numerous articles on what you can script which is not available in the UI (showing override highlighting is one of his).

                       

                      > A very nice exception to the above is the discovery of override highlighting. That's a feature not exposed in the UI but available via scripting. Are there really a ton of such things? I'd love to see a list somewhere

                       

                      Not a ton, but there are some important ones. I've sometimes thought that maybe a list should be compiled of features present in the scripting DOM which aren't exposed in the interface. Here's a beginning (there must be more):

                       

                      = InDesign has full right-to-left functionality which can be applied by scripts but which remain invisible in the interface. Harbs's tools are based on that scripting functionality.

                      = Somewhat relatedly, InDesign can be used to set Japanese, Chinese and other languages vertically. Full support through scripting, not available in the UI.

                      = Watermark functionality is there. Gerald Singelmann has written a script to use that functionality (http://indesign-faq.de/de/wasserzeichen).

                       

                      Anyway, in general I think you shouldn't think that in scripting you're confined to what the UI has to offer.

                       

                      Peter

                      • 8. Re: Where are txt.characters[-1] etc documented?
                        Peter Kahrel Adobe Community Professional & MVP

                        Uwe,

                         

                        >Sometimes, I cannot provide an example ad hoc, [-1] will fail to address the last object. Alternatively I used the lengthy [objects.length-1] notation and that worked instead.

                         

                        [-1] doesn't work on arrays, [objects.length-1] does. We tend to think that properties always return collections, but they don't: textContainers and everything starting with "all" (allTopics, allParagraphStyles, allGraphics, etc) return arrays, not containers.

                         

                        Peter

                        • 9. Re: Where are txt.characters[-1] etc documented?
                          Laubender Adobe Community Professional & MVP

                          Thanks Peter for clarification.
                          I wasn't aware of that fact. Now it's overall clear to me…

                           

                          If I stumbled in my scripting work over that, I automatically switched to the [objects.length-1] notation.

                           

                          Uwe

                          • 10. Re: Where are txt.characters[-1] etc documented?
                            Vamitul Level 4

                             

                            * I would love to do regexp/wildcard searches for paragraph styles. But AFAIK the UI only supports regexp on text not styles. And so likewise with script.

                             

                             

                            if by that you mean something: search for all text that has a paragraph style applied whose name starts with an "A", has 3 more letters and a digit (A\l{3}\d), it's a trivial script to do. I think i already have it somewhere.

                            • 11. Re: Where are txt.characters[-1] etc documented?
                              SLTyPete Level 1

                              A helpful discussion! Thanks much everyone.

                               

                              OK, I will revise my statement as follows:

                               

                              • Generally, it's a good idea to assume that the starting place for script actions is to build from things that are possible in the user interface
                              • There is a growing list of additional known functionality that's only available via scripting. This forum is one of the best places to discover and/or ask about such things. We're beginning to get organized on cataloging such extended functionality.
                              • If you need something beyond the user interface and beyond what others have already discovered, be prepared to spend some signficant time experimenting!

                               

                              That Spirograph is VERY cool. Brings back memories

                               

                              Further explanation of wildcard paragraph style searching:

                              • One can search for text regexp, ie (foo|bar) or foo.*
                              • And one can search for a paragraph style in the context of a regexp, ie find foo.* in the context of paragraph style "Quote"
                              • But one can't use a regexp in the paragraph style name in the search, ie find foo in the context of paragraph style Quote.*

                              I agree ID's regexp searching is more than just pretty good; how many word processors allow grep searching combined with such powerful format search/replace!

                               

                              Finally before I start my real world day, note the bold unresolved questions and I'm-pretty-sure-this-is-wrong facts in this newly revised version of

                               

                              A Few Not-So-Obvious InDesign Scripting Basics

                              With thanks to many contributors of the InDesign Scripting Forum, including Peter Kahrel, Jongware, Kasyan Servetsky and more

                               

                              • Be aware of the similarities and differences between collections and arrays, such as:
                                • Both have a *.length property
                                • Both allow referring to the first element as objectName[0] and the last element as objectName[objectName.length-1]
                                • Collections allow negative "index" references such as objectName[-1] and objectName[-2] (last and just-before last); arrays do not
                                • Collections allow both objectName[propertyName] and objectName.item(propertyName) where the latter is actually a built-in function that scans the properties list.
                                  • Note that "propertyName" can also be an "index" into the Nth item in the collection as above
                                  • (I'm sure there must be a past discussion here of which one is faster and which is preferred when...)
                                • Array examples: textContainers and everything starting with "all" (allTopics, allCellStyles, allCharacterStyles,allParagraphStyles, allGraphics, etc)
                                • Collection examples: *.articles, *.stories, *.spreads,  *.cellStyles, *.characterStyles, *.paragraphStyles
                                  • Why is there both document.allCellStyles and document.cellStyles etc???
                              • object.length is the number of elements in an array or collection
                              • textObject.index == charObject.index == the integer character offset in the parent Story.  storyObject.index == the character offset in the story's parent document. Both are zero-based
                                • storyObject.index does NOT appear to be char offset in parent document? It starts at zero on a page in the middle of a document???
                              • object.hasOwnProperty(propname) is a good way to test for presence of propname in a "fake associative array" (which is actually an object with unique property names... must be careful to use only valid names)

                               

                              Blessings,

                              Pete

                              • 12. Re: Where are txt.characters[-1] etc documented?
                                Peter Kahrel Adobe Community Professional & MVP

                                > But one can't use a regexp in the paragraph style name in the search, ie find foo in the context of paragraph style Quote.*

                                 

                                found = app.documents[0].findGrep(); // or .findText()

                                for (i = 0; i < found.length; i++)

                                   if (found[i].appliedParagraphStyle.name.search (/some regexp/) > -1)

                                      // do something

                                 

                                > Why is there both document.allCellStyles and document.cellStyles

                                 

                                document.cellStyles returns a collection of first-level cell styles, i.e. it ignores styles in style groups.

                                document.allCellStyles returns an array of all cell styles, including those in style groups.

                                 

                                > storyObject.index does NOT appear to be char offset in parent document? It starts at zero on a page in the middle of a document?

                                 

                                Stories are not characters. They have no offset. In a way, a story's offset is the offset of its first character.

                                 

                                Peter

                                • 13. Re: Where are txt.characters[-1] etc documented?
                                  Vamitul Level 4

                                  while on the most basic usage level array and collections are similar, "on the inside" they are quite different things.

                                  a lot of info you can find in Mark's blog:

                                  http://www.indiscripts.com/post/2010/06/on-everyitem-part-1

                                  • 14. Re: Where are txt.characters[-1] etc documented?
                                    SLTyPete Level 1

                                    WOW, Peter, we're hitting on all cylinders

                                     

                                    Peter Kahrel wrote:

                                     

                                    > But one can't use a regexp in the paragraph style name in the search, ie find foo in the context of paragraph style Quote.*

                                     

                                    found = app.documents[0].findGrep(); // or .findText()

                                    for (i = 0; i < found.length; i++)

                                       if (found[i].appliedParagraphStyle.name.search (/some regexp/) > -1)

                                          // do something

                                    Great solution and demonstrates how to nicely combine ID's regexp capabilities with builtin javascript regexp.

                                    Peter Kahrel wrote:

                                    > Why is there both document.allCellStyles and document.cellStyles

                                     

                                    document.cellStyles returns a collection of first-level cell styles, i.e. it ignores styles in style groups.

                                    document.allCellStyles returns an array of all cell styles, including those in style groups.

                                    If only the documentation said that. For cellStyles it just says "a collection of cell styles." Thanks!

                                     

                                    Peter Kahrel wrote:

                                    > storyObject.index does NOT appear to be char offset in parent document? It starts at zero on a page in the middle of a document?

                                     

                                    Stories are not characters. They have no offset. In a way, a story's offset is the offset of its first character.

                                    This makes no sense in multiple ways:

                                    1) AFAIK (from what has been said in this thread), the offset of any character in a story is known with respect to the story itself. This provides no context for content in the overall document.

                                    2) Up above you wrote "storyObject.index is the index of myStory in the document." If the index is always zero, what did you mean?

                                    3) How can we identify the position of a story (and its characters) in a document?

                                    • 15. Re: Where are txt.characters[-1] etc documented?
                                      SLTyPete Level 1

                                      Wow, Vamitul, that link is hugely helpful. THANKS!

                                      • 16. Re: Where are txt.characters[-1] etc documented?
                                        Peter Kahrel Adobe Community Professional & MVP

                                        > 1) AFAIK (from what has been said in this thread), the offset of any character in a story is known with respect to the story itself. This provides no context for content in the overall document.

                                         

                                        The position of a character in a document is the page on which the character's containing text frame is:

                                         

                                        myCharacter.parentTextframes[0].parentPage

                                         

                                        returns the page that the character is on (can be a bit more complicated).

                                         

                                        > 2) Up above you wrote "storyObject.index is the index of myStory in the document." If the index is always zero, what did you mean?

                                         

                                        That quote doesn't mean that the index is always zero. Only the first story's index is zero. The second story's index is 1, etc.

                                         

                                        3) How can we identify the position of a story (and its characters) in a document?

                                         

                                        Determine the pages on which the story's textcontainers are:

                                         

                                        storyStart = story.textContainers[0].parentPage

                                        storyEnd = story.textContainers.pop().parentPage

                                         

                                        Peter

                                        • 17. Re: Where are txt.characters[-1] etc documented?
                                          SLTyPete Level 1

                                          Peter Kahrel wrote:

                                           

                                          > 2) Up above you wrote "storyObject.index is the index of myStory in the document." If the index is always zero, what did you mean?

                                           

                                          That quote doesn't mean that the index is always zero. Only the first story's index is zero. The second story's index is 1, etc.

                                          Ohhhhh. It's not a character index. It is a "story" index. I read it as "storyObject.index is the (character) index of myStory in the document. You're saying it is a completely different kind of index...

                                           

                                          Thank you, Peter.

                                           

                                          I am not certain, but I think I could now create the equivalent diagram to the web javascript web developer "Display ID Details". Now if only that could be a live overlay over an InDD document!!!

                                          • 18. Re: Where are txt.characters[-1] etc documented?
                                            Peter Kahrel Adobe Community Professional & MVP

                                            > Now if only that could be a live overlay over an InDD document!

                                             

                                            Script it! 

                                             

                                            Peter

                                            • 19. Re: Where are txt.characters[-1] etc documented?
                                              Harbs. Level 6

                                              If you want to know what the index property refers to, check the parent property of the object. It's generally the index within its parent.