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

五迷三道 提交于 2019-12-18 04:54:08

问题


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

回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/6538779/what-is-a-vimrc-function-to-determine-if-a-buffer-has-been-modified

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!