2012-03-07 4 views
2
  1. 처음 내가 다른 언어 경험을 가지고 있지만, 자바 스크립트로 작성
  2. 처음 게시.

저는 Adobe InDesign CS5.5에서 작업하고 있습니다. 나는 ID Book에 여러 개의 파일을 가지고 있는데, 각 파일에는 다양한 "챕터"수가 들어 있습니다. 이 책에는 챕터를 축약 된 형식으로 참조하는 주제 제목이있는 색인 파일이 들어 있습니다 (예 : "CHAPTER 125"는 "ch 125 no 3"이됩니다 - "no x"부분은 부적합 함). 내 스크립트의 목표는 ID 북을 예를 들어 PDF로 내보낼 때 중요한 기능을 추가하는 문서 간 링크를 만드는 것입니다. 사용자는 색인에서 장으로 또는 그 반대로 이동할 수 있습니다. 나는 스크립트와 내가 다루는 이슈가 다른 사람들에게 유용 할 것이라고 생각하지만 내 문제를 해결할 게시물을 아직 찾지 못했다.인디자인 자바 스크립트 - 매우 느린

특정 장 ("CHAPTER 125")의 색인에있는 모든 색인 ("ch 125 no 1")은 해당 장의 머리 위치에 대한 하이퍼 링크를 가져옵니다. 스크립트의이 부분은 훌륭하게 작동하며 빠르게 실행됩니다.

나머지 절반은 각 장 텍스트의 끝에 해당 주제 머리글을 삽입하고 해당 단락을 색인의 해당 주제 헤드에 다시 링크시킵니다. (다른 말로하면, 그것들은 상호 참조이지만 진정한 x-refs는 아닙니다. 왜냐하면 나는 그것들에 대한 더 많은 통제를 원했기 때문에 주제에 대한 나의 독서는 진정한 x-refs를 명확하게 보여주고 있다고 말했습니다.) 이것은 스크립트의 일부입니다 그게 내 머리를 벽에 치고있다. 그것은 200 장의 책을 끝내지 않고 몇 시간 동안 실행됩니다. 테스트 목적으로 모든 주제 헤드와 링크가 아닌 각 장의 원하는 위치에 한 단락의 텍스트를 삽입하기 만합니다. 스크립트의 작업이 무한 루프에 얽매이지 않고 작은 텍스트 집합과 디버깅 인쇄물에서 콘솔까지 알 수 있습니다. 그럼에도 불구하고 너무 오래 실행되며 InDesign을 중단하면 InDesign이 응답하지 않아이를 죽여야하므로 부분 결과를 검토 할 수도 없습니다.

검색/읽기 포럼 기준 : 프리 플라이트를 비활성화했습니다. 도서 페이지 번호의 비활성화 된 자동 업데이트; 실시간 미리보기 설정을 지연으로 변경했습니다. 속도 저하가 InDesign 오버 헤드와 관련이 있을지는 모르겠지만 그 밖의 무엇을 시도해야할지 모르겠습니다.

이 JS 코드의 스타일이 얼마나 좋을지 모르겠지만 지금은 작동이 필요한 순간에이를 수정해야합니다.

var myBookFilePath = File.openDialog("Choose an InDesign Book File", "Indb files: *.indb"); 
var myOpenBook = app.open(myBookFilePath); 
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.neverInteract; 

// Open up every file in the currently active Book 
app.open(app.activeBook.bookContents.everyItem().fullName) 

// TODO: add error handling/user interaction here -- to pick which is Index file 
var strIndexFilename = "Index.indd"; 
var objChapHeadsWeb = {}; 
var myDoc = app.documents.item(strIndexFilename); 

$.writeln("\n\n~~~ " + myDoc.name + " ~~~"); 

// REMOVED CODE - check for existing hyperlinks, hyperlink sources/destinations 
// loop to delete any pre-existing hyperlinks & associated objects 
// works w/o any problems 

// Ugly GREP to find the Main heading text (all caps entry and nothing beyond) in the index file 
app.findGrepPreferences = NothingEnum.nothing; 
app.changeGrepPreferences = NothingEnum.nothing; 

/// GREP: ^[\u\d \:\;\?\-\'\"\$\%\&\!\@\*\#\,\.\(\)]+[\u\d](?=\.|,) 
app.findGrepPreferences.findWhat = "^[\\u\\d \\:\\;\\?\\-\\'\\\"\\$\\%\\&\\!\\@\\*\\#\\,\\.\\(\\)]+[\\u\\d](?=\\.|,)"; 
app.findGrepPreferences.appliedParagraphStyle = "Main"; 

var myFound = []; 
myFound = myDoc.findGrep(); 
$.writeln("Found " + myFound.length + " Main headings."); 

