fish-shell/share/functions/__fish_preview_current_file.fish

34 lines
1.1 KiB
Fish
Raw Normal View History

function __fish_preview_current_file --description "Open the file at the cursor in a pager"
Open command script in external editor on Alt+o Fish functions are great for configuring fish but they don't integrate seamlessly with the rest of the system. For tasks that can run outside fish, writing scripts is the natural approach. To edit my scripts I frequently run $EDITOR (which my-script) Would be great to reduce the amount typing for this common case (the names of editor and scripts are usually short, so that's a lot of typing spent on the boring part). Our Alt+o binding opens the file at the cursor in a pager. When the cursor is in command position, it doesn't do anything (unless the command is actually a valid file path). Let's make it open the resolved file path in an editor. In future, we should teach this binding to delegate to "funced" upon seeing a function instead of a script. I didn't do it yet because funced prints messages, so it will mess with the commandline rendering if used from a binding. (The fact that funced encourages overwriting functions that ship with fish is worrysome. Also I'm not sure why funced doesn't open the function's source file directly (if not sourced from stdin). Persisting the function should probably be the default.) Alternative approach: I think other shells expand "=my-script" to "/path/to/my-script". That is certainly an option -- if we do that we'd want to teach fish to complete command names after "=". Since I don't remember scenarios where I care about the full path of a script beyond opening it in my editor, I didn't look further into this. Closes #10266
2024-01-26 18:06:17 +08:00
if __fish_edit_command_if_at_cursor
return 0
end
set -l pager (__fish_anypager)
or set pager cat
# commandline -t will never return an empty list. However, the token
# could comprise multiple lines, so join them into a single string.
set -l file (commandline -t | string collect)
set -l prefix eval set
if test -z $file
# $backslash will parsed as regex which may need additional escaping.
set -l backslash '\\\\'
not status test-feature regex-easyesc && set backslash $backslash$backslash
set file (string replace -ra -- '([ ;#^<>&|()"\'])' "$backslash\$1" (commandline -xc)[-1])
set prefix set
end
set -q file[1] || return
# strip -option= from token if present
set file (string replace -r -- '^-[^\s=]*=' '' $file | string collect)
$prefix -l files $file || return # Bail if $file does not tokenize.
if set -q files[1] && test -f $files[1]
$pager $files
commandline -f repaint
end
end