Print arglist same way as :ls - vim

:ls
1 h "~/Documents/trash/practical-vim" line 1
3 h "LICENSE.txt" line 1
4 h "auto_complete/sea-shells.txt" line 1
5 h "files/a.txt" line 1
6 h "files/b.txt" line 1
output of ls command, you can use :b3 to switch to buffer 3, what I want is the same output for :args command, but what I get:
:args
[auto_complete/webapp/public/index.html] ex_mode/practical-vim.html files/mvc/index.html global/episodes.html
i.e. arglist params are printed in one line, which makes usage of :argument3 (to switch to third file in arglist) basically impossible if amount of files is huge. I want these files to be printed on new line with number by which I can access these files like in :ls command.
I tried to write a simple command for this scenario:
command! Args
\ :let var_args = argv()
\ :let var_args_size = len(var_args)
\ :if var_args_size > 0 | let var_args_size = var_args_size - 1 | endif
\ :for i in range(0, var_args_size) | echo printf("%3d %s", i + 1, var_args[i]) | endfor
But:
E15: Invalid expression: argv() :let var_args_size = len(var_args) :if var_args_size > 0 | let var_args_size = var_args_size - 1 | endif
:for i in range(0, var_args_size) | echo printf("%3d %s", i + 1, var_args[i]) | endfor
I kindly request assistance either with my command or some other way to print arglist like this:
:args
1 auto_complete/webapp/public/index.html
2 ex_mode/practical-vim.html
3 files/mvc/index.html
4 global/episodes.html
so i can execute :argument3 and switch to files/mvc/index.html without counting.

You are way beyond the point at which nifty one-liners become liabilities.
Using a function is much cleaner:
function! Args()
let var_args = argv()
let var_args_size = len(var_args)
if var_args_size > 0
let var_args_size = var_args_size - 1
endif
for i in range(0, var_args_size)
echo printf("%3d %s", i + 1, var_args[i])
endfor
endfunction
command! Args call Args()
How about a more interactive approach?
function! Args()
let prompt = 'Select an argument:'
let arg_list = map(argv(), 'v:key + 1 . ". " . v:val')
let chosen_arg = inputlist([prompt] + arg_list))
if chosen_arg
execute 'argument ' . chosen_arg
endif
endfunction
command! Args call Args()
See :help map(), :help inputlist().

Just one line
command! -bar Args echo join(map(argv(), {_, v -> printf("%3d\t%s", bufnr(v), v)}), "\n")
It shows buffer number instead of argument index, so :bX to switch buffer.

Related

Get live word count for document in vim

