Uroc327
Uroc327

Reputation: 1429

statusline highlight group from function has no effect

In my vim configuration I have a function like

function! StatuslineTrailingSpace()
  if !exists('b:statusline_trailing_space_warning')
    let b:statusline_trailing_space_warning = &modifiable ? search('\s\+$', 'nw') != 0 ? ' %#warningmsg#[\s]%*' : '' : ''
  endif

  return b:statusline_trailing_space_warning
endfunction

and then somewhere later the line

set statusline+=%{StatuslineTrailingSpace()}

But instead of a colored [\s] tag in the statusline I see the full %#warningmsg#[\s]%* string.

Trying to use %! instead of %{} as proposed in this answer does not seem to work as my vim gives the error

line   70:
E539: Illegal character <!>: statusline+=%!StatuslineTrailingSpace()

How can I get the colored statusline working?

Upvotes: 1

Views: 564

Answers (2)

romainl
romainl

Reputation: 196886

The highlight group should be in the 'statusline' option, not in the expression:

function! StatuslineTrailingSpace()
  if !exists('b:stsw')
    let b:stsw = &modifiable ? search('\s\+$', 'nw') != 0 ? ' [\s]' : '' : ''
  endif

  return b:stsw
endfunction

set statusline+=%#warningmsg#%{StatuslineTrailingSpace()}%*

Upvotes: 1

dash-tom-bang
dash-tom-bang

Reputation: 17883

My suspicion is that you must use the %! construct to get access to the buffer. However, since the docs imply that %! must start at the beginning of the option, your best bet is likely going to be to save off the current statusline and then use your function to return the whole thing.

function! StatuslineTrailingSpace()
  if !exists('b:statusline_trailing_space_warning')
let b:statusline_trailing_space_warning = &modifiable ? search('\s\+$', 'nw') != 0 ? ' %#warningmsg#[\s]%*' : '' : ''
  endif

  return s:former_status_line . b:statusline_trailing_space_warning
endfunction

let s:former_status_line = &statusline
set statusline=%!StatuslineTrailingSpace()

Something like that?

Upvotes: 2

Related Questions