Search code examples
fishtab-completion

How to expand environment variables using keyboard shortcut in Fish?


In Bash, the shortcut Esc Ctrl-e can be used to expand an environment variable at the shell:

$ echo $PATH
/home/joe

$ $PATH<Press Esc Ctrl-e>
$ /home/joe

Is there a shortcut to achieve something similar in Fish?


Solution

  • You could do something like this

    function bind_expand_all
        # what are the tokens of the current command line
        set tokens (commandline --tokenize)
        # erase the current command line (replace with empty string)
        commandline -r ""
        for token in $tokens
            # append the expanded value of each token followed by a space
            commandline -a (eval echo $token)" "
        end
        # move the cursor to the end of the new command line
        commandline -C (string length (commandline))
    end
    

    then

    bind \e\ce bind_expand_all
    

    And if this is your current command line (with the cursor at the underscore):

    $ echo $HOME (date -u)_
    

    when you hit AltCtrle, you get

    $ echo /home/jackman Thu May 10 19:27:18 UTC 2018 _
    

    To store that binding permanently, add it to your fish_user_key_bindings function (create it if it does not exist):

    Key bindings are not saved between sessions by default. Bare bind statements in config.fish won't have any effect because it is sourced before the default keybindings are setup. To save custom keybindings, put the bind statements into a function called fish_user_key_bindings, which will be autoloaded.


    A little nicer:

    function bind_expand_all
        set -l expanded
        for token in (commandline --tokenize)
            set expanded $expanded (eval echo $token)
        end
        set -l new (string join " " $expanded)
        commandline -r $new
        commandline -C (string length $new)
    end