Skip to content

iterm2: ⌘-clickでnvimが開くようにする #8

@ultimatile

Description

@ultimatile

iTerm2で表示されているURLやfile pathを⌘-clickすると既定のアプリや指定したcommandを実行することができる.
URLならopen, pathならnvimで分岐するbash scriptを作成した.
nvimで開く場合新しいiTerm2のwindowにしたいのでAppleScriptの力を借りている.

#!/bin/bash

# Get the clicked text
FILENAME="$1"
OPTIONS="$2"
# Regex to detect URLs
URL_REGEX="^(http|https|ftp|file)://"

# Check if the input is a URL
if [[ "$FILENAME" =~ $URL_REGEX ]]; then
  # Open URL in the default browser
  open "$FILENAME"
else
  # Use AppleScript to open a new iTerm2 window and execute Neovim
  osascript <<EOF
tell application "iTerm"
    create window with default profile
    tell current session of current window
        if "$OPTIONS" is not equal to "" then
            write text "nvim ${OPTIONS} '${FILENAME}'"
        else
            write text "nvim '${FILENAME}'"
        end if
    end tell
end tell
EOF
fi

上記のscriptを/path/to/run_nvim.shとして保存したとしてchmod +x /path/to/run_nvim.shを実行.
iTerm2の設定でProfiles>Advanced>Semantic Historyの項目でRun coprocess...を選択.
実行commandとして/path/to/run_nvim.sh \1 \+\2を入力.
\1はclickしたfile名.\2は行番号.nvim +行番号で指定した行番号で開ける.
他に\3, \4はそれぞれclickした箇所から左側と右側の文字列を取得する.\5pwd相当.


上記の方法だとtargetがfile pathで例えばPDFやPNGなどのnvimで開けないものを開いた場合が問題になるので
iTerm2側の設定ではdefault値のOpen with default appのままにしておき,新しいiTerm2のwindowでnvimを起動するscriptをapp化して既定のappとして設定する方が汎用的だと思われる.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions