AppleScript / Automator:将所选文本用作变量

12
我找不到如何将所选文本作为AppleScript和Automator的变量使用。
有任何想法吗?
2个回答

7

对于Applescript,它可以与其他应用程序一起使用。要获取应用程序前窗口中所选文本,Applescript必须使用该应用程序理解/响应的语言/语法。对于非常可脚本化、基于文本文档的应用程序,它们之间有很多相似之处,看起来像:

tell app "xyz" to get selection of document 1

然而,实际上并没有标准。许多应用程序在它们可脚本化字典中并没有“文本选择”对象,因此您需要做各种变通处理。请参考以下示例:
tell application "Safari" to set selectedText to (do JavaScript "(''+getSelection())" in document 1)

tell application "System Events" to tell application process "TextEdit" to tell attribute "AXSelectedText" of text area 1 of scroll area 1 of window 1 to set selectedText to its value

tell application "Microsoft Word" to set selectedText to content of text object of selection

您还可以编写“系统事件”脚本来模拟按下 command-c 键以复制文本。
tell application "System Events" to keystroke "c" using {command down}
delay 1
set selectedText to the clipboard

如果你需要更具体的帮助,请发布你的代码并指明你正在使用哪个应用程序。如果它不是一个可编写脚本的应用程序,那么你将不得不使用最后一种方法,调用系统事件。或者,你可以使用一个OS X服务,这也是你询问过的。
当你在Automator中创建一个服务时,你会创建一个新的工作流程类型为服务。然后,只需确保窗口顶部显示:“服务接收所选的文本”。然后,你就可以使用Automator操作与传递给后续操作的所选文本进行交互。不幸的是,并非所有程序都兼容服务。

6
为了看到它的工作原理,请尝试这个非常简单的Automator服务:
在Automator中创建一个“服务”,并选择“文本”和“每个应用程序”作为输入。
第一个工作流步骤是“执行AppleScript”。
AppleScript的“input”参数包含所选文本。
将AppleScript设置为:
on run {input, parameters}
    display dialog (input as text)
    return input
end run

保存后,每当您选择文本时,就可以在上下文菜单中使用此操作。也许命名不同,我不知道英文描述。但我希望这是一个很好的起点。祝玩得开心,Michael / Hamburg。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接