for (var i = 0; i < myFound.length; i++) { 
    myDoc.hyperlinkTextDestinations.add(myFound[i], { name: myFound[i].contents }); 
} 

$.writeln("There are now " + myDoc.hyperlinkTextDestinations.count() + " destinations."); 


myFound.length = 0; 

for (var j = app.documents.count()-1; j >= 0; j--) { 
    app.findGrepPreferences = NothingEnum.nothing; 
    app.changeGrepPreferences = NothingEnum.nothing; 

    // set the variable to the document we are working with 
    myDoc = null; 
    myDoc = app.documents[j]; 
    myFound.length = 0; 

    if (myDoc.name === strIndexFilename) { 
     continue;  // we don't want to look for chapter heads in the Index file, so skip it 
    } 

    $.writeln("\n\n~~~ " + myDoc.name + " ~~~"); 

// REMOVED CODE - check for existing hyperlinks, hyperlink sources/destinations 
// loop to delete any pre-existing hyperlinks & associated objects 
// works w/o any problems 

    // Clear GREP prefs 
    app.findGrepPreferences = NothingEnum.nothing; 
    app.changeGrepPreferences = NothingEnum.nothing; 

    app.findGrepPreferences.findWhat = "^CHAPTER \\d+"; 
    app.findGrepPreferences.appliedParagraphStyle = "chapter"; 

    myFound = myDoc.findGrep(); 
    var strTemp = ""; 
    $.writeln("Found " + myFound.length + " chapter headings."); 

    for (var m = 0; m < myFound.length; m++) { 
     strTemp = myFound[m].contents; 

     objChapHeadsWeb[strTemp] = {}; 
     objChapHeadsWeb[strTemp].withinDocName = myDoc.name; 
     objChapHeadsWeb[strTemp].hltdChHead = 
      myDoc.hyperlinkTextDestinations.add(myFound[m], {name:strTemp}); 
     objChapHeadsWeb[strTemp].a_strIxMains = []; 
     objChapHeadsWeb[strTemp].a_hltdIxMains = []; 
     objChapHeadsWeb[strTemp].nextKeyName = ""; 

     objChapHeadsWeb[strTemp].nextKeyName = 
      ((m < myFound.length-1) ? myFound[m+1].contents : String("")); 
    } 

    $.writeln("There are now " + myDoc.hyperlinkTextDestinations.count() + " destinations."); 
} 


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
// 
// Find the "ch" (chapter) references in the index file, link them 
//  back to the corresponding text anchors for the chapter heads 
//  in the text. 
// 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
myDoc = app.documents.item(strIndexFilename); // work with the Index file 

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

// GREP to find the "ch" (chapter) references in the index file 
// like ch 151 no 1 OR ch 12 no 3 
app.findGrepPreferences.findWhat = "(ch\\s+\\d+\\s+no\\s+\\d+)"; 

var strExpandedChap = ""; 
var strWorkingMainHd = ""; 
var arrFoundChapRefs = []; 
var myHyperlinkSource; 
var myHyperlinkDest; 

for (var x = 0; x < myDoc.hyperlinkTextDestinations.count(); x++) { 
    strWorkingMainHd = ""; 
    arrFoundChapRefs.length = 0; 

    // the special case, where we are working with the ultimate hyperlinkTextDestination obj 
    if (x === myDoc.hyperlinkTextDestinations.count()-1) { 
     // This is selecting text from the start of one MAIN heading... 
     myDoc.hyperlinkTextDestinations[x].destinationText.select(); 
     // This next line will extend the selection to the end of the story, 
     //  which should also be the end of the document 
     myDoc.selection[0].parentStory.insertionPoints[-1].select(SelectionOptions.ADD_TO); 
    } 
    // the regular case... 
    else { 
     // This is selecting text from the start of one MAIN heading... 
     myDoc.hyperlinkTextDestinations[x].destinationText.select(); 
     // ... to the start of the next MAIN heading 
     myDoc.hyperlinkTextDestinations[x+1].destinationText.select(SelectionOptions.ADD_TO); 
    } 

    strWorkingMainHd = myDoc.hyperlinkTextDestinations[x].name; 
    //arrFoundChapRefs = myDoc.selection[0].match(/(ch\s+)(\d+)(\s+no\s+\d+)/g); //NOTE: global flag 

    arrFoundChapRefs = myDoc.selection[0].findGrep(); 

    for(y = 0; y < arrFoundChapRefs.length; y++) { 
     myHyperlinkSource = null; 
     myHyperlinkDest = null; 
     strExpandedChap = ""; 

     strExpandedChap = arrFoundChapRefs[y].contents.replace(/ch\s+/, "CHAPTER "); 
     strExpandedChap = strExpandedChap.replace(/\s+no\s+\d+/, ""); 

     // if we found the chapter head corresponding to our chapter ref in the index 
     //  then it is time to create a link 
     if (strExpandedChap in objChapHeadsWeb) { 
      objChapHeadsWeb[strExpandedChap].a_strIxMains.push(strWorkingMainHd); 
      objChapHeadsWeb[strExpandedChap].a_hltdIxMains.push(myDoc.hyperlinkTextDestinations[x]); 

      myHyperlinkSource = myDoc.hyperlinkTextSources.add(arrFoundChapRefs[y]); 
      myHyperlinkDest = objChapHeadsWeb[strExpandedChap].hltdChHead; 

      myDoc.hyperlinks.add(myHyperlinkSource, myHyperlinkDest); 
     } else { 
      $.writeln("Couldn't find chapter head " + strExpandedChap); 
     } 
    } 
} 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
// NOW TIME FOR THE HARD PART... 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
myDoc = null; 
var strWorkingMainHd = ""; 
var nextKey = ""; 
var myParentStory = null; 
var myCharIndex = 0; 
var myCompareChar = null; 
var myLeftmostBound = 0; 
var myCurrentPara = null; 

