Anda di halaman 1dari 8

Page 1 of 8

/ NumberAdjuster.jsx / Verso 1.1.1 / * Este InDesign CS3/CS4 JavaScript destina-se a realizar operaes sobre os nmeros enc para encontrar nmeros dentro de qualquer documento inteiro ou apenas a seleo. Voc um estilo de carcter especfico, e / ou um caractere de prefixo. Este roteiro foi escrito por Steve Wareham em stevewareham.com baseado numa ideia de * / //================================================ ==== \ \ / / Esta funo remove caracteres no-numricos, como a vrgula stripNonNumeric funo (STR) { str + =''; RGX var = / ^ \ d | \ .|-$/; var a =''; for (var i = 0; str.length i <; i + +) { (Rgx.test (str.charAt (i))) if { if (((i str.charAt () == out.indexOf & & () = -1)! '.' '.'! | | )) {- (I str.charAt () == '' & & out.length = 0!) fora + str.charAt = (i); } } } Retornar para fora; } //================================================ ==== \ \ / / Essa funo adiciona vrgulas para nmeros addCommas funo (NSTR) { NSTR + =''; x = nStr.split ('.'); x1 = x [0]; x.length x2 => 1? '.' + X [1]:''; RGX var = / (\ d +) (\ d {3}) /; while (rgx.test (x1)) { x1.replace x1 = (RGX, '$ 1' + ',' + '$ 2'); } retorno x1 + x2; } //================================================ ==== \ \ / / Funo para arredondar nmeros numRounder funo (myNumber, myRoundto) { myRoundMod = 1; para (arredondamento = 0; myRoundto arredondamento <; arredondamento + +) { myRoundMod = * myRoundMod 10; } myRoundedNum = Math.round (myRoundMod * myNumber) / myRoundMod; myRoundedNum retorno; } //================================================ ======== \ \ / / Funo para obter uma matriz de nomes de estilo de caractere myGetCharacterStyleNames function () {

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-8&sl=en&tl=pt&u=... 28/3/2011

Page 2 of 8

myStyleNames var = app.documents.item (0) characterStyles.everyItem () nome..; myStyleNames retorno; } //================================================ ======== \ \ / / Verificar se existe um arquivo de preferncias, se no tentar ler nos valores var thisScript app.activeScript =; myTempFile var = new File (thisScript.path + "/" num_adjust_prefs.txt '+); myTempFileExists var = myTempFile.open ('r', 'texto', 'R * ch'); if (myTempFileExists == true) { try / / Tenta ler o arquivo temporrio { myTempFileContents myTempFile.read = (); myTempFile.close; myDialogValues = myTempFileContents.split ("@,@"); myOperator = parseFloat (myDialogValues [0]); myOperation myDialogValues = [1]; switch (myOperation) { caso "+": myOperationIndex = 0 break; caso "-": myOperationIndex = 1 break; "*" Caso: myOperationIndex = 2 break; caso "/": myOperationIndex = 3 break; default: myOperationIndex = 0 break; } mySearchPrefix myDialogValues = [2]; myCharStyleIndex = parseInt (myDialogValues [3]); myCharStyleCheck = myDialogValues [4]; if (myCharStyleCheck == "true") {MyCharStyleCheck = true;} else {myCharStyleCheck = false;} myScopeDocumentRadio = myDialogValues [5]; if (myScopeDocumentRadio == "true") {MyScopeDocumentRadio = true;} else {myScopeDocumentRadio = false;} myScopeSelectionRadio = myDialogValues [6]; if (myScopeSelectionRadio == "true") {MyScopeSelectionRadio = true;} else {myScopeSelectionRadio = false;} myScopeStoryRadio = myDialogValues [12]; if (myScopeStoryRadio == "true") {MyScopeStoryRadio = true;} else {myScopeStoryRadio = false;} myNFASelectionRadio = myDialogValues [7]; if (myNFASelectionRadio == "true") {MyNFASelectionRadio = true;} else {myNFASelectionRadio = false;} myNFESelectionRadio = myDialogValues [8]; if (myNFESelectionRadio == "true") {MyNFESelectionRadio = true;} else {myNFESelectionRadio = false;} myRoundtoDefault = parseInt (myDialogValues [9]); myCustomGrepCheck = myDialogValues [10]; if (myCustomGrepCheck == "true")

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-8&sl=en&tl=pt&u=... 28/3/2011

Page 3 of 8

