gpt4 book ai didi

google-apps-script - 获取用户选择的文本

转载 作者:行者123 更新时间:2023-12-03 10:00:03 25 4
gpt4 key购买 nike

我想通过Google Doc中的鼠标选择单词,然后通过脚本选择这些单词或行。

例子:

 var doc = DocumentApp.getActiveDocument();
var docText = doc.editAsText();
var text = docText.getSelection();

我尝试过,但是找不到像VBA那样的选择访问方法。

最佳答案

昨天添加了处理光标位置和选定文本的功能,地址为Issue 2865: Get current user location & state information in Document。也请参见blog post

事实证明,使用选择有一些技巧。我已尝试在此处显示它们-如果您发现其他任何评论,请添加评论,我会很乐意更新。

function onOpen() {
DocumentApp.getUi().createMenu('Selection')
.addItem("Report Selection", 'reportSelection' )
.addToUi();
}

function reportSelection () {
var doc = DocumentApp.getActiveDocument();
var selection = doc.getSelection();
var ui = DocumentApp.getUi();

var report = "Your Selection: ";

if (!selection) {
report += " No current selection ";
}
else {
var elements = selection.getSelectedElements();
// Report # elements. For simplicity, assume elements are paragraphs
report += " Paragraphs selected: " + elements.length + ". ";
if (elements.length > 1) {
}
else {
var element = elements[0].getElement();
var startOffset = elements[0].getStartOffset(); // -1 if whole element
var endOffset = elements[0].getEndOffsetInclusive(); // -1 if whole element
var selectedText = element.asText().getText(); // All text from element
// Is only part of the element selected?
if (elements[0].isPartial())
selectedText = selectedText.substring(startOffset,endOffset+1);

// Google Doc UI "word selection" (double click)
// selects trailing spaces - trim them
selectedText = selectedText.trim();
endOffset = startOffset + selectedText.length - 1;

// Now ready to hand off to format, setLinkUrl, etc.

report += " Selected text is: '" + selectedText + "', ";
report += " and is " + (elements[0].isPartial() ? "part" : "all") + " of the paragraph."
}
}
ui.alert( report );
}

关于google-apps-script - 获取用户选择的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16639331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com