macOS 使用 Vim 打开文件

macOS 使用 Vim 打开文件

原理,Automator.app + AppleScript

步骤

  1. 打开 Automator.app
  2. 创建新项目
    New
  3. 选择 Application
    Application
  4. 搜索 Run AppleScript
    AppleScript
  5. 编写脚本
  • 可以把其中的 "Terminal" 改为你喜欢的终端
  • 大概意思是,循环从输入中获取文件路径,如果文件可写,直接打开,否则使用 sudo 打开
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    on run {input, parameters}
    tell application "Terminal"
    activate
    set firstTab to true
    repeat with aFile in input
    set filename to POSIX path of aFile
    set quotedFilename to quoted form of filename
    set cmd to "if [ -w \"$FILENAME\" ]; then vim \"$FILENAME\"; else sudo vim \"$FILENAME\"; fi"

    if firstTab then
    do script "FILENAME=" & quotedFilename & "; " & cmd
    set firstTab to false
    else
    do script "FILENAME=" & quotedFilename & "; " & cmd in (do script "")
    end if
    end repeat
    end tell
    end run
  1. 保存,选择你喜欢的名称
  2. 右键你想用 Vim 打开的文件,选择 Get Info -> Open With -> 选择你刚刚保存的应用 -> 点击 Change All
    Get Info
    Open With
  3. Enjoy it!