switch tab with vimscript? - vim

I want do something like this:
check if a split named __Potion_Bytecode__ exists
if exists, switch to the split with name
if not, new a split named __Potion_Bytecode__
Here is code I am now doing:
function! PotionShowBytecode()
" Here I need to check if split exists
" open a new split and set it up
vsplit __Potion_Bytecode__
normal! ggdG
endfunction

In lh-vim-lib, I have lh#buffer#jump() that does exactly that. It relies on another function to find a window where the buffer could be.
" Function: lh#buffer#find({filename}) {{{3
" If {filename} is opened in a window, jump to this window, otherwise return -1
function! lh#buffer#find(filename)
let b = bufwinnr(a:filename) " find the window where the buffer is opened
if b == -1 | return b | endif
exe b.'wincmd w' " jump to the window found
return b
endfunction
function! lh#buffer#jump(filename, cmd)
let b = lh#buffer#find(a:filename)
if b != -1 | return b | endif
call lh#window#create_window_with(a:cmd . ' ' . a:filename)
return winnr()
endfunction
Which uses another function to work around the extremely annoying E36:
" Function: lh#window#create_window_with(cmd) {{{3
" Since a few versions, vim throws a lot of E36 errors around:
" everytime we try to split from a windows where its height equals &winheight
" (the minimum height)
function! lh#window#create_window_with(cmd) abort
try
exe a:cmd
catch /E36:/
" Try again after an increase of the current window height
resize +1
exe a:cmd
endtry
endfunction
If you want to work with tabs, you'll have to use tab* functions instead.

Related

Run J script as if it were line-by-line entered into the interpreter

Is there a way to run the script as if it were typed into the interpeter? The benefits are that I don't need echos everywhere, the work done is saved as a file, and I can use vim to do the editing. Example:
example.ijs
x =. 1
x + 3
terminal
x =. 1
x + 3
4
If not, I'll write a vimscript that can do the above then share them here. The advantage of a vimscript solution is that I could have commands to run the entire file, the current line, the current selection, everything up to and including the current line, or whatever else is useful.
Related but not a duplicate: How to call J (ijconsole) with a script automatically
It sounds like you are asking for this to be solved for the jconsole interface. I don't have answer for that, but would point out that that functionality is available for both the JHS and jQt interfaces. If you don't mind switching to a different interface then that would be a quick and easy solution.
The easiest way to interactively run a script is to use labs command:
load'labs/lab'
lab'myscript.ijt'
1 of 2 in myscript.ijt
x =. 1
NB. press Ctrl+'.' to advance.
x + 3
4
NB. Run the whole script.
lab 1 _
x =. 1
x + 3
4
More info about labs here
If you want to non-interactively run a script as if typed in the console, you can just feed the script to j (in linux):
j < myscript.ijs
4
Alternatively, to
see the lines on the screen just as though they had been typed from the keyboard
from a script, you can use 0!:1:
0!:1 < 'myscript.ijs'
x =. 1
x + 3
4
Use loadd rather than load to run the script and display the lines and results.
loadd 'example.ijs'
x =. 1
x + 3
4
This is the vimscript solution I mentioned. It's as far as I can tell language agnostic as well.
" Global variable dictates whether new terminals are opened
" horizontally ('h') or vertically ('v').
let g:terminalsplit = 'h'
" Add execution strings for each language you use.
augroup terminalcommands
autocmd!
autocmd Filetype j let g:cmdstr = 'jconsole.cmd'
autocmd Filetype python let g:cmdstr = 'python'
augroup END
" Close all terminals
nnoremap <silent> <leader>p :call CloseTerminal()<cr>
" Run file
nnoremap <leader>h :call Run(g:cmdstr, 'script')<cr>
" Run as if file were entered line-by-line into the interpreter
" Mappings for: Line, selection, file up to line, entire file
nnoremap <leader>j yy:call Run(g:cmdstr, 'interpreter')<cr>
vnoremap <leader>j ygv<esc>:call Run(g:cmdstr, 'interpreter')<cr>
nnoremap <leader>k Vggy<c-O>:call Run(g:cmdstr, 'interpreter')<cr>
nnoremap <leader>l mzggVGy'z:call Run(g:cmdstr, 'interpreter')<cr>
function! Run(cmdstr, mode)
let filepath = expand('%:p') " Copy filepath before switch to terminal
call CloseTerminal()
call OpenTerminal()
echo g:clear . " & " . a:cmdstr
call feedkeys(g:clear . " & " . a:cmdstr) " Begin run command
call RunCode(filepath, a:mode)
call feedkeys("\<c-w>p") " Switch back to file window
endfunction
function! CloseTerminal()
if has('nvim')
let terminals = split(execute('filter/term:/ls'), '\n')
else
let terminals = split(execute('filter/!/ls'), '\n')
endif
for i in range(len(terminals))
silent! exe "bd! " . split(terminals[i], ' ')[0]
endfor
endfunction
function! OpenTerminal()
if g:terminalsplit == 'h'
terminal
elseif g:terminalsplit == 'v'
vertical terminal
else
echo 'g:terminalsplit=' . &g:terminalsplit . '. Must be "h" or "v".'
endif
endfunction
function! RunCode(filepath, mode)
if a:mode == 'script'
call feedkeys(" " . a:filepath . "\<cr>")
elseif a:mode == 'interpreter'
call feedkeys("\<cr>")
call feedkeys("\<c-w>\"\"")
else
echo 'a:mode=' . a:mode . '. Must be "script" or "interpreter".'
endif
endfunction
" Use to clear the terminal window before running the script
if has('unix')
let g:clear = 'clear'
else
let g:clear = 'cls'
endif

