11 Replies Latest reply on Apr 24, 2015 10:36 AM by LenZigante

    character styles delete / replace script

    KateDdpc Level 1

      Hello there,

       

      Does anyone know if you can create a script that would delete and replace character styles?  I have a list of character styles (5 or so) that get brought into my indesign document when I import the word file.  I'm trying to see if these can be deleted and replace with a set of character styles existing in the indd doc.

       

      I'm using mac os 10.4 and CS6 with extendscript

       

      Appreciate any answers / help!

       

      many thanks

        • 1. Re: character styles delete / replace script
          csm_phil Level 4

          Hi KateDdpc,

           

          Try the below JS code.

           

          var myDoc = app.activeDocument;
          
          try{
          myDoc.characterStyles.item("old style name").remove("new style name");
          }catch(e){
              alert("The 'input character style (i.e, old style name)' is already deleted");
              }
          

           

           

          thx,

          csm_phil

          1 person found this helpful
          • 2. Re: character styles delete / replace script
            KateDdpc Level 1

            Hi there - thank you so much for your help!  This works like a charm! and so simple - seen things similar to what I needed but were much longer and confusing for me the novice!!

             

            The only thing that would make this completely perfect would be if where the name of the character style was entered in the script it recognised the fact that the style was within a style group?  This makes it much easier to know which styles belong to the original Indd and which to the word import, hence why i have the styles in separate groups... don't suppose you have a solution to that??

             

            cheers

            • 3. Re: character styles delete / replace script
              [Jongware] Most Valuable Participant

              InDesign cannot fetch the correct style group from just the name, if only because the whole idea of style groups is that you can have two character styles with the same name in different groups. But if you know the style group name in advance, you can target it pretty much the same way:

               

              myDoc.characterStyleGroups.item("groupname").characterStyles.item("old style name").remove("new style name");

               

              or, if your replace-with also is in a group

               

              myDoc.characterStyleGroups.item("groupname").characterStyles.item("old style name").remove(

              characterStyleGroups.item("groupname").characterStyles.item("

              new style name"));

               

              See http://jongware.mit.edu/idcs6js/pc_CharacterStyleGroup.html

              1 person found this helpful
              • 4. Re: character styles delete / replace script
                KateDdpc Level 1

                Yes indeed - see what you mean and that makes sense.  Thank you for your post will try that out but think that will work out for my situation as I know what the group names will be.

                 

                Thanks for your help

                • 5. Re: character styles delete / replace script
                  KateDdpc Level 1

                  Hmmm - I'm doing something wrong.  It doesn't seem to work now that I have the group added.  Still works without. oh darn.

                  • 6. Re: character styles delete / replace script
                    KateDdpc Level 1

                    Ha - success......

                     

                    var myDoc = app.activeDocument;

                     

                    try{

                    myDoc.characterStyles.item("old style name").remove(myDoc.characterStyleGroups.item("group name").characterStyles.item("new style name"));

                    }catch(e){

                        alert("The 'input character style (i.e, old style name)' is already deleted");

                        }

                     

                    or if the 'replace' style is also in a group

                     

                    var myDoc = app.activeDocument;

                     

                    try{

                    myDoc.characterStyleGroups.item("group name").characterStyles.item("old style name").remove(myDoc.characterStyleGroups.item("group name").characterStyles.item("new style name"));

                    }catch(e){

                        alert("The 'input character style (i.e, old style name)' is already deleted");

                        }

                     

                     

                    Lovely!

                    • 7. Re: character styles delete / replace script
                      Federico Erre Level 1

                      Hi! and how can i simply delete a character style? I don't want't to replace it with no other. Do I have to use de "[None]" style character? I can't translate this to java! Please, help me!

                      • 8. Re: character styles delete / replace script
                        LenZigante Level 1

                        This isn't working for me - I have style groups that are multiple levels deep and the script does not finding any levels beyond the first level.

                        eg. Headings group

                                  Heading 1 group

                                      Style 1

                                      Style 2

                                  Heading 2 group

                                      Style 1

                                      Style 2

                         

                        I've tried entering colons between the style groups as below but it's not succeeding in replacing such styles.  What am I doing wrong? Any suggestions?

                         

                        eg.

                        myDoc.characterStyleGroups.item("Headings group:Heading 1 group").characterStyles.item("Style1").remove(characterStyleGroups.item("Headings group:Heading 2 group").characterStyles.item("Style1"));



                        One other question if I may. I'm using similar scripts for both paragraph and character groups and in both cases I have multiple levels to the groups. Occasionally I need to replace a style in one of the groups with either [None], [Basic Paragraph Style], or [No Paragraph Style] (as applicable). My replacement line is similar to the one above but using 'characterStyleGroups.item("Group Name").characterStyles.item("Style")' or 'paragraphStyleGroups.item("Group Name").paragraphStyles.item("Style")' as appropriate. Unfortunately I don't seem to be able to apply any of these as replacement styles. Am I correct in assuming these default styles are not actually part of a group? I've tried entering Null and NothingEnum.nothing as their group names but to no avail. What should I be entering in place of "Group Name" in these cases?

                        • 9. Re: character styles delete / replace script
                          Marc Autret Level 4

                          Hi LenZigante,

                           

                          You access a style group within a style group using its own xxxStyleGroups collection:

                          doc.characterStyleGroups.itemByName("MyGroup").characterStyleGroups.itemByName("MySubGroup ") etc.

                           

                          This leads to a recursive approach of this topic. Here is a full replaceStyle routine that could help you:

                           

                          var pathToStyle = function F(/*str[]*/path,/*obj*/parent,/*str*/pc,/*uint=0*/i,  s,t,g)
                          // ---
                          // Recursive access to a style based on its path
                          // (utility of the replaceStyle function)
                          {
                              i||(i=0);
                              g = +(i < path.length-1);
                              s = pc + (g ? 'StyleGroups' : 'Styles');
                              t = parent[s].itemByName(path[i]);
                          
                              if( !t.isValid ) return null;
                              t = t.getElements()[0];
                              
                              return g ? F(path,t,pc,1+i) : t;
                          };
                          
                          var replaceStyle = function(/*p|c*/styleKind,/*str[]*/fromStylePath,/*str[]*/toStylePath,/*?Document*/doc,  s,fs,ts)
                          // ---
                          // styleKind :: use 'p' for paragraphStyle ; 'c' for characterStyle
                          // ---
                          // fromStylePath :: path of the style to be removed
                          // toStylePath [opt.] :: path of the replacement style (default: no style)
                          // Note 1: path format supports either a simple string (direct style name), or an
                          //         array of strings ["groupName","subGroupName", ... ,"styleName"]
                          // Note 2: in order to replace a paragraph style by the [Basic Paragraph] in a
                          //         locale-independent way, set toStylePath to "$ID/NormalParagraphStyle"
                          // ---
                          // doc (opt.) :: the document to target (default: activeDocument)
                          {
                              // Check styleKind
                              // ---
                              styleKind = styleKind ? (''+styleKind.toLowerCase()) : 'p';
                              if( 'p'!=styleKind && 'c'!=styleKind )
                                  { throw Error("Wrong styleKind argument in replaceStyle()."); }
                              s = 'p'==styleKind ? 'paragraph' : 'character';
                          
                              // Default doc
                              // ---
                              if( !(doc||(doc=app.properties.activeDocument)) )
                                  { throw Error("No document available."); }
                          
                              // Manage fromStyle
                              // ---
                              if( !fromStylePath )
                                  { throw Error("Wrong fromStylePath argument in replaceStyle()."); }
                              (('object'==typeof fromStylePath) && fromStylePath.length) || (fromStylePath=[''+fromStylePath]);
                              fs = pathToStyle(fromStylePath,doc,s);
                              if( null===fs )
                                  { throw Error("The fromStyle doesn't exist."); }
                          
                              // Manage toStyle
                              // ---
                              if( !toStylePath )
                                  {
                                  // If toStylePath is missing or empty, then use either
                                  // [None] style for character, or undefined for paragraph
                                  // ---
                                  ts = 'p'==styleKind ? undefined : parent.characterStyles.itemByName('$ID/[None]');
                                  }
                              else
                                  {
                                  (('object'==typeof toStylePath) && toStylePath.length) || (toStylePath=[''+toStylePath]);
                                  ts = pathToStyle(toStylePath,doc,s);
                                  }
                              if( null===ts )
                                  { throw Error("The toStyle doesn't exist."); }
                              
                              // Replace
                              // ---
                              fs.remove(ts);
                          };
                          
                          
                          // =====================================
                          // SAMPLE USAGE
                          // =====================================
                          
                          var STYLE_KIND = 'p',
                              FROM_STYLE_PATH = ["Headings group","Heading 1 group","Style 1"],
                              TO_STYLE_PATH = "$ID/NormalParagraphStyle";
                          
                          replaceStyle(STYLE_KIND, FROM_STYLE_PATH, TO_STYLE_PATH);
                          

                           

                          @+

                          Marc

                          • 10. Re: character styles delete / replace script
                            nicolaik Level 1

                            Federico Erre


                             

                            Hi! and how can i simply delete a character style?

                             

                             

                            Don't put the new style name as a parameter for remove() and the style will be removed and not replaced:

                             

                            myDoc.characterStyleGroups.item("groupname").characterStyles.item("old style name").remove();

                             

                            - modified line from the [Jongware] answer

                            • 11. Re: character styles delete / replace script
                              LenZigante Level 1

                              Thank you Marc. Your answer is awesome & far superior to the code I had written - I ended up trashing my code for yours. Much appreciated!