What should I use vim Visual mode for? - vim

I have been using vim for a couple of years now, and though I have learnt a lot of time saving shortcuts, but I have never used the Visual mode, which is supposed to be all powerful :
... Visual block mode (to edit columns) is something many editors lack, but that I can't live without. I have shocked and awed people at work using just this, making some edit in a few keypresses that someone would've otherwise spent ten minutes doing manually.
I want to understand why and when should I be using Visual mode.
Can someone give me an example of "making some edit in a few keypresses that someone would've otherwise spent ten minutes doing manually"?

If you see CTRL-CCTRL-V and recognise what it does, you should use visual mode.
If, like me, you see A:esc0df:$p$x as an edit command, don't bother :-)

When I use visual mode, it's to select whole lines or blocks. For example you can do [esc][shift+v][y] to copy the currently line I'm on. Here's more information.

Visual mode allows you to perform an operation on a block of text. It is the only way to perform an operation on a block in Vim.
A simple example of this would be copying or moving text.
A more advanced example would be sorting the lines in a certain part of a file. You can do this by entering visual mode, selecting a block of text, pressing Esc to enter command mode, and typing !sort. You can see more details about his example and how it works here: http://www.oualline.com/vim-cook.html#sorting_visual

I actually just did a screencast showing off great uses for visual mode. You can check it out at http://lococast.net/archives/241
As other's have said, it's great for doing any sorts of editing (edit, remove, search/replace) withing a specific range of code.

Insert a column of commas.
Delete a column of commas.
Act on rectangular selections.
Act on a section of text that is not a line or word.

Several good examples have already been given. Here are some others.
I also use visual mode:
To swap two regions of text.
To refactor out variables, types, and functions.
To surround the selection with pair of things (usually brackets)(NB: surround.vim also does this I guess), but also with control statements.
But simply most of the time to have a more interactive way to yank or change text.
To paste over without overwriting the current unnamed register.
To highlight the current selection (with Mark.vim)
And to do many other things I don't remember right know.

Related

How to remove tabs on multiple rows at once

