Skip to main content
Known Participant
November 18, 2016
Question

change case of selection

  • November 18, 2016
  • 5 replies
  • 2586 views

Hello!

A lot of times I have to change case of some part of my text to titlecase. So I've decided that it would be easier to write short script to do it automatically.

I've came with something like below.Basically after selecting part of text you want to change to title case you launch the script and it's done.

What do you think? It works for me, but maybe it could be better. Thanks in advance!

//variable made of selected text

var selectedWord = app.selection[0].contents;

//changing case of selection

var changeCase = app.selection[0].changecase (ChangecaseMode.titlecase);

//once more reading selection into variable

var changedWord = app.selection[0].contents;

//'find/change'

//clearing previous settings

app.findGrepPreferences = app.changeGrepPreferences = NothingEnum.nothing;

//setting 'find' window

app.findGrepPreferences.findWhat = selectedWord;

app.findGrepPreferences.appliedParagraphStyle = 'BODY';

//setting 'change' window

app.changeGrepPreferences.changeTo= changedWord;

//undoing previous changes, just for keeping the order

var undoingChanges = document.undo();

//launching function

app.activeDocument.changeGrep();

// clearing previous settings

app.findGrepPreferences = app.changeGrepPreferences = NothingEnum.nothing;

This topic has been closed for replies.

5 replies

foltmanAuthor
Known Participant
December 8, 2016

Hello everyone!

After testing my previous version of script I've noticed some failures, so I've wrote it again, this time with more accuracy.

Now it has some restrictions:

1. works only on selected words

2. selection can't span across paragraphs

3. changes words only in current story

4. changes words only with the same paragraph style as selected

It works for me perfectly, hope that will help someone else.

Here's code:

var myDoc = app.activeDocument;

//***initial mainCheckOut() function

function mainCheckOut(){

//checking if there is a document and what is selected

    if(app.documents.length > 0){

        if(app.selection.length > 0){

            switch(app.selection[0].constructor.name){

                case 'Character':

                case 'Word':

                case 'Line':

                case 'Paragraph':

                case 'Text':

                    myChangeCase();

                    break;

                case 'TextStyleRange':

                case 'InsertionPoint':

                case 'TextFrame':

                case 'TextColumn':

                case 'Cell':

                case 'Column':

                case 'Row':

                case 'Table':

                    alert('Select some words!');

                    break;

               default:

                    alert('Select some words!');

            }

        }

        else{

        //nothing was selected

            alert('Select some words!');

        }

    }

    else{

        alert('Open any document and select some words.');

    }

}

//end of mainCheckOut()

mainCheckOut();

//***myChangeCase function()

function myChangeCase(){

    //variables made of selected text

    var mySelection = myDoc.selection[0];

    var myStory = mySelection.parentStory;

    var myStyle = mySelection.appliedParagraphStyle;

    var myParentStyle = mySelection.appliedParagraphStyle.parent;

    var selectedWords = mySelection.contents;

    var changedWords = "";

    var findStyle;

    //function to determinate length of selection

    function findWords(){

        if(selectedWords.indexOf("\r") != -1){

            alert('Select some words in one paragraph!');

            exit();

        }

        else if(mySelection.words.length == 1){

            changedWords = selectedWords.slice(0,1).toUpperCase() + selectedWords.slice(1).toLowerCase();

        }

        else{

            var moreWords = selectedWords.split(" ");

            for (i = 0; i < mySelection.words.length; i++){

                moreWords = moreWords.slice(0,1).toUpperCase() + moreWords.slice(1).toLowerCase();

            }

            changedWords = moreWords.join(" ");

        }

    }

   

    //function to set applied paragraph style and check if it is nested in a group

    function setStyle(){

        if(myParentStyle.constructor.name == "Document"){

            findStyle = myStyle;

        }

        else{

            findStyle = myDoc.paragraphStyleGroups.item(myParentStyle.name).paragraphStyles.item(myStyle.name);

        }

    }

    findWords();

    setStyle();

    doFindChange(myStory,selectedWords,changedWords,findStyle);

}

//end of myChangeCase()

//***final doFindChange() function

function doFindChange(myStory,selectedWords,changedWords,findStyle){

    //clearing 'find/change' window settings 

    app.findGrepPreferences = app.changeGrepPreferences = NothingEnum.nothing; 

   

    //setting find window

    app.findGrepPreferences.findWhat = selectedWords;

    app.findGrepPreferences.appliedParagraphStyle = findStyle;

    //setting change window

    app.changeGrepPreferences.changeTo = changedWords; 

    //launching function 

    myStory.changeGrep();

   

    //clearing previous settings 

    app.findGrepPreferences = app.changeGrepPreferences = NothingEnum.nothing;

}

//end of doFindChange()







SumitKumar
Inspiring
November 21, 2016

Hi Jarek,

I think you do not need script for selection.

If you need change case in selection then create keyboard shortcut.

Sumit

-Sumit
Jongware
Community Expert
Community Expert
November 21, 2016

Jarek uses a script to make that same change throughout the entire document. He captures the changed word (or phrase), copies the original and new into Find/Change, and applies that on the entire story.

Pretty smart – I bet it's a real time saver.

foltmanAuthor
Known Participant
November 21, 2016

Hi guys!

