Word JS APIs: extending a Range

亡梦爱人 提交于 2020-01-06 05:52:08

问题


While working on answering this question I would really like to have been able to extend a Range by a specific number of characters. In the COM API I would have used Range.MoveEnd(). Is there any equivalent that I didn't find in the JS API?

Background: The question referenced is about finding search terms with more than 255 characters - which is a limit in Word for the desktop. The search fails.

The simple way to go about it would be to search the first 254 characters, then expand the found Range by the remaining number of characters and comparing that Range.Text to the full search term.

Not finding any equivalent for expanding a Range in this manner, I had to resort to:

  • breaking down the search term into < 255 character pieces
  • search for each piece one-by-one
  • determine whether each searched piece was adjacent to the previous
  • then expand a Range to include the adjacent piece
  • and repeat until all pieces were found

Thus, my question...

async function basicSearch() {
    await Word.run(async (context) => {
        let maxNrChars = 254;
        let searchterm = "";
        let shortSearch = true; //search string < 255 chars
        let fullSearchterm = "Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in the embed code for the video you want to add. You can also type a keyword to search online for the video that best fits your document. Aösdlkvaösd faoweifu aösdlkcj aösdofi "
        let searchTermNrChars = fullSearchterm.length;
        let nrSearchCycles = Number((searchTermNrChars / maxNrChars).toFixed(0));
        let nrRemainingChars = searchTermNrChars - (nrSearchCycles * maxNrChars);
        //console.log("Number of characters in search term: " + searchTermNrChars
        //    + "\nnumber of search cycles required: " + nrSearchCycles
        //    + "\nremaining number of characters: " + nrRemainingChars);

//numerous ranges are required to extend original found range
        let bodyRange = context.document.body.getRange();
        bodyRange.load('End');
        let completeRange = null;
        let resultRange = null;
        let extendedRange = null;
        let followupRange = null;

        let cycleCounter = 0;
        let resultText = "";
        if (searchTermNrChars > maxNrChars) {
            searchterm = fullSearchterm.substring(0, maxNrChars);
            cycleCounter++;
            shortSearch = false;
        }
        else { searchterm = fullSearchterm; }

        let results = context.document.body.search(searchterm);
        results.load({ select: 'font/highlightColor, text' });

        await context.sync();

        // short search term, highlight...
        if (shortSearch) {
            for (let i = 0; i < results.items.length; i++) {
                results.items[i].font.highlightColor = "yellow";
            }
        }
        else {
            //console.log("Long search");
            for (let i = 0; i < results.items.length; i++) {
                resultRange = results.items[i];
                resultRange.load('End');
                extendedRange = resultRange.getRange('End').expandTo(bodyRange.getRange('End'));

                await context.sync();

                //search for the remainder of the long search term
                for (let cycle = 1; cycle < nrSearchCycles; cycle++) {
                    searchterm = fullSearchterm.substring((cycle * maxNrChars), maxNrChars);
                    //console.log(searchterm + " in cycle " + cycle);
                    let CycleResults = extendedRange.search(searchterm);
                    CycleResults.load({ select: 'text, Start, End' });
                    await context.sync();
                    followupRange = CycleResults.items[0];

                    //directly adjacent?
                    let isAfter = followupRange.compareLocationWith(resultRange);
                    if (isAfter.value == Word.LocationRelation.adjacentAfter) {
                        resultRange.expandTo(followupRange);
                        extendedRange = resultRange.getRange('End').expandTo(bodyRange.getRange('End'));
                    }
                    await context.sync();
                }

                if (nrRemainingChars > 0) {
                    console.log("In remaining chars");
                    searchterm = fullSearchterm.substring(searchTermNrChars - nrRemainingChars);
                    console.log(searchterm);
                    let xresults = extendedRange.search(searchterm);
                    xresults.load('end, text');
                    await context.sync();

                    let xresult = xresults.items[0];

                    let isAfter = xresult.compareLocationWith(resultRange);

                    await context.sync();
                    console.log(isAfter.value);
                    if (isAfter.value == Word.LocationRelation.adjacentAfter) {
                        completeRange = resultRange.expandTo(xresult);
                        completeRange.load('text');
                        //completeRange.select();
                        await context.sync();
                        resultText = completeRange.text.substring(0, fullSearchterm.length);
                        console.log("Result" + cycleCounter + ": " + resultText);
                    }  
                }
                else {
                    //No remeaining chars
                    resultRange.load('text');
                    //resultRange.select();
                    await context.sync();
                    resultText = resultRange.text.substring(0, fullSearchterm.length);
                    completeRange = resultRange; 
                }

                //long search successful?
                if (resultText == fullSearchterm) {
                    completeRange.font.highlightColor = "yellow";
                }
                else {
                    console.log("Else! " + resultText + "  /  " + fullSearchterm);
                }
                completeRange = null;
            }
        }  
    });

回答1:


That was something we had in the original design, but it was actually removed from the API as it can easily lead to unexpected outcomes (i.e. hidden character inconsistencies, footnotes, etc.), and we could not cover those cases with the resources at hand. We decided to remove it.

That been said I think you can achieve something similar to range.MoveEnd() with Word.js, you just need to define to the end of what ;). One way of doing it is to use the range.expandTo(endRange) method. Again, The interesting thing is how to get the "endRange", so the following example shows how to do it if "end" means the end of the paragraph, probably in your scenario will suffice.

async function run() {
    await Word.run(async (context) => {
        //assume the range at the end of your 255 characters.
        var startRange = context.document.getSelection().getRange("end"); 
        //This one is the range at the end of the paragraph including the selection.
        var endRange = context.document.getSelection().paragraphs.getLast().getRange("end");

        var deltaRange = startRange.expandTo(endRange);
        context.load(deltaRange);

        await context.sync();
        // this will print the characters after the range all the way to the end of the paragraph.
        console.log(deltaRange.text);
    });
}

hope this helps or at least sets you up in the right direction.



来源:https://stackoverflow.com/questions/51159644/word-js-apis-extending-a-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!