This is not a programming question but an inconvenience in the android-studio editor.
If you have an unwanted tab before all your lines, how can you remove them all at once? Now I have to manually go over 50 lines to remove all the tabs to make my code look clean.
If you want to add multiple tabs at once you just select all your code and press the tab button. So I'm looking for the reverse of that.
If I understood you right, you want to beautify the code itself. Fortunately, you don't have to do that manually - at all.
There's a keybinding for it, which may vary by your OS and which layout you use by default. Go to file -> settings -> Keymap and search for auto-indent. Here's what I get on Windows 10 with the default keymap:
Again, which you have may depend on OS (I'm assuming that mainly applies to Mac though) and your keymap, but you can automatically indent your code as per language standards using Ctrl+Alt+I.
Note that this mainly does indentation. If you chose to golf code and want to ungolf it, this will not work. At least it doesn't for Java.
However: This only works with code files the IDE or plugins support. This won't work for i.e. a .txt file out of the box.
If I misunderstood you and you only want to remove tabs without doing the auto-indent, there's at least two other options.
The first option is using multiple cursors. You can add an additional cursor with shift+alt+a mouse click where you want the cursor, or holding the mouse wheel and moving the cursor with the mouse wheel held down. There might be other methods as well, but those are the two I know of.
Once you have multiple cursors, delete the tabs just like normal. But be careful! Doing so might delete the entire line itself. If it does, you can do 1 tab/n units per indent level to the left, and press delete instead.
There's (AFAIK) no limit to how many cursors you can have at once, but you can theoretically do it with 50 lines at once if you want to. But general advice - don't add more cursors than you can see at once. These do run in parallel and it's easy to lose track if you're not careful, and you might end up deleting stuff you didn't want to delete.
And finally, the regex solution:
Note: Be careful with this. If you use it incorrectly, you might get unwanted results.
If you only want to do this in a limited area, highlight it first. Then CTRL+R and you'll be presented with the regular replace menu. Make sure Regex and In Selection are selected.
A base regex to go off is ^([\s]{2,4}|\t). Explanation just for reference:
^ - At the start of the line
(
\s{4} - Match 4 spaces
|\t - Or a tab character
)
Replace with nothing and click "replace all" (or just use the regular "replace" button if you want to double-check before you do anything). This will replace one occurrence of 4 spaces or a single tab character. If you use indentation that isn't based on 4, change the number.
This is only useable and useful if you've found yourself with incorrect indentation that's the same across all the relevant lines - it will not fix indentation mistakes and/or inconsistencies such as 3-space indentation when you want 4, or random indetation for the same block. Use the first or alternatively second method for that instead.

VIM: motion without jk and HardMode installed

I am enjoying hardmode and have definitely seen improvement. However the one item I am dealing with is selecting, moving, copying only two lines at the time. Current line +1 or -1.
Before hardmode the way I would select three lines of code in visual mode would be with the motion:
V2j
Since HardMode disables the "j" key what would be a good substitute to such move?
About HardMode:
Hard Mode is a plugin which disables the arrow keys, the hjkl keys,
the page up/down keys, and a handful of other keys which allow one to
rely on character-wise navigation. The philosophy behind Hard Mode is
that you'll never master Vim's advanced motion and search
functionality if you can fall back on the anti-pattern of fumbling
around your code with the arrow keys.
https://github.com/wikitopian/hardmode
For me, HardMode is all about changing your mindset about how you move in vim. Really getting comfortable with text objects, searching etc.
In this case, you can just use 3V (3 <S-v>) to select 3 lines.
I'd urge you to learn some ex commands while you work in HardMode. Like use
:8,15d " To delete lines from line no. 8 through 15
:8,15co . "To copy range of lines 8 through 15 to current cursor position.
You can also use
:.+3 " To move down
:.-3 " To move up 3 lines
but then you'll be totally missing the point. Just use HardMode for what it's meant to be. Which is learn a few things in a constrained situation.
I think I see the point of hardmode now, and you got an answer for how to select multiple lines in visual mode. That answer is correct, but maybe you don't need to select at all? You mentioned copying, or moving, a few lines. For that, try using counts with your yank/delete commands. Example, to copy 5 lines:
5yy
To delete 3 lines:
3dd

How to get a better column edit mode in vim (more visualizable and customizable)

Vi experts, I have two questions concerning the column editing!
First, I already know how to go to the visual mode and do a column edit. But the point is that after shift+I and type, you can only see the first row changing before esc. My question is this, is it possible to make the editing operation visible in all rows? Or is this still an impossible task with the current vim?
My second question is, I want to insert a column with increasing numbers (0...9) or some user defined increasing items such as (monday...sunday) blahblah, what is the best way to achieve this, can I define a few customized functions and then call them?
"Still an impossible task" exposes a wrong assumption: Vim never wanted to be a WYSIWYG editor; just updating the current row requires less screen updates (which can be significant over slow connections; the whole modal editing of vi was partly born out of that necessity).
There are some attempts at "multiple cursors" plugins; with those, you might achieve this, though.
second question
(Note that it is bad style to ask about two unrelated things in a single question.)
Yes, you can do almost anything in "a few customized functions" (but you'd have to clarify your exact use case to get meaningful answers).
Some of that can be done via the speeddating plugin:
{Visual}<C-A> Increment by [count] the component under the cursor on each line of the linewise visual selection. If a component is absent on a line, it is filled in as being [count] higher than on the line above it. This can be used to create sequences. For example, place a "0" on a line followed by 4 blank lines, visually select all 5 lines, and press <C-A> to get a sequence of 1 through 5. You can use letters in visual mode too: make the first entry Z if you want a list starting with A.

VIM: Respect only current code block

I have started working on a huge PHP application that has thousands of lines of code in each file, with lots of huge if blocks, classes, and functions all existing in the same file. I'm not the only dev working on it, so I cannot refactor!
I have tried using the Tags List plugin but it does not really help. Is there any way to have VIM respect only a particular code block, and ignore the rest of the file? I am hoping for some or all of these features:
Enable line numbering only for the current code block, starting from 1 at the line containing the opening {, and showing no numbering for lines preceding it or after the closing }.
Searching with / would be restricted only to the block in question.
I am thinking along the lines of selecting the current block and editing it in a new buffer when enabling the mode, then replacing the existing block with the edited block when exiting the mode. However, I am having trouble actually implementing this feature. My current version is this:
map <F7> <Esc>mO<C-V>aBy:new<Return>p:set nu<Return>:set ft=php<Return>ggi<?php<Return><Esc>
map <F8> <Esc>ggdd<C-V>aBx:bp<Return>`O<C-V>aBp
However, this has several issues, such as the inability to perform incremental saves.
I would be very surprised if Vim allows the kind of line numbering you ask for.
This plugin (and 1 or 2 similar ones IIRC) allows you to visually select a region of your current file, work on it in another buffer and put everything back in its place in the original file on :w.
Even if it's not the solution you are wanting, I think the following can help you to solve your problem.
You can use phpfolding plugin, which folds by PHP syntax (functions, classes, methods, PhpDoc...)
You can then select a fold by pressing v$ over the closed fold and execute whatever you want with :whatever. For example, :s/this/self/g to substitute all this for self in the fold. When you press :, vim will automatically add '<,'> to denote following command it's only for the visually selected text.

What is the most convincing command in Vim

I want to ditch my current editor. I feel I need something else. That do not expose my hands to the risk of RSI. I need to see why I should change editor. And it would be nice to believe, that I will be coding when I'm 80 years old.
All the big guys out there are using Vim. The only Emacs guy I know are RMS. Paul Graham is a Vi dude.
. (dot) - repeats the last editing action. Really handy when you need to perform a few similar edits.
:help usr_12.txt
That'll bring up a section in the help system that discusses "Clever Tricks". If those don't get you excited I don't know what will!
Recording macros
The asterisk.
*
Its effect: Immediately search for the next instance of the word under the cursor.
The best thing is the efficiency with which you can edit code (which is done a lot in programming). The commands such as
cw to change a word
dw to delete a word
ct, to change all text until the next comma
ci( to change the contents of the parentheses you're currently in
xp to correct spelling mistakes ("spleling" -> cursor on l -> xp -> "spelling")
o to insert a new line below and start editing
O to insert a new line above
Then there is the possibility to work with named registers very quickly. To move a block, just select it, press d, then move to it's new location and press p. Much faster than Ctrl-C and Ctrl-V. Use "ud to delete text and move it to register u (I use this one for the commenting template).
And also Vim has all the scripting support you need (either using it's native scripting language or using Python, Ruby, ...)
the numbers.
in command mode
type a number ( any number of digits )
type a command.
that command will be executed $number times
ie:
99dd
erases the next 99 lines.
The fast startup time.
The sharp distinction between editing and viewing. (you know when you edit)
The only way you ever find what you are looking for is with search "/" and that is good, since it much faster than your eyes.
But the best command(s) are:
/ - search string
ZZ - quit
. - repeat last insert (I think)
%! - insert unix command
Handling multi line regexps in search strings with "\_.". While checking over 4GB text files of various formats, it had saved my life several times.
Why are you looking to be convinced to start using a different editor? If you're happy with what you have now, stick. If not, perhaps ask about editors with features that you lack.
Even if you are using Visual Studio there is the wonderful vsvim.
I love the speed of Vim but I find it lacks the features of a modern IDE for C++ development. Eclipse CDT with the viPlugin is a good compromise.
You get the power and source overview provided by Eclipse CDT with the speed and flexibility of Vim for coding.
The lovely built in regular expression evaluator.
Maybe reading "Come home to vim" by Steve Losh article is a good start, or
a series of videos about interesting plugins. And be sure to see some articles on the site vimcasts.org
You should map Caps Lock to Esc. It will make getting out of insert mode feel natural as opposed to the awkward move you must make to press the ESC key. Besides, who uses Caps Lock anyway?
\v
Make your regular expressions mostly Perl compatible.
See very magic section here for more information.
To be truly inspired, you must see a vim guru in action. If you do not have a local guru, here is a video to inspire you.
http://www.youtube.com/watch?v=jDWBJOXs_iI&feature=related
If you don't already know vim, the speed at which code is navigated, sliced, and diced will be indistinguishable from magic. After a few months of studying vim, the same editing speed will seem commonplace.

Resources