Applescript:将剪贴板文本粘贴到打开/保存对话框中

时间:2016-11-16 19:48:31

标签: applescript textedit

我有许多无标题的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

1 个答案:

答案 0 :(得分:0)

有两种方法:

1)使用GUI脚本的方法:这是您已经开始做的事情。您可以像用户一样模拟键盘事件。建议不要主要有三个原因:它通常很慢(您需要添加延迟以留出系统打开窗口的时间,关闭它们,......)。在脚本中,如果用户误击键/鼠标,则脚本将失败。最后,您几乎不依赖于应用程序的用户界面:如果编辑器(此处带有TextEdit的Apple)发生了某些变化,例如快捷键,则您的脚本将不再有效。

尽管如此,如果您仍然希望使用这种方式,那么这是为您执行此操作的脚本。我建议你像我一样添加评论(如何记住密钥代码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

我希望它有所帮助