for (var key in objChapHeadsWeb) { 
    myDoc = app.documents.item(objChapHeadsWeb[key].withinDocName); 
    myCompareChar = null; //recent addition 
    $.writeln("Working on " + key + "."); //debugging 

    nextKey = objChapHeadsWeb[key].nextKeyName; 

    objChapHeadsWeb[key].hltdChHead.destinationText.select(); 
    myLeftmostBound = myDoc.selection[0].index; 
    myParentStory = myDoc.selection[0].parentStory; 

    if((nextKey === "") || (myDoc.name !== objChapHeadsWeb[nextKey].withinDocName)) 
    { 
     //// Need to find end of story instead of beginning of next chapter 
     //myDoc.selection[0].parentStory.insertionPoints[-1].select(SelectionOptions.ADD_TO); 
     myParentStory.insertionPoints[-1].select(); 
     //myCharIndex = myDoc.selection[0].index;   /recently commented out 

     myCharIndex = myDoc.selection[0].index - 1;  //testing new version 
     myCompareChar = myParentStory.characters.item(myCharIndex);  //recenttly added/relocated from below 
    } else { 
     ///// 
     //objChapHeadsWeb[nextKey].hltdChHead.destinationText.select(SelectionOptions.ADD_TO); 
     objChapHeadsWeb[nextKey].hltdChHead.destinationText.select(); 

     //myParentStory.characters.item(myDoc.selection[0].index -1).select(); 

     myParentStory.characters.item(myDoc.selection[0].index -2).select(); //temp test ***** 

     myCharIndex = myDoc.selection[0].index; 
     myCompareChar = myParentStory.characters.item(myCharIndex); 

     if (myCompareChar.contents === "\uFEFF") { 
      $.writeln("Message from inside the \\uFEFF check.");  //debugging 

      myParentStory.characters.item(myDoc.selection[0].index -1).select(); 

      myCharIndex = myDoc.selection[0].index; 
      myCompareChar = myParentStory.characters.item(myCharIndex); 
     } 

     if((myCompareChar.contents !== SpecialCharacters.PAGE_BREAK) && 
      (myCompareChar.contents !== SpecialCharacters.ODD_PAGE_BREAK) && 
      (myCompareChar.contents !== SpecialCharacters.EVEN_PAGE_BREAK) && 
      (myCompareChar.contents !== SpecialCharacters.COLUMN_BREAK) && 
      (myCompareChar.contents !== SpecialCharacters.FRAME_BREAK)) 
     { 
      $.writeln("Possible error finding correct insertion point for " + objChapHeadsWeb[key].hltdChHead.name + "."); 
     } 
    } 

    if(myCharIndex <= myLeftmostBound) { // this shouldn't ever happen 
     alert("Critical error finding IX Marker insertion point for " + objChapHeadsWeb[key].hltdChHead.name + "."); 
    } 

    if(myCompareChar.contents !== "\r") { 
     myDoc.selection[0].insertionPoints[-1].contents = "\r"; 
    } 

    myDoc.selection[0].insertionPoints[-1].contents = "TESTING text insertion for: " + objChapHeadsWeb[key].hltdChHead.name + "\r"; 
    myDoc.selection[0].insertionPoints.previousItem(myDoc.selection[0].insertionPoints[-1]).select(); 

//myDoc.selection[0].insertionPoints[-1].contents = "<Now I'm here!>"; 

    myCurrentPara = myDoc.selection[0].paragraphs[0]; 

    myCurrentPara.appliedParagraphStyle = myDoc.paragraphStyles.item("IX Marker"); 

    // TODO: 
    //  need error handling for when style doesn't already exist in the document 
} // end big for loop 