I would like vim to display the total document word count in the status bar (where the current line and character number are displayed). I have come across similar questions on SO, and have tried all the suggestions mentioned here and here --- and none of them had any effect whatsoever on my status bar.
To explicitly name a few, I tried to paste any of the following in my ~/.vimrc (and ofc subsequently restarted vim):
function! CountNonEmpty()
let l = 1
let char_count = 0
while l <= line("$")
if len(substitute(getline(l), '\s', '', 'g')) > 3
let char_count += 1
endif
let l += 1
endwhile
return char_count
endfunction
function WordCount()
let s:old_status = v:statusmsg
exe "silent normal g\<c-g>"
let s:word_count = str2nr(split(v:statusmsg)[11])
let v:statusmsg = s:old_status
return s:word_count
endfunction
" If buffer modified, update any 'Last modified: ' in the first 20 lines.
" 'Last modified: ' can have up to 10 characters before (they are retained).
" Restores cursor and window position using save_cursor variable.
function! LastModified()
if &modified
let save_cursor = getpos(".")
let n = min([15, line("$")])
keepjumps exe '1,' . n . 's#^\(.\{,10}LOC:\).*#\1' .
\ ' ' . CountNonEmpty() . '#e'
keepjumps exe '1,' . n . 's#^\(.\{,10}Word Count:\).*#\1' .
\ ' ' . WordCount() . '#e'
call histdel('search', -1)
call setpos('.', save_cursor)
endif
endfun
OR
function WordCount()
let s:old_status = v:statusmsg
exe "silent normal g\<c-g>"
let s:word_count = str2nr(split(v:statusmsg)[11])
let v:statusmsg = s:old_status
return s:word_count
endfunction
set statusline=wc:%{WordCount()}
OR
function! WordCount()
let s:old_status = v:statusmsg
let position = getpos(".")
exe ":silent normal g\<c-g>"
let stat = v:statusmsg
let s:word_count = 0
if stat != '--No lines in buffer--'
let s:word_count = str2nr(split(v:statusmsg)[11])
let v:statusmsg = s:old_status
end
call setpos('.', position)
return s:word_count
endfunction
set statusline=wc:%{WordCount()}
OR
let g:word_count="<unknown>"
fun! WordCount()
return g:word_count
endfun
fun! UpdateWordCount()
let s = system("wc -w ".expand("%p"))
let parts = split(s, ' ')
if len(parts) > 1
let g:word_count = parts[0]
endif
endfun
augroup WordCounter
au! CursorHold * call UpdateWordCount()
au! CursorHoldI * call UpdateWordCount()
augroup END
" how eager are you? (default is 4000 ms)
set updatetime=500
" modify as you please...
set statusline=%{WordCount()}\ words
or many many more. And as I said there wa no efect. No error message, no visually perceptible change. I guess there may be a common issue which I am missing, but what is it?
Assuming your status line is enabled (set laststatus=2), the following:
set statusline+=%{wordcount().words}\ words
does exactly what you want in Vim version 7.4.1042 and above:
See :help wordcount().
If you absolutely need backward compatibility, the following is pretty much guaranteed to work in Vim 7.x, and will probably also work in earlier versions:
function! WC()
return len(split(join(getline(1,'$'), ' '), '\s\+'))
endfunction
set statusline+=%{WC()}\ words
Some of the answers from those old threads may be faster or smarter, though.
Your comments about those functions from those old threads not changing anything to your status line make me wonder if the problem is in all those old answers or elsewhere. Maybe… you don't have a status line to begin with?
Word count in vim-airline
Word count is provided standard by vim-airline for a number of file types, being at the time of writing:
asciidoc, help, mail, markdown, org, rst, tex ,text
If word count is not shown in the vim-airline, more often this is due to an unrecognised file type. For example, at least for now, the compound file type markdown.pandoc is not being recognised by vim-airline for word count. This can easily be remedied by amending the .vimrc as follows:
let g:airline#extensions#wordcount#filetypes = '\vasciidoc|help|mail|markdown|markdown.pandoc|org|rst|tex|text'
set laststatus=2 " enables vim-airline.
The \v statement overrides the default g:airline#extensions#wordcount#filetypes variable. The last line ensures vim-airline is enabled.
In case of doubt, the &filetype of an opened file is returned upon issuing the following command:
:echo &filetype
Here is a meta-example:

pass vim argument in completefunc

