The following Vim script (VimL) code snippet can be used to replace the full path of a home directory in a string with a tilde (“~”). This can be useful as a way to shorten the path to a file or directory, making it more readable.
" Language: Vim script
" Author: James Cherti
" License: MIT
" Description: A function that replaces the home directory
" with a tilde (e.g. '/home/user/file.txt' will
" be replaced with '~/file.txt').
" URL: https://www.jamescherti.com/vim-script-replace-the-home-directory-with-a-tilde/
function! ReplaceHomeWithTilde(path) abort
let l:path = fnamemodify(a:path, ':p')
let l:path_sep = (!exists('+shellslash') || &shellslash) ? '/' : '\'
let l:home = fnamemodify('~', ':p')
if l:path[0:len(l:home)-1] ==# l:home
return '~' . l:path_sep . l:path[len(l:home):]
elseif l:path == l:home
return '~' . l:path_sep
endif
return l:path
endfunction
Code language: Vim Script (vim)