javascript - Indesign JavaScript 在书中创建文本和文档内超链接 - 非常慢

标签 javascript scripting adobe adobe-indesign extendscript

  1. 第一次发帖
  2. 虽然我有使用其他语言的经验,但还是第一次用 JavaScript 编写。

我在 Adob​​e InDesign CS5.5 中工作。我的 ID Book 中有多个文件,每个文件包含不同数量的“章节”。该书包含一个索引文件,其中包含以缩写形式引用各章的主题标题(例如,“CHAPTER 125”变为“ch 125 no 3”——注意“no x”部分无关紧要)。我的脚本的目标是创建文档间链接,这些链接将在 ID Book 导出为 PDF 时添加重要功能。用户将能够从索引跳转到章节,反之亦然。我认为我正在处理的脚本和问题对其他人有用,但还没有找到任何帖子来解决我的问题。

特定章节(“CHAPTER 125”)索引中的所有引用文献(如“ch 125 no 1”)都会获得指向该章节标题位置的超链接。这部分脚本运行良好,运行速度很快。

另一半将在每章文本的末尾插入相应的主题标题,并使这些段落链接回索引中相应的主题标题。 (换句话说,它们是交叉引用,但在 ID 术语中不是真正的外部参照,因为我想更好地控制它们,而且我对该主题的阅读告诉我要避开真正的外部参照。)这是脚本的一部分那让我把头撞在墙上。它连续几个小时地运行,却没有完成一本 200 章的书。请注意,出于测试目的,我只是在每一章下的所需位置插入一段文本,而不是所有主题标题和链接。我从较小的文本集和我的调试打印到控制台知道脚本正在工作,而不是陷入无限循环。尽管如此,它运行的时间太长了,如果我打断它,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;

最佳答案

尝试打开所有链接到它们的交叉引用文件。

关于javascript - Indesign JavaScript 在书中创建文本和文档内超链接 - 非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9607184/

相关文章:

shell - zsh 运行存储在变量中的命令?

linux - 使用 date 命令比较时间

javascript - 真正新手的 DRY Javascript

javascript - Jquery ajax 在 HTTP 上调用延迟响应

python - 使用 python api 从 zabbix 获取历史记录

user-interface - Acrobat DC - 更改应用程序背景颜色? (GUI太亮了)

ios - Adobe air 的 In App Purchase ANE 是否成功?

javascript - 授权特定字符的日期选择器字段

javascript - Json转Array,只提取值

php - 使用 jQuery getScript 从 PHP 脚本调用 JavaScript 函数