How do I map Vim colon search and replace command to work just with visual selection? - vim

Sometimes I want to replace some text in multiple lines but not in the whole line, so I toggle visual mode on and highlight the text I want to replace. But then, I need to add this annoying \%V that I always forget for it to replace the text just in the selection and not in the whole line
:'<, '>s/\%Vold/new/g
Is there a way to map the normal replace command
:'<, '>s/old/new/g
To the one shown above so that I don't need to remember that V every time?
Thank you
I tried using cmap command in the vimrc file in the following way:
cmap '<, '>s/* '<, '>s/\%V*
But this of course doesn't work, because instead of the asterisk I should input the text I want to search and replace to end the search and replace command.

There are three basic parts to a mapping:
the mapping command,
the "left-hand side" (LHS),
and the "right-hand side" (RHS).
The LHS is the key sequence/combination that you want to press and the RHS is a different key sequence that you want Vim to "press" instead of those in the LHS. You "map" one key sequence to another.
The RHS is, fundamentally, a macro: a sequence of keystrokes, "just" like if you pressed them yourself but without any delay between them. So, the RHS is really just a bunch of keystrokes you are tired of making over and over again.
The main use of mappings is to reduce repetitiveness. You figure that you often press the imaginary sequence sdlusdrosydtsodsd and you map it all to <F5> to be more efficient.
In this case…
The current mode is visual mode so the mapping has to be a visual mode mapping.
This makes :xmap or :xnoremap the proper mapping command. Let's make it :xnoremap.
The repetitive key sequence you want to abstract away is:
:s/\%V
That's your RHS.
(Note that the range '<,'> is automatically inserted for you so it can be ignored.)
The key sequence you want to press instead is, let's say… <F5>.
That's your LHS.
Now that you have your mapping command, your LHS, and your RHS, building the mapping is extremely easy:
:xnoremap <F5> :s/\%V

Related

Doing an insert remapping for commenter

I am trying to do a remapping when I'm in insert mode to insert a comment but am having a tough time figuring out what all the keys map to. What I am trying to do is:
:inoremap leadercspace ==> escleadercspacei
Basically, if I'm in insert mode I want to get out of insert mode to insert the comment (leader+c+space) and then go back into insert mode.
What would the correct :inoremap mapping for this be? What I have right now is:
:inoremap <leader>c<space> <Esc><Leader>c<space>i
But this doesn't seem to work (at least the latter half of it -- it does seem to be executing the mapping command). Note: the plugin I'm trying to remap is:
https://github.com/preservim/nerdcommenter
[count]<leader>c<space> |NERDCommenterToggle|
Toggles the comment state of the selected line(s). If the topmost selected line is commented, all selected lines are uncommented and vice versa.
From vim doc (:help nore):
Disallow mapping of {rhs}, to avoid nested and recursive mappings
In other words, the nore part forbids mapping to be applied to the rhs (right hand side).
So in your case, the <Esc><Leader>c<space>i doesn't trigger the VimCommenter mapping for that reason.
To allow recursion, you can take off the nore:
:imap <leader>c<space> <Esc><Leader>c<space>i
My recommendation is that, instead of creating an insert-mode mapping for this purpose, just use the native Ctrl+O mapping to run a single Normal mode command from Insert mode.
Assuming your leader key is set to the default \, you can use:
Ctrl+O, \, c, Space
You'll be left in Insert mode at the end of this sequence.
The advantages of this approach over an insert mode mapping are:
You don't need any extra configuration, since Ctrl+O is a native Vim command.
This works for any Normal mode command, so you don't need to add extra mappings for other commands you might want to be able to access from Insert mode.
Adding a multi-character mapping in Insert mode starting with <Leader> means Vim will always pause and hold if you insert the leader character. In this case, it will also pause when you insert <Leader> and c. I find that avoiding this kind of mappings of otherwise printable characters is usually best.

How to efficiently add parentheses or a string in vim?

In traditional text editors, whenever I needed to open a string or parentheses and type something between it I used to do:
Type () or ""
Press left
Type in what I need
Press right
But in vim (that is if I followed the vim way) the process becomes quite tedious as I have to enter the normal mode to move a whole bunch of times:
Type () or ""
Press <ESC>
Press i
Type what I need
Press <ESC>
Press l
Press a
If it is not a good practice to use the arrow keys at any time, is there a more efficient way of doing this kind of task in vim?
It is actually quite easy to automatically append those closing characters in a mapping, and put your cursor where you want it. The trick is to do that, without also messing up the undo/redo/repeat actions. The problem is that cursor movement commands in insert mode will break the "undo sequence" so that any change you make after moving the cursor is undone separately from changes made before moving the cursor.
Warning: the following information may become dated
There are plenty of plugins available to automatically append these characters (see the partial list at the Vim wiki page for appending closing characters), and prior to Vim 7.4, some of them even had complicated workarounds for keeping the undo sequence intact. Unfortunately, they all relied on a bug in Vim that got fixed in version 7.4 for this.
A patch is available to add a cursor movement that does not break undo, so if you want to compile Vim yourself, you can grab that patch and use mappings like the following (no plugin required!) to do what you want:
inoremap ( ()<C-G>U<Left>
inoremap <expr> ) strpart(getline('.'), col('.')-1, 1) == ")" ? "\<C-G>U\<Right>" : ")"
These mappings will insert "()" when you type an opening (, placing the cursor in between the parentheses. When you type ')' and there is already a closing ')' after the cursor, Vim will skip over the parenthesis instead of inserting a new one. Cursor movement is preceded by <C-G>U which is the feature the aforementioned patch adds, allowing the following cursor movement to not break the undo sequence (as long as the movement is all in a single line).
As of Vim 7.4.663, this patch has still not been officially included.
No. Doing it in Vim is exactly the same as in your "traditional" editor:
Type () or ""
Press left
Type in what you need
Press right
But… why don't you type the opening character, what you want inside the pair and then the closing character?
Type ( or "
Type what you need
Type ) or "
Too simple?
I think using arrow keys to move around is bad practice in normal mode but in your case; moving one space while in insert mode, I would hazard to say using the arrow keys is probably best practice.
That being said if you are dead set on avoiding them you could use <i_ctrl-o>.
:help i_ctrl_o
CTRL-O execute one command, return to Insert mode *i_CTRL-O*
So, while in insert mode, you could type: ()<ctrl-o>h<xxx><ctrl-o>l, where <xxx> is whatever you want in the brackets.
Unfortunately that doesn't work if you cursor is on the last character of the line, which if you are typing it most likely is.
To solve that problem do :set virtualedit+=onemore or add it to your ~/.vimrc file.
Note that this solution is more keystrokes than simply using the arrow keys but you don't need to move your hands away from the home row so it may be faster anyway.

How can I use the commands defined in this vim tip?

I am looking for a way to use f followed by some character to jump to the next uppercase letter.
I ran across this question and want to use the accepted answer, since that did not appear to have any dependencies.
However, after I added the lines into my .vimrc, I cannot figure out how to actually jump to the next uppercase character.
I tried Ctrl-Right and Ctrl-o, and both orderings of them, but I could not jump to the next uppercase letter in the line. I also read the actual vim tip, but that also does not explain how to actually use the commands.
What is the correct sequence of commands, and in which mode, to actually jump to the next uppercase letter?
Does it have to be the find command? What about typing /[A-Z]? It'll find the next upper case character (even if it's on a different line), and it's fast to type. Pressing n will take you to the next one without retyping the command again.
What you found in the other answer was a macro command. VIM has a rich macro language that allows you to define functions. You can run a function by typing a colon and then its name.
Of course, typing :findNextCapitalCharacter is a bit long to type. You can use map to define a key macro that will basically type the letters for you to find the next command. I like prefixing my mapped macros with some character like %, so typing %c will find the next capital character.
Further Explanation
I'm currently just doing /\u, but I still want to know how to use the macro in that answer for my own learning. In the case of those macros, what is the actual means to invoke the macro command?
You're way ahead of me! I didn't know about \u being uppercase.
Looking at the answer, I see they're not defining a macro, but doing key mapping. Here's a quick intro:
In command mode (that's where you can't type in anything into your file, but where you can use commands), type in :map #$ iHello World and press return. Now, still in command mode, type #$. You'll see that VIM typed iHello World for you. The i put VIM into insert mode, so it could type in Hello World That's mapping!
In VIM, you have special map modes depending on the mode you're in. In the original VI, you had two modes: Command and Insert. In VIM, you have Command, Select, Visual, and Command-Pending modes. The different map command depend upon the mode. Type :help mapmode into VIM and press <RETURN> to see about the various map modes and their VIM commands. This will be VIM help manual sections 1.3 to 1.5. Read it thoroughly to understand what the different map command mean.
What the accepted answer is doing is entering the maps three different times, once for each mode. There are two different maps (one search to the previous and one search to the next), so six all together.
The accepted answer is mapping Cntrl-Left Arrow <C-left> and Cntrl-Right Arrow <C-Right> to each of these mappings. Much like I mapped #$ to Hello World.
Setting g:camelcase is setting a global variable called camelcase to a string. If the string is A-Z, it will be for just capital letters. If it's A-Z0-9, it's for capital letters and numbers. You should only define one instance of this variable.
I think you're problem is that you're typing in <C-Left> for the map. What you're suppose to type is ^V^-> where ^V is Ctrl-V and ^-> is Ctrl-Left Arrow. When you type that in, the map command will change those into <C-Left>.

How can I delete empty lines in motion in Vim

I know how to delete blank lines with commands.
We may visually select the text block first, and then run commands like
s/^$/d to delete all blank lines or %s/^\(\s*\n\)\+/\r to keep only one blank lines.
Can I perform the above using motion, so that I can just press some keys to perform the "delete-motion" without having to enter command-line mode?
Creating a new operator for this is a good idea, but it can be tough to get right.
The operator-user plugin makes that task easy.
Once you have installed operator-user, all you need to do is add two lines to your vimrc, one to define the operator, and one to define your personal mapping to it:
call operator#user#define_ex_command('delete-blanks', 'g/^$/d')
map _ <Plug>(operator-delete-blanks)
This creates a new operator _. Change it to whatever you like best.
Now you can do _3} or _G or _23k to delete the blank lines contained in the motion. Text objects _a}, doubling of the operator 4__, and Visual mode V7j_ are all also supported, as befits a proper operator.
You could use operatorfunc. For example:
Define a function like this in your .vimrc:
function! DeleteEmptyLines(type)
if a:type == 'line'
silent execute ".,'\"g/^$/d"
endif
endfunction
And a mapping:
nnoremap <silent> ,d :set operatorfunc=DeleteEmptyLines<CR>m"g#
,d performs now just like an operator and accepts a (line-based) motion. You can, for example, insert ,d5j or ,dG in normal mode to delete empty lines in the next 5 lines or to the end of file.
You can find more information on how to extend this functionality here:
http://learnvimscriptthehardway.stevelosh.com/chapters/33.html
and of course::h operatorfunc and :h map-operator.
From :h map-operator:
"An operator is used before a {motion} command. To define your own operator
you must create mapping that first sets the operatorfunc option and then
invoke the g# operator. After the user types the {motion} command the
specified function will be called."
well, using motions I don't think you can only delete blank lines.
But you can do it using a mapping:
:nmap <Leader>db :g/^$/d<CR>
The motions help you move one word, one paragraph away... And before the motion you use an operator (d, c...).
So what you'd want is to create a new operator that deletes blank lines within the given motion (or selection). What I gave you is close to that, but you'd have to invent a new operator (and I don't think there's many unbound keys left).
Other vimmers may correct me, but I think the easiest way to create such operators would be to define a map for each motion and bind it to a function.
There isn't a motion that can combine with a delete such that it only deletes blank lines. A motion denotes all the text between the initial and final position, without any gaps. That includes motions which search using regular expressions.

VIM: Mappable (unused) shortcut letters?

I'm trying to create two mappings which are efficient for myself:
map X ddp
Which I'd use to delete and paste in one go.
map X "_dw
Which would delete a word without yanking into a register.
However I don't want to break any existing, useful shortcuts so I'm wondering what keys I could use - any suggestions? Am I being too uptidy?
vim help has a section :he map-which-keys
1.7 WHAT KEYS TO MAP *map-which-keys*
If you are going to map something, you will need to choose which key(s) to use
for the {lhs}. You will have to avoid keys that are used for Vim commands,
otherwise you would not be able to use those commands anymore. Here are a few
suggestions:
- Function keys <F2>, <F3>, etc.. Also the shifted function keys <S-F1>,
<S-F2>, etc. Note that <F1> is already used for the help command.
- Meta-keys (with the ALT key pressed). |:map-alt-keys|
- Use the '_' or ',' character and then any other character. The "_" and ","
commands do exist in Vim (see |_| and |,|), but you probably never use them.
- Use a key that is a synonym for another command. For example: CTRL-P and
CTRL-N. Use an extra character to allow more mappings.
See the file "index" for keys that are not used and thus can be mapped without
losing any builtin function. You can also use ":help {key}^D" to find out if
a key is used for some command. ({key} is the specific key you want to find
out about, ^D is CTRL-D).
Many Vim plugins use an initial <Leader> to start their key sequences; this is an (otherwise normally) unused key that is configurable by the user.
*<Leader>* *mapleader*
To define a mapping which uses the "mapleader" variable, the special string
"<Leader>" can be used. It is replaced with the string value of "mapleader".
If "mapleader" is not set or empty, a backslash is used instead. Example:
:map <Leader>A oanother line<Esc>
Works like:
:map \A oanother line<Esc>
But after:
:let mapleader = ","
It works like:
:map ,A oanother line<Esc>
Note that the value of "mapleader" is used at the moment the mapping is
defined. Changing "mapleader" after that has no effect for already defined
mappings.
Every single ASCII character, upper and lower case, is used for something in Vim. So you're going to wind up overwriting something--just pick something that you don't use. It may help to use a common idiom for your own extensions. I use a leading comma, for example:
map ,w :w!<CR>
map ,e :e #<CR>
imap ,, <ESC>
(The last is particularly useful for me, since I pretty much never need to write two consecutive commas in insert mode, and it's nice not to have to go all the way to the Esc key.)
Typically I use control + [letter] or alt + [letter] for most mappings and it's safe, but watch out for 'w' since that's needed for window commands. You might also be interested in arpeggio.vim which lets you create mappings to simultaneously pressed groups of keys - it will massively expand the possibilities for your mappings with no danger of over-mapping something. For example, you could map "dp" (pressed simultaneously) to execute "ddp" to delete and paste in one command.
Uhmm, no, don't. When creating your mappings try not to overwrite anything ... not so much because you don't use the command you're overmapping, but because some plugin which you have/or will have maybe using it.
And then you overmap it, and then you have to worry.
Personally, for commands such as you gave as an example, I like Ctrl+some key combinations. There are a lot of free ones in vim, and the letters on the left side near Ctrl make a nice pair then.
Btw, what are you trying to do with those mappings ... I understand the second one (delete word by word), but the first doesn't make sense to me. What is it supposed to do ? Transpose lines ?

Resources