zsh: update prompt with current time when a command is started

cbowns picture cbowns · Oct 29, 2012 · Viewed 12.1k times · Source

I have a zsh prompt I rather like: it evaluates the current time in precmd and displays that on the right side of the prompt:

[Floatie:~] ^_^ 
cbowns%                      [9:28:31 on 2012-10-29]

However, this isn't exactly what I want: as you can see below, this time is actually the time the previous command exited, not the time the command was started:

[Floatie:~] ^_^ 
cbowns% date                           [9:28:26 on 2012-10-29]
Mon Oct 29 09:28:31 PDT 2012
[Floatie:~] ^_^ 
cbowns% date                           [9:28:31 on 2012-10-29]
Mon Oct 29 09:28:37 PDT 2012
[Floatie:~] ^_^ 
cbowns%                                [9:28:37 on 2012-10-29]

Is there a hook in zsh to run a command just before the shell starts a new command so I can update the prompt timestamp then? (I saw Constantly updated clock in zsh prompt?, but I don't need it constantly updated, just updated when I hit enter.)

(The ^_^ is based on the previous command's return code. It shows ;_; in red when there's a nonzero exit status.)

Answer

nitarshan picture nitarshan · Jul 29, 2013

This is in fact possible without resorting to strange hacks. I've got this in my .zshrc

RPROMPT='[%D{%L:%M:%S %p}]'

TMOUT=1

TRAPALRM() {
    zle reset-prompt
}

The TRAPALRM function gets called every TMOUT seconds (in this case 1), and here it performs a prompt refresh, and does so until a command starts execution (and it doesn't interfere with anything you type on the prompt before hitting enter). I know you don't need it constantly refreshed but it still gets the job done without needing a line for itself!

Source: http://www.zsh.org/mla/users/2007/msg00944.html (It's from 2007!)