MacOS下如何实现通过iTerm用NeoVim打开选中文件?
在macOS的「打开方式」中添加通过NeoVim打开文件的选项
我希望在macOS的*「打开方式」*列表中添加一个选项,用于通过NeoVim打开文件。具体来说,就是打开一个新的iTerm终端窗口,执行命令启动NeoVim并打开选中的文件。
最初的Shell脚本尝试
我创建了一个.app文件并放置在/Applications目录下,其可执行文件为一个shell脚本,代码如下:
#!/bin/sh osascript <<EOF tell application "iTerm" activate set new_window to (create window with default profile) set cSession to current session of new_window tell new_window tell cSession delay 0.1 write text "\"echo it's working\"" delay 2 repeat delay 0.1 -- display dialog cSession is at shell prompt set isdone to is at shell prompt if isdone then exit repeat end repeat end tell end tell end tell EOF
该脚本可以成功启动iTerm并执行测试命令,但我无法获取选中文件的路径。我尝试使用$1、$2等命令行参数,以及运行declare -p查看所有变量,都未能找到目标文件路径。
成功的AppleScript实现方案
后来我改用AppleScript实现了需求,以下是使用的AppleScript代码:
on run -- app double-clicked or script run from editor open (choose file with multiple selections allowed) end run on open theItems -- droplet -- 将所有文件路径用引号包裹后拼接成字符串 set pathList to {} repeat with itemPath in theItems set end of pathList to quoted form of POSIX path of itemPath end repeat set AppleScript's text item delimiters to space set pathString to pathList as text set AppleScript's text item delimiters to "" doStuff(pathString) end open on doStuff(pathString) -- 核心执行逻辑 tell application "iTerm" activate set new_window to (create window with default profile) set cSession to current session of new_window tell new_window tell cSession delay 0.1 write text "nvim " & pathString end tell end tell end tell end doStuff
内容的提问来源于stack exchange,提问作者Yaroslav Biloshytskyi
相关产品推荐
相关产品推荐

