12 Replies Latest reply on Nov 27, 2015 2:51 AM by lewis_cooper

    Script Improvement Needed

    lewis_cooper

      Hi Everyone,

       

      I'm hoping someone can help me improve my javascript.

       

      I currently have a script that (inserted below), when executed on selected text, extracts the text, splits it and applies an object style. It works very well but leaves paragraph breaks and forced line break hanging around that I'd really rather not have. See the inserted images for my start state, current results and lastly preferred result.

       

      Does anyone know how I can achieve this? I'm not an experience scripter at all so I don't know where to start!

       

      Many thanks in advance,

      Lewis

       

       

       

       

      if (app.selection.length == 1 && app.selection[0].hasOwnProperty("baseline") && app.selection[0].length > 1) 
      { 
          mObjSt = app.activeDocument.objectStyles.item("Colour Label Grey"); 
          app.selection[0].insertionPoints[0].contents = "\r"; 
          app.findGrepPreferences = app.changeGrepPreferences = null; 
          app.findGrepPreferences.findWhat = "  (\\u)(?=~s)"; 
          app.changeGrepPreferences.changeTo = "\\r\$1"; 
          app.selection[0].changeGrep(); 
          app.findGrepPreferences.findWhat = "\\n\\n\\r"; 
          app.changeGrepPreferences.changeTo = ""; 
          app.selection[0].changeGrep(); 
          app.findGrepPreferences.findWhat = ", "; 
          app.changeGrepPreferences.changeTo = ""; 
          app.selection[0].changeGrep(); 
          p = app.selection[0].parentTextFrames[0]; 
          lh = (p.lines[-1].baseline - p.lines[0].baseline) / (p.lines.length-1); 
          top = app.selection[0].lines[0].baseline - lh; 
          while (app.selection[0].length > 0) 
           { 
            f = app.activeDocument.layoutWindows[0].activePage.textFrames.add ({geometricBounds:[top, p.geometricBounds[3]+2*lh, top+lh, 2*(lh+p.geometricBounds[3])-p.geometricBounds[1] ]}); 
            app.selection[0].lines[0].move (LocationOptions.AFTER, f.texts[0]); 
            top += lh; 
            f.appliedObjectStyle = mObjSt; 
           } 
           p.characters[-1].contents = "";
          
      } else 
      alert ("please select some text to shred"); 
      if (f.lines[-1].contents.indexOf("\r") != -1) f.characters[-1].contents = ""; 
      
      

       

      Screen Shot 2015-11-24 at 20.26.49.png

      Screen Shot 2015-11-24 at 20.29.21.png

       

       

       

      Screen Shot 2015-11-24 at 20.29.25.png

        • 1. Re: Script Improvement Needed
          Loic.Aigon Adobe Community Professional

          Hi,

           

          Unless I am wrong what you are trying to achieve is to isolate the last line in a pseudo table. So you may focus on getting those text patterns like A Washed black. This is what I could recommend :

           

          var main = function(){
          
            var sel, doc, found, n = 0, tf, st, tb, tc = [], gb, w, tfb;
          
            if ( !app.documents.length 
            || app.selection.length!=1
            || !app.selection[0].properties.parentStory ) return;
          
            app.findGrepPreferences = app.changeGrepPreferences = null;
          
            doc = app.activeDocument;
            sel = app.selection[0];
            st = sel.parentStory;
          
            if ( !(sel instanceof  TextFrame) ) {
            if ( !sel.parentTextFrames.length ) return;
            sel = sel.parentTextFrames[0];
            }
          
          
            app.findGrepPreferences.findWhat = "\\u~s\\u[\\l ]+\\l";
            found = st.findGrep();
            n = found.length;
          
            if ( !n ) return;
          
          
            gb = sel.geometricBounds;
            w = Math.abs(gb[3]-gb[1]);
            tfb = sel.visibleBounds;
            tfb[1]+=(w+5);
            tfb[3]+=(w+5);
            tf = sel.parentPage.textFrames.add({visibleBounds:tfb});
            tb = tf.tables.add({bodyRowCount:n, columnCount:1, width:w});
            while ( n-- ) {
            found[n].move(LocationOptions.AT_BEGINNING, tb.cells[n].insertionPoints[0]);
            }
          
          
            tf.fit(FitOptions.FRAME_TO_CONTENT);
          
            app.findGrepPreferences.findWhat = " {2,}";
            app.changeGrepPreferences.changeTo = "";
            st.changeGrep();
          }
          var u;
          app.doScript("main()",u,u,UndoModes.ENTIRE_SCRIPT);
          

           

           

          HTH,

           

          Loïc

          www.ozalto.com

          • 2. Re: Script Improvement Needed
            lewis_cooper Level 1

            Hi Loic.Aigon

             

            Thanks very much for your reply. Your script does a better job of isolating the right elements but it's essential that I'm left with individual text boxes for each line of text. Each text box needs to have the object style 'Colour Label Grey' applied to it as in the original script. So unfortunately the table approach won't work. Any other ideas?

             

            Cheers,

            • 3. Re: Script Improvement Needed
              tpk1982 Level 4

              Hi Lewis,

               

              Use the below script. It is enhanced one of your need.

               

              var the_document = app.documents.item(0);
              // Create a list of paragraph styles
              var list_of_paragraph_styles = the_document.paragraphStyles.everyItem().name;
              
              
              // Create a list of character styles
              var list_of_character_styles = the_document.characterStyles.everyItem().name;
              
              
              // Create a list of object styles
              var list_of_object_styles = the_document.objectStyles.everyItem().name;
              
              // Make dialog box for selecting the styles
              var the_dialog = app.dialogs.add({name:"Create anchored text frames"});
              with(the_dialog.dialogColumns.add()){
                with(dialogRows.add()){
                staticTexts.add({staticLabel:"Make the anchored frames from ..."});
                }
                with(dialogRows.add()){
                staticTexts.add({staticLabel:"This character style:"});
                var find_cstyle = dropdowns.add({stringList:list_of_character_styles, selectedIndex:0});
                }
                with(dialogRows.add()){
                staticTexts.add({staticLabel:"Or this paragraph style:"});
                var find_pstyle = dropdowns.add({stringList:list_of_paragraph_styles, selectedIndex:0});
                }
                with(dialogRows.add()){
                staticTexts.add({staticLabel:"Leave one dropdown unchanged!"});
                }
                dialogRows.add();
                with(dialogRows.add()){
                staticTexts.add({staticLabel:"Delete matches?"});
                var delete_refs = dropdowns.add({stringList:["Yes","No"], selectedIndex:0});
                }
                dialogRows.add();
                with(dialogRows.add()){
                staticTexts.add({staticLabel:"Anchored text frame settings:"});
                }
                with(dialogRows.add()){
                staticTexts.add({staticLabel:"Object style:"});
                var anchor_style = dropdowns.add({stringList:list_of_object_styles, selectedIndex:0});
                }
                with(dialogRows.add()){
                staticTexts.add({staticLabel:"Frame width:"});
                var anchor_width = measurementEditboxes.add({editUnits:MeasurementUnits.MILLIMETERS, editValue:72});
                }
                with(dialogRows.add()){
                staticTexts.add({staticLabel:"Frame height:"});
                var anchor_height = measurementEditboxes.add({editUnits:MeasurementUnits.MILLIMETERS, editValue:72});
                }
              }
              the_dialog.show();
              
              
              // Define the selected styles
              var real_find_cstyle = the_document.characterStyles.item(find_cstyle.selectedIndex);
              var real_find_pstyle = the_document.paragraphStyles.item(find_pstyle.selectedIndex);
              var real_anchor_style = the_document.objectStyles.item(anchor_style.selectedIndex);
              
              // Check if a style is selected
              if(find_cstyle.selectedIndex != 0 || find_pstyle.selectedIndex != 0) {
              
                // Define whether to search for character styles or paragraph styles
                app.findChangeGrepOptions.includeFootnotes = false;
                app.findChangeGrepOptions.includeHiddenLayers = false;
                app.findChangeGrepOptions.includeLockedLayersForFind = false;
                app.findChangeGrepOptions.includeLockedStoriesForFind = false;
                app.findChangeGrepOptions.includeMasterPages = false;
              
                if(find_cstyle.selectedIndex != 0) {
                app.findGrepPreferences = NothingEnum.nothing;
                app.findGrepPreferences.appliedCharacterStyle = real_find_cstyle;
                } else {
                app.findGrepPreferences = NothingEnum.nothing;
                app.findGrepPreferences.appliedParagraphStyle = real_find_pstyle;
                app.findGrepPreferences.findWhat = "^";
                }
              
                // Search the document
                var found_items = the_document.findGrep();
              
              
                myCounter = found_items.length-1;
                do {
                // Select and copy the found text
                var current_item = found_items[myCounter];
              
              
                if(find_pstyle.selectedIndex != 0) {
                var found_text = current_item.paragraphs.firstItem();
                var insertion_character = (found_text.characters.lastItem().index) + 1;
                var check_insertion_character = insertion_character + 1;
                var alt_insertion_character = (found_text.characters.firstItem().index) - 1;
                var the_story = found_text.parentStory;
                app.selection = found_text;
                if(delete_refs.selectedIndex == 0) {
                app.cut();
                } else {
                app.copy();
                }
                } else {
                var found_text = current_item;
                var insertion_character = (found_text.characters.lastItem().index) + 2;
                var check_insertion_character = insertion_character;
                var alt_insertion_character = (found_text.characters.firstItem().index) - 1;
                var the_story = found_text.parentStory;
                app.selection = found_text;
                if(delete_refs.selectedIndex == 0) {
                app.cut();
                } else {
                app.copy();
                }
                }
              
                // Make text frame from selection
                try {
                app.selection = the_story.insertionPoints[check_insertion_character];
                app.selection = the_story.insertionPoints[insertion_character];
                } catch(err) {
                app.selection = the_story.insertionPoints[alt_insertion_character];
                }
              
                var the_anchored_frame = app.selection[0].textFrames.add({geometricBounds:["0","0",anchor_height.editContents,anchor_width.editContents],anchoredObjectSettings:{anchoredPosition: AnchorPosition.ANCHORED}});
                app.selection = the_anchored_frame.insertionPoints[0];
                app.paste();
              
              
                // Apply the object style now to "force apply" paragraph style set in the object style
                if(anchor_style.selectedIndex != 0) {
                the_anchored_frame.appliedObjectStyle = real_anchor_style;
                }
              
                myCounter--;
                } while (myCounter >= 0);
              } else {
                alert("No styles selected!");
              
              

               

               

              Thanks,

              Karthi

              • 4. Re: Script Improvement Needed
                Trevorׅ Adobe Community Professional

                Hi Lewis

                Change line9 from app.findGrepPreferences.findWhat = "\\n\\n\\r";

                to app.findGrepPreferences.findWhat = "\\n";

                Then add after line 17 before the while line add the line app.findGrepPreferences.findWhat = "\\r";

                Then after the top += line add the line f.changeGrep();

                Not test but should work


                HTH


                Trevor



                • 5. Re: Script Improvement Needed
                  Trevorׅ Adobe Community Professional

                  Ok

                  I tested this one.

                  I would write the script very differently myself, I'm just being lazy and sticking the the original script as mush as possible.

                  app.doScript(splitLines, undefined ,undefined, UndoModes.ENTIRE_SCRIPT);
                  function splitLines(){
                    if (app.selection.length == 1 && app.selection[0].hasOwnProperty("baseline") && app.selection[0].length > 1) 
                      { 
                          mObjSt = app.activeDocument.objectStyles.item("Colour Label Grey"); 
                          app.selection[0].insertionPoints[0].contents = "\r"; 
                          app.findGrepPreferences = app.changeGrepPreferences = null; 
                          app.findGrepPreferences.findWhat = "  (\\u)(?=~s)"; 
                          app.changeGrepPreferences.changeTo = "\\r\$1"; 
                          app.selection[0].changeGrep(); 
                          app.findGrepPreferences.findWhat = "\\n"; 
                          app.changeGrepPreferences.changeTo = ""; 
                          app.selection[0].changeGrep(); 
                          app.findGrepPreferences.findWhat = ", "; 
                          app.changeGrepPreferences.changeTo = ""; 
                          app.selection[0].changeGrep(); 
                          p = app.selection[0].parentTextFrames[0]; 
                          lh = (p.lines[-1].baseline - p.lines[0].baseline) / (p.lines.length-1); 
                          top = app.selection[0].lines[0].baseline - lh; 
                          app.findGrepPreferences.findWhat = "\\r";
                          while (app.selection[0].length > 0) 
                          {
                            if (app.selection[0].characters[0].contents == "\r") {app.selection[0].characters[0].contents = ""; continue;}
                            f = app.activeDocument.layoutWindows[0].activePage.textFrames.add ({geometricBounds:[top, p.geometricBounds[3]+2*lh, top+lh, 2*(lh+p.geometricBounds[3])-p.geometricBounds[1] ]}); 
                            app.selection[0].lines[0].move (LocationOptions.AFTER, f.texts[0]); 
                            top += lh; 
                            f.changeGrep();
                            f.appliedObjectStyle = mObjSt; 
                          } 
                          p.characters[-1].contents = ""; 
                          if (f.lines[-1].contents.indexOf("\r") != -1) f.characters[-1].contents = ""; 
                      } else 
                      alert ("please select some text to shred"); 
                  }
                  
                  • 6. Re: Script Improvement Needed
                    lcooperdesign85

                    Hi Trevor,

                     

                    Amazing, thank you this is so nearly perfect. The only thing that is't quite right is shown in the attached. As you'll see the last colour "G Denim" gets its last letter deleted. Do you know how I can avoid this?

                     

                    Screen Shot 2015-11-25 at 10.22.18.png

                     

                    Thanks again,

                    Lewis

                    • 7. Re: Script Improvement Needed
                      Trevorׅ Adobe Community Professional

                      Hi

                       

                      Remove line 31 if (f.lines[-1].....

                      • 8. Re: Script Improvement Needed
                        lcooperdesign85 Level 1

                        Thanks Trevor.

                         

                        Unfortunately that yielded the same results.

                         

                        However, I did try removing line 27 instead. What happens is that "G Denim" remains intact but doesn't get moved to its own text frame like the others.

                         

                        What's interesting, is that this doesn't happen every time. Only when there are lots of colours.

                         

                        Strange (to me at least )

                        • 9. Re: Script Improvement Needed
                          Trevorׅ Adobe Community Professional

                          I'm busy now but send a link to a sample document where it happens (Cut out the irrelevant, image, private stuff  from the document first) and I'll have a peek

                          • 11. Re: Script Improvement Needed
                            Trevorׅ Adobe Community Professional

                            This should be a good start.

                            Note there is a problem with the object style and you need to lower the text frame general inset top / bottom options of the style (I don't have your font but that's waht it looks like to me).

                            // By Trevor https://forums.adobe.com/message/8214750#8214750
                            // http://creative-scripts.com
                            app.doScript(splitLines, undefined ,undefined, UndoModes.ENTIRE_SCRIPT);
                            function splitLines(){
                              var mObjSt, t, lh, f, top, selct, pp, left, right, p1, tempFrame;
                              selct = app.selection.length == 1 && app.selection[0];
                              if (selct && selct.hasOwnProperty("baseline") && selct.length > 1)
                                {
                                    p = selct.parentTextFrames[0];
                                    pp = p.parentPage;
                                    lh = (p.lines[-1].baseline - p.lines[0].baseline) / (p.lines.length-1);
                                    top = selct.characters[0].baseline - lh;
                                    left = p.geometricBounds[3]+2*lh;
                                    right = 2*(lh+p.geometricBounds[3])-p.geometricBounds[1];
                                    tempFrame = pp.textFrames.add({geometricBounds: pp.bounds, textWrapPreferences:{textWrapMode:TextWrapModes.NONE}, textFramePreferences:{ignoreWrap: true}});
                                    selct.move(LocationOptions.AFTER, tempFrame.texts[0]);
                                    t = tempFrame.parentStory;
                                    mObjSt = app.activeDocument.objectStyles.item("Colour Label Grey");
                                    app.findGrepPreferences = app.changeGrepPreferences = null;
                                    app.findGrepPreferences.findWhat = "  (\\u)(?=~s)";
                                    app.changeGrepPreferences.changeTo = "\\r\$1";
                                    t.changeGrep();
                                    app.findGrepPreferences.findWhat = "\\n";
                                    app.changeGrepPreferences.changeTo = "\r";
                                    t.changeGrep();
                                    app.findGrepPreferences.findWhat = ", ";
                                    app.changeGrepPreferences.changeTo = "\\r";   // change this as it looked like a mistake
                                    t.changeGrep();
                                    app.findGrepPreferences.findWhat = "\\r";
                                    app.changeGrepPreferences.changeTo = "";
                                    while ((p1 = t.paragraphs[0]).isValid) {
                                        if (p1.characters[0].contents == "\r") {
                                            p1.remove();
                                            continue;
                                        }
                                        p1.changeGrep();
                                        f = pp.textFrames.add ({geometricBounds:[top, left, top+lh, right]});
                                        p1.move (LocationOptions.AFTER, f.texts[0]);
                                        top += lh;
                                        f.appliedObjectStyle = mObjSt;
                                    }
                                    tempFrame.remove();
                                } else
                                alert ("please select some text to shred");
                            }
                            

                             

                            HTH and please don't forget to mark as correct

                             

                            Trevor

                             

                            Custom Scripts & Services | Creative-Scripts.com

                            • 12. Re: Script Improvement Needed
                              lewis_cooper Level 1

                              Hi Trevor,

                               

                              Thank you so much for this, it works like a dream!

                               

                              The text frame insets are intentionally like that, so that I have a visible margin for my designs. The restults of the script are overset, yes, but if I hit cmd+alt+c (fit frame to content) twice then the frame sits snuggly around it. I won't ask you to add that bit! ;-)

                               

                              Thanks again!

                              Lewis