【发布时间】:2012-05-07 21:16:12
【问题描述】:
我正在使用nslater's wonderful script 计算选定文本块中的单词和字符,但我需要两个增强功能:
即使没有选择文本,脚本也可用。 目前,当我在没有选择的情况下拉出可用服务列表时,服务不存在(当然,这是合乎逻辑的,但增强 #2 会改变一些事情)。
向脚本添加条件行为:如果没有选择文本,则处理所有文本,但如果有选择,则只处理选中的文本文本。
这是 nslater 的脚本,我将其粘贴到 Automator 中(我按照他注释说明中的步骤创建了服务):
# Word and Character Count service for Mac OS X
#
# Adds a Word and Character Count option to the text selection context menu in all apps
#
# Use Automator.app to create a new service, and then select the Run AppleScript action.
# Paste this code in to the text box, and save as Word and Character Count. Now switch to
# a new app, select some text, and open the context menu to find the new option.
on run {input, parameters}
tell application "System Events"
set _appname to name of first process whose frontmost is true
end tell
set word_count to count words of (input as string)
set character_count to count characters of (input as string)
tell application _appname
display alert "" & word_count & " words, " & character_count & " characters"
end tell
return input
end run
【问题讨论】:
-
服务不是这样工作的。操作系统安排服务接收所需的输入。如果服务接受输入,那么它仅在有选择时可用。如果服务不接受输入,那么服务就没有可靠的方法来获取选定的文本(或所有文本)。
-
感谢@KenThomases。因此,如果我理解正确,我需要做的是使用 Keyboard Maestro 或其他东西设置一个宏来启动文本选择逻辑,然后调用服务。
-
也许吧。我不熟悉键盘大师,但也许它允许直接调用脚本,这根本不涉及服务。
-
@KenThomases:实际上,如果您将服务用作哑启动器(“无输入”)并使用 Accessibility API 检索文本选择的状态,则可以这样做。请参阅my answer 了解如何做到这一点。在 Applescript 中尽可能接近文本系统,我认为……
标签: text osx-lion applescript