如何在文档绑定脚本中查找用户光标的位置 [英] How to find where user's cursor is in Document-bound script
问题描述
我有一个Google Apps脚本,该脚本与容器绑定到Google文档,并从自定义菜单调用.我希望它能够对当前选定的文本执行操作,但是我还没有找到一种让脚本知道选择了什么文本的方法.
I have a google apps script that is container-bound to a Google Document, and invoked from a custom menu. I would like it to be able to act upon the currently selected text, but I have not found a way for the script to know what text is selected.
我希望我可以使这段代码起作用. addMyLink()
函数会将自定义网址(基于某些baseUrl
)附加到所选文本.
My hope is that I could make this code work. The addMyLink()
function will attach a custom url (based on some baseUrl
) to the selected text.
function onOpen() {
DocumentApp.getUi().createMenu('Linker')
.addItem('Add awesome link', 'addMyLink')
.addToUi();
}
function addMyLink(event) {
var doc = DocumentApp.getActiveDocument();
var currElement = event.element;
var currSelection = {
startOffset: event.startOffset,
endOffset: event.endOffset
};
// if selected text does not have a link already, add one
if (currElement.asText().getLinkUrl(currSelection.startOffset) == null) {
//Logger.log('no link')
var url = baseUrl.replace('%target%',matchString)
//Logger.log(url);
currElement.asText().setLinkUrl(currSelection.startOffset, currSelection.endOffset, url);
}
}
不幸的是,从自定义菜单调用的函数不会接收事件,因此此代码只是梦想.还有其他获取此信息的方法吗?
Unfortunately, functions invoked from custom menus don't receive events, so this code is only a dream. Is there some other way to get this information?
我已经在问题跟踪器上输入了新问题,如果您对此感兴趣,请加星号:
I've entered a new issue on the issue tracker, please star if you're interested in it:
问题2865 :获取当前用户位置和文档中的状态信息
Issue 2865: Get current user location & state information in Document
推荐答案
昨天添加了处理光标位置和所选文本的功能,地址为博客文章.
The ability to work with cursor position and selected text was added yesterday, addressing Issue 2865: Get current user location & state information in Document. See the blog post as well.
Google提供的方法不同于上面问题中描述的方法-没有事件,而是分别通过Document.getCursor()和Document.getSelection()获得有关光标位置和元素选择的信息.
The approach provided by Google is different than the one described in the question above - there is no event, instead the information about cursor position and element selection is available through Document.getCursor() and Document.getSelection(), respectively.
这是问题的代码,适用于新的API.在此示例中,您可以选择文档中的任何文本,然后使用所选文本向Google搜索添加链接.
Here's the code from the question, adapted to the new APIs. With this example, you can select any text in your document and add a link to a google search using the selected text.
/**
* If user has selected text, add a url link there, unless
* the text already has a link.
*/
function addMyLink() {
var doc = DocumentApp.getActiveDocument();
var selection = doc.getSelection();
// get a URL pattern containing %target%.
// For this example, assume we want to build a google query
var baseUrl = "https://www.google.com/search?q=%target%";
if (!selection) {
tryAgain( "No current selection." );
}
else {
var elements = selection.getSelectedElements();
// We'll only put a hyperlink on text within a paragraph - if the selection
// spans paragraphs, reject it.
if (elements.length > 1) { tryAgain( "Selection cannot span paragraphs." ); return;}
var element = elements[0].getElement();
var elementText = element.asText();
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;
// If you have poo, fling it now...
// I mean - if you have other validation steps, put them here.
// Check if there's a link here already.
// Caveat: if there a link that starts INSIDE the selection,
// this won't find it.
if (elementText.getLinkUrl(startOffset) == null) {
// Generate the URL, and set it on the selected text
var url = baseUrl.replace('%target%',selectedText);
elementText.setLinkUrl(startOffset, endOffset, url);
}
else {
tryAgain( "Remove existing link first." );
}
}
}
/*
* Use Dialog Box to deliver a message to user, with
* "try again" message.
*
* @param {String} message The message to display in the dialog box
*
* @return {Button} The button the user clicked
*/
function tryAgain ( message ) {
var ui = DocumentApp.getUi();
return ui.alert("Please try again",message,ui.ButtonSet.OK);
}
function onOpen() {
DocumentApp.getUi().createMenu('Selection')
.addItem("Add Google Link", 'addMyLink' )
.addToUi();
}
这篇关于如何在文档绑定脚本中查找用户光标的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!