//TODO: add error handling support to carry on if user cancels 
//close each open file; user should be prompted to save changed files by default 

app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll; 
app.documents.everyItem().close(); 

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

답변

0

크로스 레퍼런스의 모든 파일을 열어보십시오.

0

아마도 약간 속도가 빨라질 수있는 몇 가지 개선 사항을 제안 할 수 있습니다. 우선, 함수를 사용하여 훨씬 적은 범위에 집중할 수있는 수많은 전역 변수가 있습니다. 많은 글로벌 변수를 갖는 것은 퍼포먼스면에서 큰 비용이 든다.

한 번 말씀 드렸듯이 나는 책 한 권을 한 번에 열지 않고 하나씩 처리 할 것입니다. grep 호출은 비용이 많이 들기 때문에 패턴을 조사 할 수도 있습니다.

또 다른 하나는 $ .writeln 명령을 광범위하게 사용하는 것입니다. 특히 루프 내에서 피하십시오. 쉬운 보고서 라이브러리를 선호하십시오.

마지막으로 "더 나은"방법으로 코드를 다시 작성하려고했지만 처리 할 파일이없고 필요에 대한 명확한 이해로 전체 스크립트를 구성하기가 어려웠습니다. 그러나 다음 스 니펫이 코드를 다시 작성하고 중요한 시간 개선을 시작하는 데 도움이되기를 바랍니다.

var debug = true; 
 

 
var log = function(msg) { 
 
\t 
 
\t var l = File (Folder.desktop+"/log.txt"); 
 
\t 
 
\t if (!debug) return; 
 
\t 
 
\t l.open('a'); 
 
\t l.write(msg); 
 
\t l.close(); 
 
}; 
 

 
var main = function() { 
 
\t 
 
\t var bookFile, uil = app.scriptPreferences.userIntercationLevel; 
 
\t 
 
\t log("The party has started"); 
 
\t 
 
\t bookFile = File.openDialog("Choose an InDesign Book File", "Indb files: *.indb"); 
 
\t 
 
\t if (!bookFile) return; 
 
\t app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT; 
 
\t 
 
\t try { 
 
\t \t processBookFile (bookFile); 
 
\t } 
 
\t catch(err) { 
 
\t \t alert(err.line+"///"+err.message); 
 
\t } 
 

 
\t app.scriptPreferences.userInteractionLevel = uil; 
 
}; 
 

 
function processBookFile (bookFile) { 
 
\t var book = app.open (bookFile), 
 
\t bks = book.bookContents, 
 
\t n = bks.length; 
 
\t 
 
\t while (n--) { 
 
\t \t File(bks[n].name)!="Index.indd" && processBookContent (bks[n]); 
 
\t } 
 
} 
 

 
function processBookContent (bookContent) { 
 
\t var bcf = bookContent.fullName, 
 
\t doc = app.open (bcf, debug); 
 
\t 
 
\t //DEAL WITH HEADINGS 
 
\t processHeadings (doc); 
 
\t 
 
\t //DEAL WITH CHAPTERS 
 
\t processHeadings (doc); 
 
\t 
 
\t //add hyperlinks 
 
\t addHyperlinks(doc); 
 
} 
 

 

 

 
function processHeadings (doc){ 
 
\t var props = { 
 
\t \t findWhat : "^[\\u\\d \\:\\;\\?\\-\\'\\\"\\$\\%\\&\\!\\@\\*\\#\\,\\.\\(\\)]+[\\u\\d](?=\\.|,)", 
 
\t \t appliedParagraphStyle : "Main" 
 
\t }, 
 
\t found = findGrep(doc, props), 
 
\t n = found.length; 
 
\t 
 
\t while (n--) { 
 
\t \t doc.hyperlinkTextDestinations.add(doc, { name: found[i].contents }); 
 
\t } 
 
}; 
 

 
function processChapters (doc) { 
 
\t var props = { 
 
\t \t findWhat : "^CHAPTER \\d+", 
 
\t \t appliedParagraphStyle : "chapter" 
 
\t }, 
 
\t found = findGrep(doc, props), 
 
\t n = found.length; 
 
\t 
 
\t while (n--) { 
 
\t \t doc.hyperlinkTextDestinations.add(found[n], found[n].contents); 
 
\t } 
 
} 
 

 
function findGrep(doc, props){ 
 
\t app.findGrepPreferences = app.changeGrepPreferences = null; \t 
 
\t app.findGrepPreferences.properties = props; 
 
\t return doc.findGrep(); 
 
} 
 

 
function addHyperlinks (doc){ 
 
\t //a logic of yours 
 
}; 
 

 

 
main();