{MyCustomGrepCheck = true;} else {myCustomGrepCheck = false;} myCustomGrepFieldContents = myDialogValues [11]; } catch (e) / / Se houve um erro na leitura pref. arquivo { myOperator = 1; myOperationIndex = 0; mySearchPrefix = ""; myCharStyleIndex = 0; myCharStyleCheck = false; myScopeStoryRadio = false; myScopeDocumentRadio = false; myScopeSelectionRadio = true; myNFASelectionRadio = true; myNFESelectionRadio = false; myRoundtoDefault = 2; myCustomGrepCheck = false; myCustomGrepFieldContents = "[-]*[ 0-9] [0-9] * \ \ b ". } } / / Fim de caso exista um arquivo temporrio else {/ / Seno se o prefs arquivo / temp no pde ser encontrado myOperator = 1; myOperationIndex = 0; mySearchPrefix = ""; myCharStyleIndex = 0; myCharStyleCheck = false; myScopeStoryRadio = false; myScopeDocumentRadio = false; myScopeSelectionRadio = true; myNFASelectionRadio = true; myNFESelectionRadio = false; myRoundtoDefault = 2; myCustomGrepCheck = false; myCustomGrepFieldContents = "[-]*[ 0-9] [0-9] * \ \ b ". }

//================================================ ======== \ \ / / Caixa de dilogo Display para com as opes para o usurio myDialog app.dialogs.add var = ({nome: "Nmero Adjuster 1.2", canCancel: true}); myOperations var = new Array ("Adio", "subtrao", "Multiplicao", "diviso"); myCharStyles var = myGetCharacterStyleNames ();

