set complete+=k[file] not working for whole line completion? - vim

I have ~/.bash_history that contains lines such as sudo apt-get install, aplay foo.wav, etc. I thought it would be convenient if I could use these lines for completing whole lines while writing shell scripts.
:h compl-whole-line says:
CTRL-X CTRL-L
Search backwards for a line that starts with the
same characters as those in the current line before
the cursor. Indent is ignored. The matching line is
inserted in front of the cursor.
** The 'complete' option is used to decide which buffers
are searched for a match. Both loaded and unloaded
buffers are used.**
Note the asterisks I inserted. :h 'complete' says:
k k{dict} scan the file {dict}. Several "k" flags can be given,
patterns are valid too. For example: >
:set cpt=k/usr/dict/*,k~/spanish
So I thought :set complete+=k~/.bash_history would do the job. It didn't.
Start vim with
$ vim -u NONE -N
then
:set complete+=k~/.bash_history
:set complete?
" complete=.,w,b,u,t,i,k~/.bash_history
, I enter to the insert mode (i), and when I type
su<C-x><C-l>
, vim says Whole line completion (^L^N^P) Pattern not found. The completion is working for words, so when I type
su<C-p>
sudo is suggested.
What am I missing? How can I use my history for whole line completion without :sp ~/.bash_history?

set complete+=k[file] has nothing to do with line completion: whatever file you give to it will only be used as a source by dictionary completion (<C-x><C-k>) and keyword completion (<C-n>/<C-p>).
:help i_ctrl-x_ctrl-l is clear: line completion only works with lines found in loaded and unloaded buffers. Since ~/.bash_history is not loaded as a buffer, line completion will obviously never use it as a source.
So yes, the only practical solution is to load that file.
:sp ~/.bash_history is not really optimal, though, because a) it takes too much room, both physically and in your buffer list, and b) it requires way too many keystrokes.
The "too much room" part of the problem is easily solved with a more suited command:
:badd ~/.bash_history
The "too many keystrokes" part of the problem could be solved with an autocommand that runs the command above each time you edit a shell script:
augroup shell
autocmd!
autocmd BufNewFile,BufRead *.sh badd ~/.bash_history
augroup END

Related

How to move to end of a file upon opening it via a command in .vimrc using vim/MacVim?

I'm trying to open a file using a command I set in my .vimrc file. The relevant line in my .vimrc is similar to the following:
command Of so /Users/Dude/Working/open_file.txt
With open_file.txt containing the following:
tabnew /Users/Dude/Working/Project/config.txt
What I'd like to do when executing the 'Of' command is navigate to the end of config.txt. I've tried adding a large line number which is unlikely to exceed the number of lines in the file like so:
tabnew /Users/Dude/Working/Project/config.txt
250000
This takes me to the end of the file but doesn't seem like the right way to do it. Ideally, I'd also like to add a new line after the last line and navigate there too.
A few things:
I would suggest you use full names instead of short names. e.g. so -> source.
source is probably the wrong choice here as you can do everything with the right-hand-side of command
May want to use ! with command so you can resource your vimrc file. e.g. command! Of ...
$ represents the last line of the file. No need to choose a magic number
Create a new line can be done with :normal o or :put _
So with some tweaks we get the following command:
command! Of tabedit /Users/Dude/Working/Project/config.txt | $put_
For more help see:
:h :command
:h :put
:h :range
:h :bar
Have a look at :h :normal in your case just write :norm Go instead of your number there.
:tabnew, like most variants of :edit (and the command-line arguments when launching Vim), takes arbitrary Ex commands via the [+cmd] argument. The $ command will move to the end of the file:
tabnew +$ /Users/Dude/Working/Project/config.txt

Open file hook to move the cursor to the buffer/file end

How can i write a hook function that will place the cursor at the end of the file on opening a file.
In elisp, it looks approximately like this,
(add-hook 'open-buffer-hook
(lambda () (end-of-buffer)))
In vim, I can open a file and press :$ to go to the end but i am keen on doing it via a hook.
Using autocmd you may hook into BufReadPost and execute something like G$ in normal mode to advance to the last line and the last character.
autocmd BufReadPost * :normal G$
I used BufReadPost to cause this command to run after the file is fully read into the buffer. The * applies this rule to all buffer types, but you could limit it by FileType or by filename pattern as well. See :help autocmd for more details.
An autocommand seems too much to me.
In your shell,
$ vim file +$
opens file in Vim and jumps to the last line.
In Vim,
:edit +$ file
opens file and jumps to the last line.
This works with other related commands like :vsplit or :tabedit.
It you just want to open files from the command line, you can use
vim +':norm G$' file.txt

How can I execute the current line as Vim EX commands?

Say I'm editing my _vimrc file and I've just added a couple of lines, for instance a new key mapping. I don't want to reload the whole file (:so %) since that will reset a lot of temporary stuff I'm experimenting with. I just want to run the two lines that I'm currently working on.
I'm having no luck trying to copy/paste the lines into the command buffer, since I can't use the put command in there. Is there any way I could run the current line (or current selection) as EX commands?
Summary:
After Anton Kovalenko's answer and Peter Rincker's comment I ended up with these key maps, which either executes the current line, or the current selected lines if in visual mode:
" Execute current line or current selection as Vim EX commands.
nnoremap <F2> :exe getline(".")<CR>
vnoremap <F2> :<C-w>exe join(getline("'<","'>"),'<Bar>')<CR>
To execute the current line as an ex command, you may also use:
yy:#"
This will yank the current line to the "-register and execute it. I don't think it is too much typing.
Executing the line under cursor as an Ex command:
:execute getline(".")
Convenient enough for 2 lines. (I'd figure out something for doing it with regions, but I'm not a vim user). And for currently selected region, the following seems to do the job:
:execute getreg("*")
As commented by Peter Rincker, this mapping can be used for executing the currently selected lines:
:vnoremap <f2> :<c-u>exe join(getline("'<","'>"),'<bar>')<cr>
For that purpose, I have defined the following commands and mappings:
":[range]Execute Execute text lines as ex commands.
" Handles |line-continuation|.
" The same can be achieved via "zyy#z (or yy#" through the unnamed register);
" but there, the ex command must be preceded by a colon (i.e. :ex)
command! -bar -range Execute silent <line1>,<line2>yank z | let #z = substitute(#z, '\n\s*\\', '', 'g') | #z
" [count]<Leader>e Execute current [count] line(s) as ex commands, then
" {Visual}<Leader>e jump to the following line (to allow speedy sequential
" execution of multiple lines).
nnoremap <silent> <Leader>e :Execute<Bar>execute 'normal! ' . v:count1 . 'j'<CR>
xnoremap <silent> <Leader>e :Execute<Bar>execute 'normal! ' . v:count1 . 'j'<CR>
Just after posting this, I found a work-around. I can copy text into the clipboard using "*y, then put that text into the command buffer by using the middle mouse button. This works for me, but is hardly a convenient solution for people without clipboard support, mouse support or just an aversion to removing their hands from the Vim position.
The accepted answer doesn't handle continuation sections. Also, surprisingly, the bar isn't needed, newlines are fine. This will work, first yanking the text into register x:
vno <c-x> "xy:exe substitute(#x,"\n\\",'','g')<cr>
As someone has already mentioned, the only exception are commands that "eat up" newlines. Eg, executing the above mapping on:
:sign define piet text=>> texthl=Search
:exe ":sign place 2 line=23 name=piet file=" . expand("%:p")
will cause vim to to think that the user is trying to define textl as "Search\n:exe ":sign place... etc.
You could also try
:<C-R><C-L><CR>
Per the vim docs, the combination will plop the current line into the command line. From there, hitting enter should do the trick. I realize that this does not handle multiline cases, however it doesn't require a .vimrc and therefore works out of the box.
If you're doing a lot of experimenting (trying things out that you might want to add to your vimrc, I assume?) it might help to do so in a scratch file like experimental.vim so you aren't just relying on your history to know what you're trying out. Now that you have these great mappings, it will be easy to rerun things from experimental or vimrc without sourcing the whole file.
Also (sorry, I can't comment on answers yet, it seems), I tried this mapping of Peter's:
vnoremap <Leader>es :<c-u>exec join(getline("'<","'>"),'<BAR>')<CR>
This works in most cases, but it fails specifically on function definitions.
function! TestMe()
echo "Yay!"
endfunction
This mapping joins the lines into a single string, separated by <BAR> and then execs them.
I'm not entirely sure why, but if I try to do that with a function definition in normal mode:
:exec 'function! TestMe()| echo "Yay!"|endfunction'
-> E488: Trailing characters
After some testing, I've found that it will work with newline separators instead:
:exec "function! TestMe()\n echo 'Yay!'\nendfunction"
:call TestMe()
-> Yay!
So, I've changed my mapping to this:
vnoremap <Leader>es :<c-u>exec join(getline("'<","'>"),"\n")<CR>
I suppose there is a vim or ex reason why the <BAR> method doesn't work on functions (maybe even some setting I have on?), and I'm curious to hear what it is if someone knows.
I don't want to reload the whole file (:so %) since that will reset a lot of temporary stuff I'm experimenting. I just want to run the two lines that I'm currently working on.
If you want to execute a command because you want to refine it before committing it to _.vimrc, then you should launch a Command Line Window for Ex-mode commands with q:.
At launch the Command Line Window is buffered with the contents of the command line history. It is a normal Vim window the contents of which can be edited as any text buffer with the exception of pressing on any line which executes the command on that line. It is very useful when you want to slightly change a long, complex command you wrote earlier and re-run it.
To launch a 'Command Line Window' for search strings press q/.
!! (shorthand for :.!) executes the current line as input to a command, per POSIX ex & vi. You may need to append sh if it is a system command.
Executing !! on a blank line (and omitting sh) is a shortcut for reading a shell command straight into the buffer. By it's nature :.! overwrites the current line while :.r! inserts on the line below.
ls -A | head -n +4
~
~
!sh
Results:
.sh_history
.sh_logout
.kshrc
corelist.txt
~
~
4 lines added; 1 line deleted`
This means there is no need to redirect pipelines to a file and then examine the data to see if the contents are valid. Just execute commands in vi directly and undo if you make a mistake.
Alternately, yanking a line as a named buffer allows you to execute it as an ex command, almost like a macro. You can still edit and undo the line to get it correct instead of trying to edit the : line in command mode.
The functions recommended here are all POSIX and have been supported for over 40 years, so no special vim or other enhanced features are required.
:%s/meep/pEEp/ | g/foo/ s//BAR
foo
grok
meep
~
~
Yank the ex command (line 1, :%s...) into a named buffer / macro.
I just use the label m for "macro".
"myy
or
:1y m
Now execute the named buffer / macro, in command mode, using #:
#m
Results:
:%s/pEEp/pEEp/ | g/BAR / s//BAR
BAR
grok
pEEp
~
~
4 lines changed
But remember that "multiple undo" is not POSIX. undo is only a toggle between undo and redo in a "historically accurate & compliant" ex / vi implementation.
The work-around is to save to a temporary (or valid) file name before executing a questionable edit:
:w $$.tmp
Then just :e! to "reset and reload" if needed.
You can also use :pre (preserve) to make a special temporary backup file prior to making multiple changes.
Then use :reco! % (recover this!) to restore back to that point.
Realize that :preserve creates a snapshot-like file which is deleted as soon as it is rolled back to. It does not matter if you save the edit(s) or not.
Therefore writing your own file (:w ...) and restoring with :e! may still have value because the system will not automatically delete it.
:pre is perfect when you should have ran sudo vi ... or otherwise do not have the necessary permissions - but you only realized the mistake after making several changes. i.e. vi /etc/sudoers instead of sudo vi /etc/sudoers.
^^ NEVER DO THIS! ONLY AN EXAMPLE! USE sudo visudo INSTEAD!
You can get a list of existing recovery files with vi -r and recover one directly with vi -r filename as needed, optionally with something like sudo vi -r filename.
The distinction here is that even though the ":preserved file" has it's own "special" name and path internally, it will :write to the original, intended location when ":recovered ==> /etc/sudoers
Just be sure to use :wq! and not something like ZZ when done with your "recovery" or you will still lose the edits which you tried to save.
By the way, ^R is expected to redraw or repaint the display per POSIX; it is not "undo" in any compliant vi implementation.

How to stop vim from adding a newline at end of file?

So I work in a PHP shop, and we all use different editors, and we all have to work on Windows. I use vim, and everyone in the shop keeps complaining that whenever I edit a file there is a newline at the bottom. I've searched around and found that this is a documented behavior of vi & vim... but I was wondering if there was some way to disable this feature. (It would be best if I could disable it for specific file extensions).
If anyone knows about this, that would be great!
And for vim 7.4+ you can use (preferably on your .vimrc) (thanks to 罗泽轩 for that last bit of news!):
:set nofixendofline
Now regarding older versions of vim.
Even if the file was already saved with new lines at the end:
vim -b file
and once in vim:
:set noeol
:wq
done.
alternatively you can open files in vim with :e ++bin file
Yet another alternative:
:set binary
:set noeol
:wq
see more details at Why do I need vim in binary mode for 'noeol' to work?
Add the following command to your .vimrc to turn of the end-of-line option:
autocmd FileType php setlocal noeol binary fileformat=dos
However, PHP itself will ignore that last end-of-line - it shouldn't be an issue. I am almost certain that in your case there is something else which is adding the last newline character, or possibly there is a mixup with windows/unix line ending types (\n or \r\n, etc).
Update:
An alternative solution might be to just add this line to your .vimrc:
set fileformats+=dos
There is another way to approach this if you are using Git for source control. Inspired by an answer here, I wrote my own filter for use in a gitattributes file.
To install this filter, save it as noeol_filter somewhere in your $PATH, make it executable, and run the following commands:
git config --global filter.noeol.clean noeol_filter
git config --global filter.noeol.smudge cat
To start using the filter only for yourself, put the following line in your $GIT_DIR/info/attributes:
*.php filter=noeol
This will make sure you do not commit any newline at eof in a .php file, no matter what Vim does.
And now, the script itself:
#!/usr/bin/python
# a filter that strips newline from last line of its stdin
# if the last line is empty, leave it as-is, to make the operation idempotent
# inspired by: https://stackoverflow.com/questions/1654021/how-can-i-delete-a-newline-if-it-is-the-last-character-in-a-file/1663283#1663283
import sys
if __name__ == '__main__':
try:
pline = sys.stdin.next()
except StopIteration:
# no input, nothing to do
sys.exit(0)
# spit out all but the last line
for line in sys.stdin:
sys.stdout.write(pline)
pline = line
# strip newline from last line before spitting it out
if len(pline) > 2 and pline.endswith("\r\n"):
sys.stdout.write(pline[:-2])
elif len(pline) > 1 and pline.endswith("\n"):
sys.stdout.write(pline[:-1])
else:
sys.stdout.write(pline)
I have not tried this option, but the following information is given in the vim help system (i.e. help eol):
'endofline' 'eol' boolean (default on)
local to buffer
{not in Vi}
When writing a file and this option is off and the 'binary' option
is on, no <EOL> will be written for the last line in the file. This
option is automatically set when starting to edit a new file, unless
the file does not have an <EOL> for the last line in the file, in
which case it is reset.
Normally you don't have to set or
reset this option. When 'binary' is
off the value is not used when writing
the file. When 'binary' is on it is
used to remember the presence of a
for the last line in the file,
so that when you write the file the
situation from the original file can
be kept. But you can change it if you
want to.
You may be interested in the answer to a previous question as well: "Why should files end with a newline".
I've added a tip on the Vim wiki for a similar (though different) problem:
http://vim.wikia.com/wiki/Do_not_auto-add_a_newline_at_EOF
OK, you being on Windows complicates things ;)
As the 'binary' option resets the 'fileformat' option (and writing with 'binary' set always writes with unix line endings), let's take out the big hammer and do it externally!
How about defining an autocommand (:help autocommand) for the BufWritePost event? This autocommand is executed after every time you write a whole buffer. In this autocommand call a small external tool (php, perl or whatever script) that strips off the last newline of the just written file.
So this would look something like this and would go into your .vimrc file:
autocmd! "Remove all autocmds (for current group), see below"
autocmd BufWritePost *.php !your-script <afile>
Be sure to read the whole vim documentation about autocommands if this is your first time dealing with autocommands. There are some caveats, e.g. it's recommended to remove all autocmds in your .vimrc in case your .vimrc might get sourced multiple times.
I've implemented Blixtor's suggestions with Perl and Python post-processing, either running inside Vim (if it is compiled with such language support), or via an external Perl script. It's available as the PreserveNoEOL plugin on vim.org.
Starting with vim v7.4 you can use
:set nofixendofline
There is some information about that change here: http://ftp.vim.org/vim/patches/7.4/7.4.785 .
Maybe you could look at why they are complaining. If a php file has a newline after the ending ?>, php will output it as part of the page. This is not a problem unless you try to send headers after the file is included.
However, the ?> at the end of a php file is optional. No ending ?>, no problem with a newline at the end of the file.
Try to add in .vimrc
set binary
I think I've found a better solution than the accepted answer. The alternative solutions weren't working for me and I didn't want to have to work in binary mode all the time.
Fortunately this seems to get the job done and I haven't encountered any nasty side-effects yet: preserve missing end-of-line at end of text files. I just added the whole thing to my ~/.vimrc.
Would it be possible for you to use a special command for saving these files?
If you do :set binary, :w and :set nobinary the file will be written without newline if there was none to start with.
This sequence of commands could be put into a user defined command or a mapping, of course.
I found this vimscript plugin is helpful for this situation.
Plugin 'vim-scripts/PreserveNoEOL'
Or read more at github

redirection to a file of a search in Vim

My problem is simple. I search a specific pattern in a file (let's say label in a Tex file)
:g/label/#
but there are lots of occurrences. So I'd like to redirect this output to another file to be able to work easily with it.
Do you have a trick or a command that I don't know?
it's not clear from the original post what you mean by "work easily with it" but it's often useful to see and quickly jump between all of the matches in a buffer without "extracting" the matches to a separate buffer.
vim has an internal grep built in. your example would be something like this (in vim, % denotes the current file)
:vimgrep /label/ %
This will take you to the first occurrence and report how many matches there were. What's cool is that you can look at all of the matches listed by opening up the quickfix error list using
:cope
Now you can just scroll around and press enter on a line to jump to the exact position of the match.
The quickfix error list is exactly the same buffer you use if you run make from inside vim and your compiler throws errors: it gives you a list of what and where the errors are.
After you've jumped to one location pointed by quickfix, you can go to forwards and backwards in the list via :cn and :cp. :ccl closes the error list.
You can also expand your "error" list via :vimgrepa /newpattern/ % or :vimgrepadd
The (documented) caveat is that vim's internal grep is slower than most native grep implementations (but you do get it "for free" in windows, for example). If you do have a grep installed, you can use :grep instead of :vimgrep for similar results.
quoting :help grep
Vim has two ways to find matches for a
pattern: Internal and external. The
advantage of the internal grep is that
it works on all systems and uses the
powerful Vim search patterns. An
external grep program can be used when
the Vim grep does not do what you
want.
The internal method will be slower,
because files are read into memory.
The advantages are:
- Line separators and encoding are automatically recognized, as if a file
is being edited.
- Uses Vim search patterns. Multi-line patterns can be used.
- When plugins are enabled: compressed and remote files can be searched.
You can also use the location list if you're already using the error list for dealing with compilation errors. just add l (for location) to the beginning of the grep command (:lvimgrep,:lvimgrepa :lgrep, :lgrepa) and use :lopen :ln :lp :lcl instead of the :c* ones.
For more commands consult
:help grep
:help quickfix-window
:help quickfix
:help quickfix-error-lists
:redir > matches.txt|execute 'g/foo/#'|redir END
See :h :redir, you can also redirect to registers, variables, the clipboard etc.
What you're doing is essentially 'grep -n label file' from command line. So you can run that command and > it into a file easily enough.
The derivation of 'grep' is even from basically the same source.
I've gotten this of the net at some point:
function GoToLine(mainbuffer)
let linenumber = expand("<cword>")
silent bd!
silent execute "buffer" a:mainbuffer
silent execute ":"linenumber
silent nunmap <Enter>
endfunction
command -nargs=1 GoToLine :call GoToLine(<f-args>)
function GrepToBuffer(pattern)
let mainbuffer = bufnr("%")
silent %yank g
enew
silent put! g
execute "%!egrep -n" a:pattern "| cut -b1-80 | sed 's/:/ /'"
silent 1s/^/\="# Press Enter on a line to view it\n"/
silent :2
silent execute "nmap <Enter> 0:silent GoToLine" mainbuffer "<Enter>"
" silent nmap <C-G> <C-O>:bd!<Enter>
endfunction
command -nargs=+ Grep :call GrepToBuffer(<q-args>)
Put it in your .vimrc, then :Grep Foo
Requires external grep program to work properly.
(Just an idea -- untested.)
You can delete all the lines with your pattern in it, write to another file, and undo the delete.
:g/label/d
:w matches
u

Resources