2016-11-16 412 views
0

我有许多无标题的TextEdit文件。我想使用applescript来保存每个文档的顶部行的文本作为名称。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 
+0

只需使用“另存为”命令提供的名称和路径。 – pbell

+0

该名称在剪贴板上。我想通过这种方式自动命名。 – Jimmbo

回答

0

有2种方法做的:

1)使用GUI脚本的方法:这是你已经开始做了。您可以像用户一样模拟键盘事件。这主要不是因为3个原因而推荐的:它通常很慢(您需要添加延迟来为系统打开窗口留出时间,关闭它们,..)。在脚本期间,如果用户误击了键/鼠标,您的脚本将失败。最后,你几乎不依赖于应用程序的用户界面:如果编辑器(这里是带有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 

我希望它能帮助