Search code examples
variableszshprompt

zsh declare PROMPT using multiple lines


I would like to declare my ZSH prompt using multiple lines and comments, something like:

PROMPT="
    %n       # username
    @
    %m       # hostname
    \        # space
    %~       # directory
    $
    \        # space
"

(e.g. something like perl regex's "ignore whitespace mode")

I could swear I used to do something like this, but cannot find those old files any longer. I have searched for variations of "zsh declare prompt across multiple lines" but haven't quite found it.

I know that I can use \ for line continuation, but then we end up with newlines and whitespaces.

edit: Maybe I am misremembering about comments - here is an example without comments.


Solution

  • Not exactly what you are looking for, but you don't need to define PROMPT in a single assignment:

    PROMPT="%n"    # username
    PROMPT+="@%m"  # @hostname
    PROMPT+=" %~"  # directory
    PROMPT+="$ "
    

    Probably closer to what you wanted is the ability to join the elements of an array:

    prompt_components=(
       %n   # username
       " "  # space
       %m   # hostname
       " "  # space
       "%~"  # directory
       "$"
    )
    PROMPT=${(j::)prompt_components}
    

    Or, you could let the j flag add the space delimiters, rather than putting them in the array:

    # This is slightly different from the above, as it will put a space
    # between the director and the $ (which IMO would look better).
    # I leave it as an exercise to figure out how to prevent that.
    prompt_components=(
     "%n@%m"  # username@hostname
     "$~"  # directory
     "$" 
    )
    
    PROMPT=${(j: :)prompt_components}