Lightline.vim: How I can get path in component "filename" truncated to 'c/w/d/e/example.txt'?

Created on 1 Dec 2020  路  4Comments  路  Source: itchyny/lightline.vim

Hi there!

I would like to know if there's a way to get a _truncated-style path_ in "filename" component, where it outputs the path from the current working directory (cwd)?
Example:
From cwd exampleDir/subDir/fileExample.txt I want to get e/s/fileExample.txt.

I've tried to research for this solution on my own, but I am unable to find a way to achieve it. Could please guide me on how to achieve it? I can write the component function on my own, I just can't figure an algorithm in VimScript to do it. I've tried researching help for any similar function.

I have noticed that by default without this plugin, Vim provides this result for tab names.
Also, I don't mean to get an absolute path, which I can get with expand('%p').

Most helpful comment

Thank you, that works!
I haven't thought of searching under the keywords "shorten path".

If anyone else is looking for the solution _(with truncating on specified window width)_, I did this way:

function! LightlineFileName()
let l:filePath = expand('%')
    if winwidth(0) > 160
        return l:filePath
    else
        return pathshorten(l:filePath)
    endif
endfunction

All 4 comments

There is no easy way to do this but you can:

echo join(map(split(expand('%:h'), '/'), 'v:val[0] . "/"'), '') . expand('%:t')

Oops, there is 'pathshorten()' available!

echo pathshorten(expand('%'))
echo pathshorten(expand('%'), 2)

Thank you, that works!
I haven't thought of searching under the keywords "shorten path".

If anyone else is looking for the solution _(with truncating on specified window width)_, I did this way:

function! LightlineFileName()
let l:filePath = expand('%')
    if winwidth(0) > 160
        return l:filePath
    else
        return pathshorten(l:filePath)
    endif
endfunction

To make this work, define a component_function and add filename to your g:lightline:

let g:lightline = {
      \ 'colorscheme': 'solarized',
      \ 'active': {
      \   'left': [ [ 'mode', 'paste' ],
      \             [ 'readonly', 'filename', 'modified' ] ],
      \   'right': [ [ 'lineinfo' ],
      \              [ 'percent' ],
      \              [ 'fileformat', 'fileencoding', 'filetype' ] ]
      \ },
      \ 'inactive': {
      \   'left': [ [ 'mode', 'paste' ],
      \             [ 'readonly', 'filename', 'modified' ] ],
      \   'right': [ [ 'lineinfo' ],
      \              [ 'percent' ],
      \              [ 'fileformat', 'fileencoding', 'filetype' ] ]
      \ },
      \ 'component_function': {
      \   'filename': 'LightlineTruncatedFileName'
      \ }
      \ }

function! LightlineTruncatedFileName()
let l:filePath = expand('%')
    if winwidth(0) > 100
        return l:filePath
    else
        return pathshorten(l:filePath)
    endif
endfunction
Was this page helpful?
0 / 5 - 0 ratings