try {/ / tenta criar a caixa de dilogo com (myDialog) { com (dialogColumns.add ()) { com (dialogColumns.add ()) { com (borderPanels.add ()) { com (dialogColumns.add ()) { staticTexts.add ({staticLabel: "Realizar a operao:"}); com (= mySearchScopeButtons radiobuttonGroups.add ()) { myRadio1 radiobuttonControls.add = ({staticLabel: "Todo o documento", checkedState: myScopeDoc myRadioStory radiobuttonControls.add = ({staticLabel: "Histria do quadro selecionado

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-8&sl=en&tl=pt&u=... 28/3/2011

Page 4 of 8

myRadio2 radiobuttonControls.add = ({staticLabel: "A seleo atual", checkedState: myScopeSele } staticTexts.add ({staticLabel: ""}); staticTexts.add ({staticLabel: "Nmeros so formatadas como :"}); com (= myNumberFormattButtons radiobuttonGroups.add ()) { myRadio3 radiobuttonControls.add = ({staticLabel: "1,234.56", checkedState: myNFASelectionRadi myRadio4 radiobuttonControls.add = ({staticLabel: "1.234,56", checkedState: myNFESelectionRadi } staticTexts.add ({minWidth: 15}); } } } com (dialogColumns.add ()) { com (borderPanels.add ()) { staticTexts.add ({staticLabel: "Operao de realizar :"}); myOperationsDropDown dropdowns.add var = ({StringList: myOperations, selectedIndex: myOperatio staticTexts.add ({staticLabel: "Operador:"}); myOperatorField realEditboxes.add var = ({EditValue: myOperator}); } com (borderPanels.add ()) { staticTexts.add ({staticLabel: "Como muitos lugares para arredondar para ?"}); myRoundto realEditboxes.add var = ({EditValue: myRoundtoDefault}); staticTexts.add ({minWidth: 125}); } com (borderPanels.add ()) { staticTexts.add ({staticLabel: "S encontramos nmeros com caracteres de prefixo ($,#, etc):"} myPreCharField textEditboxes.add var = ({editContents: mySearchPrefix}); staticTexts.add ({minWidth: 15}); } com (borderPanels.add ()) { var myCharStyleCheckBox checkboxControls.add = (); myCharStyleCheck myCharStyleCheckBox.checkedState =; staticTexts.add ({staticLabel: "Somente nmeros com ajuste :"}); estilo de caractere myCharStyleDropDown dropdowns.add var = ({StringList: myCharStyles, selectedIndex: myCharStyle staticTexts.add ({minWidth: 25}); } com (borderPanels.add ()) { var myCustomGrepCheckBox checkboxControls.add = (); myCustomGrepCheck myCustomGrepCheckBox.checkedState =; staticTexts.add ({staticLabel: "Pesquisa sobre Custom RegEx :"}); myGrepField textEditboxes.add var = ({editContents: myCustomGrepFieldContents, minWidth: 155}) staticTexts.add ({minWidth: 45}); } } } Fim} / / da caixa de dilogo } / / Fim de tentar catch (e) {alert (e + "Tente apagar o arquivo de preferncias");} //================================================ ======== \ \ //================================================ ======== \ \

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-8&sl=en&tl=pt&u=... 28/3/2011

Page 5 of 8

if (myDialog.show () == true) { myRunScript var = true / / Chave para verificar se a procurar e substituir funciton deve ser e //================================================ ======== \ \ / / Verificar o comprimento do caractere de prefixo, no pode ter mais de um personagem myPrefixcheck var = true; if (myPreCharField.editContents.length> 1) { alert ("O prefixo de pesquisa no pode ser superior a um personagem."); myRunScript = false; } //================================================ ======== \ \ / / Definir as variveis, com base no que foi digitado na caixa de dilogo myDocument var = app.activeDocument; var myNumberFormatIndex myNumberFormattButtons.selectedButton =; var mySearchScopeIndex mySearchScopeButtons.selectedButton =; switch (mySearchScopeIndex) / / Definir o escopo usado para pesquisa { case 0: myScope = quebrar "doc"; case 1: myScope = "histria" break; case 2: myScope = "seleo" break; default: myScope = "seleo" break; }

myOperator var = myOperatorField.editContents / / Alterar o myOperfield a uma caixa de realedi parseFloat myOperator = (myOperator); / wouldnt ser isso necessrio var myOperationIndex myOperationsDropDown.selectedIndex =; switch (myOperationIndex) / / Define a operao a executar { case 0: myOperation = "+" break; case 1: myOperation = "-" break; case 2: myOperation = "*" break; case 3: myOperation = "/" break; default: myOperation = "+" break; }

myRoundto var = parseFloat (myRoundto.editContents); / / mudar isso para uma caixa de realedit / / Obter o caractere de prefixo se est sendo usado para a pesquisa. Escape RegEx re mySearchPrefix var = myPreCharField.editContents; if (mySearchPrefix == "$" | | =="[" mySearchPrefix | | =="^" mySearchPrefix | | =="." {MySearchPrefix = "\ \" + mySearchPrefix;} / / Escape pesquisa caracteres especiais prefixos if (mySearchPrefix == "\ \" | | =="+" mySearchPrefix | | mySearchPrefix == "*" | =="( {MySearchPrefix = "\ \" + mySearchPrefix;} / / Escape ainda mais especial prefixos caracteres if (mySearchPrefix! = "") / / Colocar o prefixo [] se ele for usado, criar replacePrefix var = {MyReplacePrefix mySearchPrefix; mySearchPrefix = "[" + + mySearchPrefix "]";} else {myReplacePrefix = mySearchPrefix;}

myCharStyleDropDown.selectedIndex myCharStyleIndex var = / / Obter estilo de caractere a pesqu Var. MyCharStyle app.documents.item = (0) characterStyles [myCharStyleIndex]; / / Definir o Grep para pesquisa if (myCustomGrepCheckBox.checkedState == true) {MyGrep myGrepField.editContents =;}

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-8&sl=en&tl=pt&u=... 28/3/2011

Page 6 of 8

else {myGrep = "[-]*[ 0-9] [0-9] * \ \ b ";.} / / else usar esse padro Grep para pesquisa //================================================ ======== \ \ / / Definir as variveis com base em cujo mbito de usar = New Array mySearchScope (); if (myScope == "doc") { mySearchScope [0] = myDocument; mySearchAmount = 1; } else if (myScope == "histria") { if (app.selection.length! = 1) { myRunScript = false; alert (myErrorMessage = "Selecione um nico quadro de texto e tente novamente"); } mais { mySearchScope [0] app.selection = [0] parentStory.; mySearchAmount = 1; } } else / / Seno basta pesquisar na seleo { app.selection mySearchScope =; mySearchAmount = mySearchScope.length; } //================================================ ======== \ \ / / Executar a pesquisa ea substituio if (myRunScript == true) { / / Para a quantidade de itens de alto nvel no mbito de aplicao (ou seja, as selees) for (i = 0; i <mySearchAmount; i + +) { / / Desmarque a localizar / alterar suas preferncias. app.findGrepPreferences = NothingEnum.nothing; app.changeGrepPreferences = NothingEnum.nothing; try / / Tenta fazer a busca executar a operao + + substituir { / / Pesquisa no estilo de caractere se essa opo foi marcada if (myCharStyleCheckBox.checkedState == true) = {App.findGrepPreferences.appliedCharacterStyle myCharStyle;}

/ / Encontrar nmeros correspondentes mySearchGrep var app.findGrepPreferences.findWhat = myGrep + mySearchPrefix / / Encontre todos myFoundArray var = mySearchScope [i] findGrep ();. / / Array de partidas para o grep pesquisa

/ / Muda corresponde ao resultado da operao para (k = myFoundArray.length - 1, k> = 0; k -) { myFoundNumber var = myFoundArray [k] contedo.; if (mySearchPrefix! = "") {MyFoundNumber myFoundArray = [k] contents.slice (1);.} / / Slice do prefixo pesquisa se foi u if (myNumberFormatIndex == 1) / / Se o formato do nmero 1.234,56 {

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-8&sl=en&tl=pt&u=... 28/3/2011

Page 7 of 8

/ / Switch com vrgulas decimais, para que possamos ainda fazer alguns clculos sobre os nmer myFoundNumber.replace myFoundNumber = (/, / gi, "vrgula"); myFoundNumber.replace myFoundNumber = (/ \. / gi, ","); myFoundNumber.replace myFoundNumber = (/ vrgula / gi, "."); } / / Tira vrgulas a partir do nmero myStrippedFoundNumber = stripNonNumeric (myFoundNumber);

/ / Execute a operao selecionada no nmero encontrado if (myOperation == MyResult "+"){ var = (parseFloat (myStrippedFoundNumber) + myOperator) + "" else if (myOperation == MyResult "-"){ var = (parseFloat (myStrippedFoundNumber) - myOperator) else if (myOperation == MyResult "*"){ var = (parseFloat (myStrippedFoundNumber) myOperator *) else if (myOperation == MyResult "/"){ var = (parseFloat (myStrippedFoundNumber) / myOperator) / / Volta o resultado numRounder MyResult = (MyResult, myRoundto); / / Adicionar Vrgula para o resultado da operao MyResult = addCommas (MyResult); if (myNumberFormatIndex == 1) / / Se o formato do nmero 1.234,56 { / / Switch e vrgulas decimais volta para onde eles foram encontrados myResult.replace MyResult = (/, / gi, "vrgula"); myResult.replace MyResult = (/ \. / gi, ","); myResult.replace MyResult = (/ vrgula / gi, "."); myFoundNumber.replace myFoundNumber = (/, / gi, "vrgula"); myFoundNumber.replace myFoundNumber = (/ \. / gi, ","); myFoundNumber.replace myFoundNumber = (/ vrgula / gi, "."); }

/ / Se o prefixo busca tinha um "/" adicionado a ele para fugir chars regex reservados. remov if (myReplacePrefix.length> 1) = {MyReplacePrefix myReplacePrefix.slice (1)}

/ / Muda o texto encontrado com o resultado da operao app.changeGrepPreferences.changeTo = (myReplacePrefix MyResult +); app.findGrepPreferences.findWhat = (mySearchPrefix myFoundNumber +); myFoundArray [k] changeGrep ().; } / / Fim do loop atravs de todas as correspondncias encontradas, realizando operao e subs } / / Fim de tentar catch (e) {alert (e)} / / Reset Preferncias Grep app.findGrepPreferences = NothingEnum.nothing; app.changeGrepPreferences = NothingEnum.nothing; } / / Fim do loop atravs de todos os objetos de nvel superior } / / Fim da myRunScript se verdade //================================================ ======== \ \ / / Escreve os novos valores da caixa de dilogo em arquivo temporrio tente { myTempFileContents var = myOperator "@,@" + + + myOperation "@,@" myPreCharField.edit myTempFile.open ('w', 'texto', 'R * ch'); myTempFile.writeln (myTempFileContents); myTempFile.close (); } catch (e) {alert (e);}

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-8&sl=en&tl=pt&u=... 28/3/2011

Page 8 of 8

} / / Fim do dilogo, se no for cancelada / / Fim do numberAdjuster.jsx

http://translate.googleusercontent.com/translate_c?hl=pt-BR&ie=UTF-8&sl=en&tl=pt&u=... 28/3/2011

Anda mungkin juga menyukai