【问题标题】:Applescript: Pasting Clipboard Text into Open/Save Dialog BoxApplescript:将剪贴板文本粘贴到打开/保存对话框中
【发布时间】:2016-11-16 19:48:31
【问题描述】:

我有许多未命名的 TextEdit 文件。我想使用 applescript 来保存每个文档的第一行文本作为名称。

以下将选择并复制文档的第一行(不优雅,但它有效),但我不知道如何将剪贴板粘贴到保存对话框中(然后点击“保存”)。有人可以帮忙吗?

tell application "TextEdit" to activate
tell application "TextEdit"

tell application "System Events" to key code 126 using command down
tell application "System Events" to key code 125 using shift down
tell application "System Events" to key code 8 using command down


end tell

【问题讨论】:

  • 只需使用提供名称和路径的“另存为”指令。
  • 名字在剪贴板上。我想以这种方式自动命名。

标签: applescript textedit


【解决方案1】:

有两种方法:

1) 使用 GUI 脚本的方法:这是您已经开始做的事情。您可以像用户一样模拟键盘事件。不推荐它主要有 3 个原因: 它通常很慢(您需要添加延迟以留出系统打开窗口的时间,关闭它们,..)。在脚本执行过程中,如果用户误按了键/鼠标,您的脚本将失败。最后,您几乎不依赖应用程序的用户界面:如果编辑器(此处为 Apple 与 TextEdit)更改了某些内容,例如快捷键,您的脚本将不再工作。

尽管如此,如果您仍想以这种方式使用,这里是为您执行此操作的脚本。我建议您像我一样添加 cmets(如何记住键码 8 是 'c' !)。我添加了一些额外的选项来选择要保存的路径(转到主文件夹,输入特殊路径,...)。使用与否由您决定:

tell application "TextEdit"
activate
tell application "System Events"
    key code 126 using command down -- command up (cursor at start)
    key code 125 using shift down -- shift down (select 1st line)
    keystroke "c" using command down -- command C (copy)
    keystroke "s" using command down -- open save dialog
    delay 0.5 -- to let save as dialog time to open
    keystroke "v" using command down -- paste the title from clipboard

    -- other options
    -- keystroke "h" using {command down, shift down} -- go home directory
    delay 0.5
    keystroke "g" using {command down, shift down} -- go to dialog
    delay 0.5
    keystroke "Desktop/Sample" -- path from Documents folder to Sample folder on Desktop
    delay 0.5
    keystroke return -- close the go to dialog
    delay 0.5

    keystroke return -- close the save as dialog
end tell
end tell

2) 使用Applescript指令的方法。它通常更短,更优雅的脚本,运行速度更快,并且用户在执行过程中不能破坏它。下面的脚本与上面的脚本相同:它选择第一个文本行并使用该标题保存文档。第 1 行定义了保存的文件夹:

set myPath to (path to desktop folder) as string -- path where to save file
tell application "TextEdit"
activate
tell front document
    set myTitle to first paragraph
    set myTitle to text 1 thru -2 of myTitle -- to remove the return at end of paragraph
    save in (myPath & myTitle)
end tell
end tell

希望对你有帮助

【讨论】:

  • 我正在尝试在我自己的脚本中使用您的 #2 答案并调用 BBEdit,但我收到错误消息“无法获取文档的第 1 段”。这是在 Sierra 和 Applescript 2.5 上。你知道问题可能是什么吗?好像不是BBEdit;我可以将 BBEdit 与其他脚本一起使用。我应该打开一个新问题吗?
  • 根据您得到的错误,看起来您正在运行脚本而没有打开 TextEdit 文档,或者打开的文档不包含第一段....或者它是一个错误塞拉。我没有 Sierra,但许多论坛都在报告 Sierra 上的 Applescript 错误。
  • 谢谢,我发现问题在于如何让 Applescript 感知 BBEdit。我需要使用正则表达式来访问 BBEdit 文档的内容,所以我现在使用 GUI 脚本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-18
  • 1970-01-01
  • 2020-05-27
  • 2022-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多