10 Replies Latest reply: Aug 6, 2012 8:15 AM by uraeus1618 RSS

    Scripting inline styles to text

    uraeus1618 Community Member

      Hello,

      I am having trouble getting my head around the indesign DOM in regards to programmatically (javascript) applying text styles inline and on the fly. By that I mean the text items I want formatted don't exist in the current document at the moment the script is executed. To give an example

      In the current document there is only one textframe called "frame1"

      In the script...

      var str1 = "$";

      var str2 = "19";

      var st3 = "95";

       

      The result I wish to see in the text "frame1" (if written in html) is <sup>$</sup>19<sup>95</sup> All on the one line

       

      I found this post http://forums.adobe.com/message/4547401 Solution 2 maybe how to do it,

       

      myTextFrame = app.selection[0]; // is this necessary? can i use textFrames.itemByName(name)?

      firstInsertionPoint = myTextFrame.insertionPoints[-1].index;

      myTextFrame.contents += "New Text";

      myAddedText = myTextFrame.characters.itemByRange(myTextFrame.insertionPoints[firstInsertionPoint],

      myTextFrame.insertionPoints[-1]);

      // i assume i would apply position.superscript here

      myAddedText.appliedFont = app.fonts.itemByName("Trajan Pro"); // etc.

       

      but I do not understand exactly what it's doing especially with the insertion points.  I have coded Visual Studio Projects for Office Word and the syntax looks kind of familiar but I find indesign documentation too spartan to help me. Grant Gamble's book was very helpful until I wanted to go down this weird path.

       

      I am using indesign 5.5 and ESTK

       

      Thank you in advance

      Anthony

       

      Hi again,

      I tried playing with the above source post solution 1, the move method of the paragraph collection has it's parameter list around the wrong way at least according to indesign 5.5. Has there been a change between versions? Is this the right way of going about this?

      thanks again

        • 1. Re: Scripting inline styles to text
          pkahrel Community Member

          Maybe you shouldn't be bothered with insertionPoints -- depends on what you really want to do. In your case (styling money amounts) it might be easier to fill your frame with text, then using Find/Change to add formatting. Example:

           

          myFrame = app.activeDocument.textFrames.item("frame1");

          myFrame.contents = "$19.95";

           

          app.findGrepPreferences = app.changeGrepPreferences = null;

          app.findGrepPreferences.findWhat = "\\\x{0024}";

          app.changeGrepPreferences.position = Position.superscript;

          myFrame.changeGrep();

           

          Peter

          • 2. Re: Scripting inline styles to text
            uraeus1618 Community Member

            Thanks for your response Peter. I cannot find detailed references to the methods you are using eg findWhat accepts a string, thats all. Why the hex notation (unicode?)

             

            If I wanted the to superscript the 95 cents part and performed a findwhat what would happen in a case of $95.95?

             

            I am feeling more like an alchemist than programmer here, any meatier references out there?

            Thank you

            • 3. Re: Scripting inline styles to text
              pkahrel Community Member

              The dollar symbol is a special case. With any other character you could have used the literal, e.g. "£" and "¥". But ironically, InDesign's grep has trouble finding the dollar symbol, which is also a metacharacter standing for "end of string". That's why you should search for the dollar symbol's unicode value. In other words, searching "\\$" does not work, but "\\\x{0024}" does.

               

              To superscript just the 95 cents part, you would do search "(?<=\\\x{0024}\\d\\d\\.)\\d\\d", which stands for two digits (\d\d) preceded by dollar-digit-digit-digit-dot (the (?<=. . .) construct stands for 'preceded by').

               

              This, though, matches only two-digit dollar amounts followed by two-digit cents, and you probably want to match single- and triple-dollar amounts too. You found yourself a tough intro into grep, what with InDesign's difficulty finding dollar symbols and Ggrep's general inability to cope with variable-length strings in so-called lookbehinds (the (?<=. . .) constructs). You could do multiple queries:

               

               

              "(?<=\\\x{0024}\\d\\.)\\d\\d"

               

              "(?<=\\\x{0024}\\d\\d\\.)\\d\\d"

               

              "(?<=\\\x{0024}\\d\\d\\d\\.)\\d\\d"

               

              If you feel like an alchemist, join the club. Grep isn't the easiest thing around but that shouldn't discourage you from learning it because it's really very powerful and even a smattering of grep will get you a long way. As to resources, for grep in InDesign you could try http://shop.oreilly.com/product/9780596156015.do

               

              Peter

              • 4. Re: Scripting inline styles to text
                uraeus1618 Community Member

                Interesting, you share the same name as the author of the book

                 

                Thanks for persevering with this.

                in javascript this works

                app.findGrepPreferences = app.changeGrepPreferences = null;

                                            app.findGrepPreferences.findWhat = "\\\x{0024}";

                                            app.changeGrepPreferences.position = Position.superscript;

                                            myFrame.changeGrep();

                // this doesnt

                app.findGrepPreferences = app.changeGrepPreferences = null;

                                            app.findGrepPreferences.findWhat = "(?<=\\\x{0024}\\d\\d)\\d\\d"

                                            app.changeGrepPreferences.position = Position.superscript;

                                            myFrame.changeGrep();

                 

                I plugged (?<=\x{0024}\d\d)\d\d into indesign find change and it selected the 95 part

                There is no decimal point!!

                Since I can calculate the string lengths (these strings are coming from web service) of the price, i can perform string building for the regex. This should work, can't figure on why the last findwhat doesnt match.

                Sincerely

                Anthony

                I got your three books books BTW, trawlling now

                update

                Curious. After a much needed walk over the hills, I ran the script twice in succession. It worked on the already prerended $1995 ie both $ an 95 were superscripted and not rendered on the last run.

                I will need to run the grep after looping through the 'price' variables. I can store the regex in string array as vars are processed, then loop at the end.

                • 5. Re: Scripting inline styles to text
                  pkahrel Community Member

                  > Interesting, you share the same name as the author of the book

                   

                  The cause for much confusion!

                   

                  It's in fact easier in your case not to try to automate the Find/Change panel, so to speak, but to go a different route:

                   

                  app.findGrepPreferences = null;

                  app.findGrepPreferences.findWhat = "\\x{0024}\\d+";

                  found = app.activeDocument.findGrep();

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

                     {

                     found[i].characters[-2].position = Position.superscript;

                     found[i].characters[-1].position = Position.superscript;

                     }

                   

                  Instead of "\\x{0024}\\d+", by the way. you can use \x{0024}\d+/.source, which makes expressions easier to read because there's no need to escape backslashes. It's also easier to transfer grep expressions from a script to the Find/Changedialog and v.v.

                   

                  Not sure what you meant by "I will need to run the grep after looping through the 'price' variables. I can store the regex in string array as vars are processed, then loop at the end."

                   

                  Peter

                  • 6. Re: Scripting inline styles to text
                    uraeus1618 Community Member

                    Hi Peter,

                    Thanks for the head up on

                       found[i].characters[-2].position = Position.superscript;

                       found[i].characters[-1].position = Position.superscript;

                    i didn't know you could do such things

                     

                    As I said, the price is coming in  (web service) as two variables. There is a reason for this. There is some type setting done on the two variables before they are added to the service. For example, size of font. I can calculate the length of the dollar component IF there is one. It maybe zero eg 99 cents. Knowing the length of dollars it can loop appending "\d" 's at the end of each iteration and use this regex in the grep. Works perfectly. Though with above code frag you provided i can do it another way. It's good to have choices!

                     

                    In a all I have written a web app that acts as a front end for indesign "documents/objects/templates/empty square holes i can poke round pegs into" This app acts to constrain data input to fit particular document characteristics such as length of text centered at a particular size to fit nicely in a bounding box within an A4 portrait document. Or A3 or A5 or A6 or landscape. The up shot of this is that the graphics designer stops being a data entry clerk and editor when he recieves a CSV of items to be printed off. He would need to wander thru thousands of these items making sure text didnt spill over background objects or flow outside of document. He would need to manually adjust and call owner of data to re-edit text so it would fit. We calculated he was spending 22-32(time of year) hours a month on this labour that was costing my employer and detracting from what he was employed to do by his company. He hates it. The onus of compisition and constraint was put on the consumer of the printed output. If constraints are violated they cant be submitted.

                     

                    The data for each template consists of one html fragment representing the text areas (divs and clever usage of "data-" attribute prefix), one style sheet for preview as you type, one background image, and one xslt sheet to transform the web service into something indesign script can parse easily and i dont need to shoot myself. I wrote the indesign client using "extendables" http() which gets a list of published batches and he can punch the XML straight into indesin(he can now thanks to you)

                     

                    The app itself is an engine which runs these sheets and creates data input fields, data verification, store to mssql 10 and retrieve for editing and a searchable (searching XML types in tuples BTW )library keyed in on the document type context. There 8 of these contexts so far representing portrait and landscape for A4 A5 A6 and a big A3 6x3 items per page. There is a security layer in asp.net membership and roles which i have tweaked a little

                     

                    It's all done! I need to sit with the GD so we can put the existing document templates into library objects so the script can retrieve them and perform the type of work we have been discussing. The two parties are gobsmacked by the look and consistancy of data styling. The user interface needs some work since  c# puts it together, but i'm not really a designer. Sorry for rabbiting on, I wanted to tell someone who might be the slightest bit interested in what or how i did.

                     

                    Thanks again

                    • 7. Re: Scripting inline styles to text
                      pkahrel Community Member

                      Not at all, interesting story, thank you.

                       

                      Peter

                      • 8. Re: Scripting inline styles to text
                        uraeus1618 Community Member

                        Hey Peter,

                        Is there a way of permanently centering text in a textframe before my script writes to it? The Text tool when selected and placed in the frame brings up the horizontal text alignment buttons. If i click center then add a space and then run the script the first line is centered but subsequent lines are not. I assume the reason being because of how i apply different font sizes to different lines

                        // this represents one line being written

                        var tempFrame = app.activeDocument.textFrames.add();

                        tempFrame.paragraphs[0].appliedFont = app.fonts.itemByName("Komika Axis");

                        tempFrame.paragraphs[0].pointSize = Number(member[i].attribute("size"));

                        var myTextFrame = g.doc.textFrames.itemByName(String(member[i].name()));

                        tempFrame.paragraphs[0].move(LocationOptions.AFTER, myTextFrame.insertionPoints[-1]);

                        var tempFrame = app.activeDocument.textFrames.add();

                        tempFrame.contents = String(tags[j].text());

                        tempFrame.remove();

                         

                        I believe there is way to script it, could you please advise if the above code could be modified to center text horizontally each time a line is written.

                        Many thanks

                        Anthony

                        • 9. Re: Scripting inline styles to text
                          pkahrel Community Member

                          myTextFrame.paragraphs.everyItem().justification = Justification.centerAlign;

                           

                          But you'd probably be better off defining a paragraph style and using that.

                           

                          Peter

                          • 10. Re: Scripting inline styles to text
                            uraeus1618 Community Member

                            Thanks Peter, worked like a charm