I am writing a vimscript that uses completefunc as:
" GetComp: Menu and Sunroutine Completion {{{1
function! GetComp(arg, findstart, base)
if a:findstart
" locate the start of the word
let line = getline('.')
let start = col('.') - 1
while start > 0 && line[start - 1] =~ '\a'
let start -= 1
endwhile
return start
else
echomsg '**** completing' a:base
python << EOF
import vim
import os
flsts = [' ']
path = "."
for dirs, subdirs, files in os.walk(path):
for tfile in files:
if tfile.endswith(('f90', 'F90', 'f', 'F')):
ofile = open(dirs+'/'+tfile)
for line in ofile:
if line.lower().strip().startswith(vim.eval("a:arg")):
modname = line.split()[1]
flsts.append(modname)
vim.command("let flstsI = %s"%flsts)
EOF
if eval("a:arg") = "module"
for m in ["ieee_arithmatic", "ieee_exceptions", "ieee_features", "iso_c_bindings", "iso_fortran_env", "omp_lib", "omp_lib_kinds"]
if m =~ "^" . a:base
call add(flstsI, m)
endif
endfor
elseif eval("a:arg") = "subroutine"
for m in ["alarm()", "date_and_time()", "backtrace", "c_f_procpointer()", "chdir()", "chmod()", "co_broadcast()", "get_command()", "get_command_argument()", "get_environment_variable()", "mvbits()", "random_number()", "random_seed()"]
if m =~ "^" . a:base
call add(flstsI, m)
endif
endfor
endif
return flstsI
endif
endfunction
I will call it for 2 different argument as:
inoremap <leader>call call <C-o>:set completefunc=GetComp("subroutine", findstart, base)<CR><C-x><C-u>
inoremap <leader>use use <C-o>:set completefunc=GetComp("module", findstart, base)<CR><C-x><C-u>
But trying so, gives error: Unknown function GetComp(
I don't know how to call them.
If I don't use arg, then, using this reply, I can call this perfectly.
Kindly help.
You'll have to attach a context to your completion. If you look closely at my message on vi.se, you'll see a framework that permits to bind data to a user-completion. From there in your mapping, it just becomes a question of which context to attach.
A simplified way would be to execute a (preparation) function from the mappings and have the function set script global variables that will be used in your completion function.

Can I search all my registers to paste a value

Let's say I'm restructuring some text including a line that contains the text "log". After a bit more editing, I want to paste the log line, but its now in some far-off register. Is there a way to search all registers for the first that contains the term "log" and paste its contents?
The following should do the job:
function! SearchAndPasteReg()
let l:pattern = input('Reg search: ')
if l:pattern == '' | return | endif
for l:i in range(1, 9)
if match(eval('#'.l:i), l:pattern) != -1
execute printf('normal "%i]p', l:i)
return
endif
endfor
redraw | echo 'Pattern not found'
endf
nnoremap <silent> ]R :call SearchAndPasteReg()<cr>
I'm not sure if you are talking about numbered registers, or all the registers. If you want to search for all regs, just extend the range with a list containing all the desired register names, something like this:
function! SearchAndPasteReg()
let l:pattern = input('Reg search: ')
if l:pattern == '' | return | endif
let l:regs = range(char2nr('1'), char2nr('9'))
call map(extend(l:regs, range(char2nr('a'), char2nr('z'))), 'nr2char(v:val)')
for l:reg in l:regs
if match(eval('#'.l:reg), l:pattern) != -1
execute printf('normal "%s]p', l:reg)
return
endif
endfor
redraw | echo 'Pattern not found'
endf
nnoremap <silent> ]R :call SearchAndPasteReg()<cr>
One way(not very handy though) would be to redirect output to a register you don't use, lets say z.
:redir #z
list registries
:reg
And paste the result from "z in some buffer and then is searchable.
And you will also have to stop the redirection after.
:redir END
With a third party plugin maybe, but you can still use the :reg[isters] command to see the content of all your registers or :reg 0123456789 for only the numbered registers.

Unexpected behavior of Vim IDE(winmanager, minibufexpl, neerdtree, taglist)

My environment is vim with winmanager, minibufexpl, neerdtree and taglist. Now I have a problem, when I open more than one file(also the minibufexpl has two file names), and there are four windows(neerdtree window, taglist window, minibufexpl windows and opened file window). Then I use :q to quit one file, but the opened file is colsed also. I think the correct behavior is to move to the next file.
You probably want to close the buffer instead. That can also close the window, however, which may or may not be what you want.
This plugin should help with that:
http://vim.wikia.com/wiki/Deleting_a_buffer_without_closing_the_window
I additionally have this mapped in my .vimrc so I can just do a <leader>bd to close the buffer.
Edit in response to comments from OP:
Here is the code for the plugin from the link I pasted in:
" Delete buffer while keeping window layout (don't close buffer's windows).
" Version 2008-11-18 from http://vim.wikia.com/wiki/VimTip165
if v:version < 700 || exists('loaded_bclose') || &cp
finish
endif
let loaded_bclose = 1
if !exists('bclose_multiple')
let bclose_multiple = 1
endif
" Display an error message.
function! s:Warn(msg)
echohl ErrorMsg
echomsg a:msg
echohl NONE
endfunction
" Command ':Bclose' executes ':bd' to delete buffer in current window.
" The window will show the alternate buffer (Ctrl-^) if it exists,
" or the previous buffer (:bp), or a blank buffer if no previous.
" Command ':Bclose!' is the same, but executes ':bd!' (discard changes).
" An optional argument can specify which buffer to close (name or number).
function! s:Bclose(bang, buffer)
if empty(a:buffer)
let btarget = bufnr('%')
elseif a:buffer =~ '^\d\+$'
let btarget = bufnr(str2nr(a:buffer))
else
let btarget = bufnr(a:buffer)
endif
if btarget < 0
call s:Warn('No matching buffer for '.a:buffer)
return
endif
if empty(a:bang) && getbufvar(btarget, '&modified')
call s:Warn('No write since last change for buffer '.btarget.' (use :Bclose!)')
return
endif
" Numbers of windows that view target buffer which we will delete.
let wnums = filter(range(1, winnr('$')), 'winbufnr(v:val) == btarget')
if !g:bclose_multiple && len(wnums) > 1
call s:Warn('Buffer is in multiple windows (use ":let bclose_multiple=1")')
return
endif
let wcurrent = winnr()
for w in wnums
execute w.'wincmd w'
let prevbuf = bufnr('#')
if prevbuf > 0 && buflisted(prevbuf) && prevbuf != w
buffer #
else
bprevious
endif
if btarget == bufnr('%')
" Numbers of listed buffers which are not the target to be deleted.
let blisted = filter(range(1, bufnr('$')), 'buflisted(v:val) && v:val != btarget')
" Listed, not target, and not displayed.
let bhidden = filter(copy(blisted), 'bufwinnr(v:val) < 0')
" Take the first buffer, if any (could be more intelligent).
let bjump = (bhidden + blisted + [-1])[0]
if bjump > 0
execute 'buffer '.bjump
else
execute 'enew'.a:bang
endif
endif
endfor
execute 'bdelete'.a:bang.' '.btarget
execute wcurrent.'wincmd w'
endfunction
command! -bang -complete=buffer -nargs=? Bclose call s:Bclose('<bang>', '<args>')
nnoremap <silent> <Leader>bd :Bclose<CR>

