How to set the color only for the result of mapping vim function?

I've got this on my vimrc:

nmap <F3> i<C-R>=strftime("%Y-%a-%m-%d %I:%M %R")<CR><Esc>
imap <F3> <C-R>=strftime("%Y-%a-%m-%d %I:%M %R")<CR>

When I press F3 on vim editor, it returns something like datetime. But I don't know how can I set a different color for this.

I found some other functions that seems do it on https://manpages.debian.org but I don't know for sure... Any idea?

Upvotes: 1

Views: 173

Answers (1)

romainl
romainl

Reputation: 196751

The function you are calling in your mapping is not an external function/command/whatever: it is a Vim function that only returns plain text, without any highlighting information whatsoever.

This has two consequences:

  • all the manpages you will find on that site are irrelevant,
  • you will have to handle that highlighting yourself, in Vim, outside of those mappings.

First, you could simplify your pair of mappings a bit:

inoremap <F3> <C-R>=strftime("%Y-%a-%m-%d %I:%M %R")<CR>
nmap <F3> i<F3><Esc>

Second: if it is a one-shot, you can get away with something like the following:

:match Directory /\d\{4}-\w\{3}-\d\{2}-\d\{2}\s\d\{2}:\d\{2}\s\d\{2}:\d\{2}/

which matches a date as returned by your :help strftime() call and assigns it to the default Directory highlight group (that's the first one that came to mind):

enter image description here

See :help :match.

Third, if you want it to be automatic, you will have to delve a little more into syntax highlighting, which is a two-steps process:

  1. you define syntax groups with :help syntax,
  2. you apply visual attributes to those groups with :help :highlight.

Assuming you want this to happen in buffers with filetype foo, you can create ~/.vim/after/syntax/foo.vim where you can define your own syntax group:

syntax match MyDate /\d\{4}-\w\{3}-\d\{2}-\d\{2}\s\d\{2}:\d\{2}\s\d\{2}:\d\{2}/

and link it to a default group:

highlight link MyDate Directory

If you prefer to handle the visual attributes of that specific highlight group yourself, you can follow the method described in this gist.

Upvotes: 3

Related Questions