Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a vimrc function to determine if a buffer has been modified?

Tags:

vim

tabs

I have a tabline function that I stole/modified from somewhere, but I would like the filename to have an asterisk before it if it has been modified since the last time it was written to disk (ie if :up would perform an action).

For example this is my tabline when I open vim -p file*.txt

file1.txt file2.txt file3.txt

Then after I change file1.txt and don't save it:

*file1.txt file2.txt file3.txt

My tabline function:

if exists("+showtabline")
   function MyTabLine()
      let s = ''
      let t = tabpagenr()
      let i = 1
      while i <= tabpagenr('$')
         let buflist = tabpagebuflist(i)
         let winnr = tabpagewinnr(i)
         let s .= ' %*'
         let s .= (i == t ? '%#TabLineSel#' : '%#TabLine#')
         let file = bufname(buflist[winnr - 1])
         let file = fnamemodify(file, ':p:t')
         if file == ''
            let file = '[No Name]'
         endif
         let s .= file
         let i = i + 1
      endwhile
      let s .= '%T%#TabLineFill#%='
      let s .= (tabpagenr('$') > 1 ? '%999XX' : 'X')
      return s
   endfunction
   set stal=2
   set tabline=%!MyTabLine()
endif
like image 632
Philip Avatar asked Jun 30 '11 17:06

Philip


2 Answers

I was just looking for the same and found that %m and %M is not well suited, as it tells you whether the currently open buffer is modified. So you cannot see if other buffers are modified (especially for tabs, this is important).

The solution is the function getbufvar. Roughly from the help:

let s .= (getbufvar(buflist[winnr - 1], "&mod")?'*':'').file

instead of

let s .= file

should do the trick. This can be used nicely to show all buffers open in one tab (in case of multiple splits).

like image 173
bitmask Avatar answered Oct 09 '22 01:10

bitmask


tabline uses similar flags as statusline (see :h statusline). So %m is what you need and modifying the lines just before the endwhile as

let s .= file
let s .= (i == t ? '%m' : '')
let i = i + 1

will automatically place the default [+] after the file name in the current tab if there are unsaved changes.

like image 37
abcd Avatar answered Oct 09 '22 01:10

abcd