How do I search the open buffers in Vim?

I'd like to search for text in all files currently open in vim and display all results in a single place. There are two problems, I guess:
I can't pass the list of open files to :grep/:vim, especially the names of files that aren't on the disk;
The result of :grep -C 1 text doesn't look good in the quickfix window.
Here is a nice example of multiple file search in Sublime Text 2:
Any ideas?
Or
:bufdo vimgrepadd threading % | copen
The quickfix window may not look good for you but it's a hell of a lot more functional than ST2's "results panel" if only because you can keep it open and visible while jumping to locations and interact with it if it's not there.
ack and Ack.vim handle this problem beautifully. You can also use :help :vimgrep. For example:
:bufdo AckAdd -n threading
will create a nice quickfix window that lets you hop to the cursor position.
Like the answer of Waz, I have written custom commands for that, published in my GrepCommands plugin. It allows to search over buffers (:BufGrep), visible windows (:WinGrep), tabs, and arguments.
(But like all the other answers, it doesn't handle unnamed buffers yet.)
I really liked romainl's answer, but there were a few sticky edges that made it awkward to use in practice.
The following in your .vimrc file introduces a user command Gall (Grep all) that addresses the issues that I found irksome.
funct! GallFunction(re)
cexpr []
execute 'silent! noautocmd bufdo vimgrepadd /' . a:re . '/j %'
cw
endfunct
command! -nargs=1 Gall call GallFunction(<q-args>)
This will allow case-sensitive searches like this:
:Gall Error\C
and case-insensitive:
:Gall error
and with spaces:
:Gall fn run
Pros
It will only open the Quickfix window, nothing else.
It will clear the Quickfix window first before vimgrepadd-ing results from each buffer.
The Quickfix window will contain the locations of all matches throughout the open buffers, not just the last visited.
Use :Gall repeatedly without any special housekeeping between calls.
Doesn't wait on errors and displays results immediately.
Doesn't allow any autocmd to run, speeding up the overall operation.
Ambivalent features
Doesn't preemptively jump to any occurrence in the list. :cn gets second result or CTRL-w b <enter> to get to the first result directly.
Cons
If there's only one result, you'll have to navigate to it manually with CTRL-w b <enter>.
To navigate to a result in any buffer quickly:
:[count]cn
or
:[count]cp
E.g. :6cn to skip 6 results down the list, and navigate to the correct buffer and line in the "main" window.
Obviously, window navigation is essential:
Ctrl-w w "next window (you'll need this at a bare minimum)
Ctrl-w t Ctrl-w o "go to the top window then close everything else
Ctrl-w c "close the current window, i.e. usually the Quickfix window
:ccl "close Quickfix window
If you close the Quickfix window, then need the results again, just use:
:cw
or
:copen
to get it back.
I made this function a long time ago, and I'm guessing it's probably not the cleanest of solutions, but it has been useful for me:
" Looks for a pattern in the open buffers.
" If list == 'c' then put results in the quickfix list.
" If list == 'l' then put results in the location list.
function! GrepBuffers(pattern, list)
let str = ''
if (a:list == 'l')
let str = 'l'
endif
let str = str . 'vimgrep /' . a:pattern . '/'
for i in range(1, bufnr('$'))
let str = str . ' ' . fnameescape(bufname(i))
endfor
execute str
execute a:list . 'w'
endfunction
" :GrepBuffers('pattern') puts results into the quickfix list
command! -nargs=1 GrepBuffers call GrepBuffers(<args>, 'c')
" :GrepBuffersL('pattern') puts results into the location list
command! -nargs=1 GrepBuffersL call GrepBuffers(<args>, 'l')
An improved (on steroids) version of Waz's answer, with better buffer searching and special case handling, can be found below (The moderators wouldn't let me update Waz's answer anymore :D).
A more fleshed out version with binds for arrow keys to navigate the QuickFix list and F3 to close the QuickFix window can be found here: https://pastebin.com/5AfbY8sm
(When i feel like figuring out how to make a plugin i'll update this answer. I wanted to expedite sharing it for now)
" Looks for a pattern in the buffers.
" Usage :GrepBuffers [pattern] [matchCase] [matchWholeWord] [prefix]
" If pattern is not specified then usage instructions will get printed.
" If matchCase = '1' then exclude matches that do not have the same case. If matchCase = '0' then ignore case.
" If prefix == 'c' then put results in the QuickFix list. If prefix == 'l' then put results in the location list for the current window.
function! s:GrepBuffers(...)
if a:0 > 4
throw "Too many arguments"
endif
if a:0 >= 1
let l:pattern = a:1
else
echo 'Usage :GrepBuffers [pattern] [matchCase] [matchWholeWord] [prefix]'
return
endif
let l:matchCase = 0
if a:0 >= 2
if a:2 !~ '^\d\+$' || a:2 > 1 || a:2 < 0
throw "ArgumentException: matchCase value '" . a:2 . "' is not in the bounds [0,1]."
endif
let l:matchCase = a:2
endif
let l:matchWholeWord = 0
if a:0 >= 3
if a:3 !~ '^\d\+$' || a:3 > 1 || a:3 < 0
throw "ArgumentException: matchWholeWord value '" . a:3 . "' is not in the bounds [0,1]."
endif
let l:matchWholeWord = a:3
endif
let l:prefix = 'c'
if a:0 >= 4
if a:4 != 'c' && a:4 != 'l'
throw "ArgumentException: prefix value '" . a:4 . "' is not 'c' or 'l'."
endif
let l:prefix = a:4
endif
let ignorecase = &ignorecase
let &ignorecase = l:matchCase == 0
try
if l:prefix == 'c'
let l:vimgrep = 'vimgrep'
elseif l:prefix == 'l'
let l:vimgrep = 'lvimgrep'
endif
if l:matchWholeWord
let l:pattern = '\<' . l:pattern . '\>'
endif
let str = 'silent ' . l:vimgrep . ' /' . l:pattern . '/'
for buf in getbufinfo()
if buflisted(buf.bufnr) " Skips unlisted buffers because they are not used for normal editing
if !bufexists(buf.bufnr)
throw 'Buffer does not exist: "' . buf.bufnr . '"'
elseif empty(bufname(buf.bufnr)) && getbufvar(buf.bufnr, '&buftype') != 'quickfix'
if len(getbufline(buf.bufnr, '2')) != 0 || strlen(getbufline(buf.bufnr, '1')[0]) != 0
echohl warningmsg | echomsg 'Skipping unnamed buffer: [' . buf.bufnr . ']' | echohl normal
endif
else
let str = str . ' ' . fnameescape(bufname(buf.bufnr))
endif
endif
endfor
try
execute str
catch /^Vim\%((\a\+)\)\=:E\%(683\|480\):/ "E683: File name missing or invalid pattern --- E480: No match:
" How do you want to handle this exception?
echoerr v:exception
return
endtry
execute l:prefix . 'window'
"catch /.*/
finally
let &ignorecase = ignorecase
endtry
endfunction

Resources