获取用户选择的文本

Ama*_*any 4 google-docs google-apps-script

我想在Google文档中通过鼠标选择单词或行,并通过脚本获取这些选定的单词或行.

例:

  var doc = DocumentApp.getActiveDocument();
  var docText = doc.editAsText();
  var text = docText.getSelection();
Run Code Online (Sandbox Code Playgroud)

我尝试过,但我没有找到任何选择访问方法,如在VBA中.

Mog*_*dad 6

昨天添加了处理光标位置和所选文本的功能,解决了问题2865:获取Document中的当前用户位置和状态信息.也请参阅博客文章.

事实证明,使用选择有一些技巧.我试图在这里展示它们 - 如果你找到其他人,请添加评论,我很乐意更新.

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 );
}
Run Code Online (Sandbox Code Playgroud)