set name to window and reference to it with command

I have 8 square (equal) windows in my vim screen spanning over 2 large monitors and I want to refer each of them with shortcuts < A-1 >, < A-2 > ... . There is a command in vim N-wincmd-wincmd that allows to to reference to the window by its number, but it is useless for me because other plugins sometimes create windows (like syntastic for syntax checking) and referring by number doesn't exactly matches the correct window. I thought maybe I could reference windows by names, so the question is, how do I set a name to some window, and then make a short cut so the cursor goes to the window with that name when pressing < A - n > where n is the window number?
The following lets you save a static extra window number for each visible window, and then jump to it quickly.
Just call :MarkWins when your layout is clean, and then the mappings <A-1>, <A-2>... will jump to the good window, even if new windows were created after that.
" Mark all visible windows from 1 :
command! MarkWins call s:mark_windows()
" Go to a previously marked window :
command! -nargs=1 GoToMarkedWin call s:go_to_marked_win(<f-args>)
" Mappings (Alt-1, Alt-2...) :
for s:n in range(1,8)
exe printf('noremap <silent> <a-%d> :GoToMarkedWin %d<cr>', s:n, s:n)
endfor
function! s:mark_windows()
let l:old_winnr = winnr()
windo let w:win_mark = winnr()
exe printf('%d wincmd w', l:old_winnr)
endf
function! s:go_to_marked_win(n)
let l:old_winnr = winnr()
while 1
if exists('w:win_mark') && w:win_mark == a:n
return
endif
wincmd w
if winnr() == l:old_winnr | return | endif
endw
endf

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

Vim autocommand trigger on opening "nothing"

I want vim to open up the :Explorer when no file is opened or created. Eg. when I call vim without any options.
calling vim newfile.txt should still behave the normal way though.
How would I go about doing this? I can't seem to find the correct autocmd for it.
If you want to do this for vim invocation only, the best way is to use argc():
autocmd VimEnter * :if argc() is 0 | Explore | endif
argc() function returns a number of filenames specified on command-line when vim was invoked unless something modified arguments list, more information at :h argc().
Found the answer myself:
"open to Explorer when no file is opened
function! TabIsEmpty()
" Remember which window we're in at the moment
let initial_win_num = winnr()
let win_count = 0
" Add the length of the file name on to count:
" this will be 0 if there is no file name
windo let win_count += len(expand('%'))
" Go back to the initial window
exe initial_win_num . "wincmd w"
" Check count
if win_count == 0
" Tab page is empty
return 1
else
return 0
endif
endfunction
" Test it like this:
" echo TabIsEmpty()
function! OpenExplorer()
if (TabIsEmpty())
:Explore
end
endfunction
The greatest part of this code was taken from this question.

Resources