I will explain why I'm trying to build this script and why I'm complicating things a little bit.

For example in Shakespeare's play there is part:

Flourish. Enter HENRY BOLINGBROKE, DUKE OF YORK, with other Lords, and Attendants, NORTHUMBERLAND.

HENRY BOLINGBROKE Kind uncle York, the latest news we hear

Is that the rebels have consumed with fire

Our town of Cicester in Gloucestershire;

But whether they be ta’en or slain we hear not.

Enter NORTHUMBERLAND.

Welcome, my lord what is the news?

NORTHUMBERLAND First, to thy sacred state wish I all happiness.

The next news is, I have to London sent

The heads of Oxford, Salisbury, Blunt, and Kent:

The manner of their taking may appear

At large discoursed in this paper here.

HENRY BOLINGBROKE We thank thee, gentle Percy, for thy pains;

And to thy worth will add right worthy gains.

Enter LORD FITZWATER.

LORD FITZWATER My lord, I have from Oxford sent to London

The heads of Brocas and Sir Bennet Seely,

Two of the dangerous consorted traitors

That sought at Oxford thy dire overthrow.

HENRY BOLINGBROKE Thy pains, Fitzwater, shall not be forgot;

Right noble is thy merit, well I wot.

Enter HENRY PERCY, and the BISHOP OF CARLISLE.

So now I want to change all instances of NORTHUMBERLAND  (or other name) to titlecase, but only those that are italicized.  I'm therefore selecting text and executing script - it will change only wanted part because of 'appliedParagraphStyle' restriction.

Peter, I've added 'document.undo()' part only for the sake of order - I want to be able to undo grep change if necessary with one cmd+z.

Previous lin:

  1. var changeCase = app.selection[0].changecase (ChangecaseMode.titlecase)

would add one additional step required.

Hope I'm not complicating thing even more!

Jump_Over
Legend
November 21, 2016

Jarek,

So - as you've written - script is working well and there is no need to fix something, right?

Just aside:

if your goal is to reach possibility to 'undo' entire script changes - include it into a function and call using method app.doScript()

I mean:

app.doScript( main, ScriptLanguage.JAVASCRIPT , [], UndoModes.ENTIRE_SCRIPT, "filteredChangecase" )

function main() {

// your code

}

Jarek

tpk1982
Legend
November 21, 2016

Jarek,

filteredChangecase is script file name?

Peter Kahrel
Community Expert
Community Expert
November 19, 2016

Jarek -- This one line changes your selected word to title case:

app.selection[0].changecase (ChangecaseMode.titlecase);

Why are you using changeGrep() and undo()?

Peter

Jump_Over
Legend
November 19, 2016

Peter,

It looks like selection is the way to input data for change every instance across paragraphStyle 'Body' area.

"Undo" doesnt looks necessary since good format will be changed to good format.

But @tpk982 code look like targeted to ID version upto CS2 (doc.search(), findPref)

Jarek

tpk1982
Legend
November 20, 2016

HI Jarek,

Yes it is created when Cs2 using.. but it is working in all Indesign version, because of the inclusion of

  1. app.scriptPreferences.version = "4.0" 
tpk1982
Legend
November 19, 2016

Am using this script to change words for case changes..

app.scriptPreferences.version = "4.0"

if ((app.documents.length != 0) && (app.selection.length != 0)) {

myDoc = app.activeDocument;

myStyles = myDoc.paragraphStyles;

myStringList = myStyles.everyItem().name;

myCaseList = ["Uppercase","Lowercase", "Title case", "Sentence case"];

myCases = [ChangecaseMode.uppercase, ChangecaseMode.lowercase, ChangecaseMode.titlecase, ChangecaseMode.sentencecase];

var myDialog = app.dialogs.add({name:"Case Changer"})

with(myDialog){

  with(dialogColumns.add()){

   with (dialogRows.add()) {

    with (dialogColumns.add()) {

     staticTexts.add({staticLabel:"Paragraph Style:"});

    }

    with (dialogColumns.add()) {

     myStyle = dropdowns.add({stringList:myStringList,selectedIndex:0,minWidth:133});

    }

   }

   with (dialogRows.add()) {

    with (dialogColumns.add()) {

     staticTexts.add({staticLabel:"Change Case to:"});

    }

    with (dialogColumns.add()) {

     myCase = dropdowns.add({stringList:myCaseList,selectedIndex:0,minWidth:133});

    }

   }

  }

}

var myResult = myDialog.show();

if (myResult != true){

  // user clicked Cancel

  myDialog.destroy();

  errorExit();

}

  theStyle = myStyle.selectedIndex;

  theCase = myCase.selectedIndex;

  myDialog.destroy();

  app.findPreferences = null;

  app.changePreferences = null;

  myFinds = myDoc.search('',false,false,undefined,{appliedParagraphStyle:myStyles[theStyle]});

  myLim = myFinds.length;

  for (var j=0; myLim > j; j++) {

   myFinds.texts[0].changecase(myCases[theCase]);

  }

} else {

errorExit();

}

// +++++++ Functions Start Here +++++++++++++++++++++++

function errorExit(message) {

if (arguments.length > 0) {

  if (app.version != 3) { beep() } // CS2 includes beep() function.

  alert(message);

}

exit(); // CS exits with a beep; CS2 exits silently.

}

HTH