2

Given these file names, I want to get the corresponding value:

Chart.js          => C.j
chart.js          => c.j
chart-type.js     => ct.j
ChartType.js      => CT.j
_chart-type.scss  => ct.s

Here is my vimscript which only returns the first letter.
As you can see my main motivation is to shorten names in airline tabline extension.

function! airline#extensions#tabline#formatters#default#format(bufnr, buffers)
      return strpart(fnamemodify(bufname(a:bufnr), ':t'), 0, 1)
endfunction
4

I tried this code (written in /tmp/vim.vim):

fu! Shorten_filename() abort
    let bufname = fnamemodify(bufname('%'), ':t')
    let tokens = split(bufname, '\ze\u\|[-_]')
    call map(tokens, {i,v -> matchstr(v, '\a')})
    let ext = fnamemodify(bufname, ':e')
    return join(tokens, '').(!empty(ext) ? '.'.ext[0] : '')
endfu

set laststatus=2
set stl+=%{Shorten_filename()}

Then started Vim like this:

vim -Nu /tmp/vim.vim Chart.js chart.js chart-type.js ChartType.js _chart-type.scss

And executed :next to review each buffer in the argument list. The statusline displayed successively:

  • C.j
  • c.j
  • ct.j
  • CT.j
  • ct.s

So, I guess you could try it as a base for your script. Maybe something like:

function! airline#extensions#tabline#formatters#default#format(bufnr, buffers)
    let bufname = fnamemodify(bufname(a:bufnr), ':t')
    let tokens = split(bufname, '\ze\u\|[-_]')
    call map(tokens, {i,v -> matchstr(v, '\a')})
    let ext = fnamemodify(bufname, ':e')
    return join(tokens, '').(!empty(ext) ? '.'.ext[0] : '')
endfunction
2
  • That's awesome! You just made my day :-) – Amin Roosta Feb 23 '18 at 5:20
  • 1
    nitpick: I think you can leave out the \zs (which looks funny anyhow) – Christian Brabandt Feb 23 '18 at 6:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.