在 Google 文档中使用 Google Apps 脚本更改光标所在位置的单词的颜色

Change the color of the word where the cursor is with Google Apps Script in a Google Document

我正在尝试更改当前 google 文档光标结束时的单词颜色(当执行服务器功能时)。我不知道该怎么做。我看到: 解释了如何获取该行的最后一个字,但这并没有真正起作用,这就是我所拥有的(非常粗糙的代码):

function clientize() {///
  var t = Date.now();
  var doc = DocumentApp.getActiveDocument().getCursor();
  var els = doc.getElement();
  var txt = els.asText().getText().split(" ");
  var word = txt[txt.length - 1];
  var offset = doc.getOffset();
  var highlightStyle = {};
  highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF0000';
  els.setBold(offset - 5,offset , true)
 // els.setAttributes(4,10,highlightStyle);

  return (word)
}

但它只给我该行的最后一个词,而不是光标实际所在的词,而且我也不知道如何在找到文本后更改文档中该词的颜色.我知道我可以根据一定范围更改颜色,但它只适用于 getElement(),但我如何更改光标所在的整个单词的特定范围?

例如,假设我有一行,光标为:

hello world ho|w are you today

那么当我激活服务器功能时,只有"how"这个词应该变成红色,例如

这怎么可能????

你可以这样做,诀窍是获取当前用户单词开始和结束的偏移量。

function clientize() {

  // Get the Position of the user's cursor
  var position = DocumentApp.getActiveDocument().getCursor();

  // Get the element that contains this Position
  var ref_element = position.getElement();

  // Get the text in the element
  var text = ref_element.asText().getText(); 

  // Get the cursor's relative location within ref_element.
  // Verify if cursor is within text elem. or paragraph elem.
  var ref_offset = position.getOffset();
  if (ref_element.getType() == DocumentApp.ElementType.PARAGRAPH){

    // Cursor is at beginning or end of line
    if (ref_offset == 1){

      // Cursor is at last word. Move to the left into TEXT
      ref_offset = text.length - 1;

    }
  }

  // Get offset for current word's initial char
  var offset_first = ref_offset - text.substring(0,ref_offset).split(" ")[text.substring(0,ref_offset).split(" ").length - 1].length;

  // Get how many chars to the end of current word
  var chars_to_end;
  if (text.substring(ref_offset, ref_offset + text.length - 1).indexOf(" ") > -1) {

    // if word has a trailing space exclude it from count
    chars_to_end = text.substring(ref_offset, ref_offset + text.length - 1).indexOf(" ");

  } else {
    chars_to_end = text.substring(ref_offset, ref_offset + text.length - 1).length - 1;
  }

  // Get offset for current word's last char
  var offset_last = ref_offset + chars_to_end;

  // Define the styling attributes
  var style = {};
  style[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF00FF';

  // Apply styling to current word
  ref_element.asText().setAttributes(offset_first, offset_last, style);
}

注意:如果返回的单词后面或前面有逗号或其他字符,则必须过滤返回的单词。 提示:使用正则表达式。 看看这个测试 document with it's bound script 看看它是否有效。

这里的关键函数也供参考:setAttributes(startOffset, endOffsetInclusive, attributes)

请注意,有很多方法可以解决这个问题,这只是实现它的一种方法。