How do I fix the indentation of an entire file in Vi? - vim

In Vim, what is the command to correct the indentation of all the lines?
Often times I'll copy and paste code into a remote terminal and have the whole thing messed up. I want to fix this in one fell swoop.

=, the indent command can take motions. So, gg to get the start of the file, = to indent, G to the end of the file, gg=G.

Before pasting into the terminal, try :set paste and then :set nopaste after you're done. This will turn off the auto-indent, line-wrap and other features that are messing up your paste.
edit: Also, I should point out that a much better result than = indenting can usually be obtained by using an external program. For example, I run :%!perltidy all the time. astyle, cindent, etc. can also be used. And, of course, you can map those to a key stroke, and map different ones to the same keystroke depending on file type.

The master of all commands is
gg=G
This indents the entire file!
And below are some of the simple and elegant commands used to indent lines quickly in Vim or gVim.
To indent the all the lines below the current line
=G
To indent the current line
==
To indent n lines below the current line
n==
For example, to indent 4 lines below the current line
4==
To indent a block of code, go to one of the braces and use command
=%

If you want to reindent the block you're in without having to type any chords, you can do:
[[=]]

You can use tidy application/utility to indent HTML & XML files and it works pretty well in indenting those files.
Prettify an XML file
:!tidy -mi -xml %
Prettify an HTML file
:!tidy -mi -html %

press escape and then type below combinations fast:
gg=G

1G=G. That should indent all the lines in the file. 1G takes you the first line, = will start the auto-indent and the final G will take you the last line in the file.

if you do not want to use :set paste, middle-click, set nopaste, you can also paste the content of the clipboard:
"*p
"+p
That way you don't have to leave normal mode.
if you have to paste + or * depends on how you selected the text, see :help quoteplus.

In Vim, use :insert. This will keep all your formatting and not do autoindenting. For more information help :insert.

:set paste is your friend I use putty and end up copying code between windows. Before I was turned on to :set paste (and :set nopaste) copy/paste gave me fits for that very reason.

For complex C++ files vim does not always get the formatting right when using vim's = filter command. So for a such situations it is better to use an external C++ formatter like astyle (or uncrustify) e.g.:
:%!astyle
Vim's '=' function uses its internal formatter by default (which doesn't always gets things right) but one can also set it use an external formatter, like astyle, by setting it up appropriately as discussed in this question.

vim-autoformat formats your source files using external programs specific for your language, e.g. the "rbeautify" gem for Ruby files, "js-beautify" npm package for JavaScript.

For XML files, I use this command
:1,$!xmllint --format --recover - 2>/dev/null
You need to have xmllint installed (package libxml2-utils)
(Source : http://ku1ik.com/2011/09/08/formatting-xml-in-vim-with-indent-command.html )

You can create a mapping to do this for you.
This one will auto indent the whole file and still keep your cursor in the position you are:
nmap <leader>ai mzgg=G`z

Just go to visual mode in vim , and select from up to down lines after selecting just press = , All the selected line will be indented.

For vi Editor, use :insert. This will keep all your formatting and not insert auto-indenting.Once done press escape to view the actual formatted file otherwise you'l see some garbage characters. like ^I
e.g:
public static void main(String[] args) {
^I
^I System.out.println("Some Garbage printed upon using :insert");
}

Related

SLES12 vim - background changes scrolling + copy paste issues

I am using gnome-terminal with SLES12 and I encounter an issue where I am scrolling down during showing file in vim, the background color is changing.
Using some exploration during the internet I got the following solution :
if &term =~ '256color'
" Disable Background Color Erase (BCE) so that color schemes
" work properly when Vim is used inside tmux and GNU screen.
set t_ut=
endif
But using this solution, it creates a new one.
When I copy paste a line from vim and paste it on other vim , the copy consider also the blank lines in as characters , and creates really long lines.
To emphasize, lets say I have the following line which contain 11 char (including the space)
the copy paste consider also the rest of the line (the blank ones) as characters.
I would like that the copy paste would stop at char 'd '
hello world
Any idea how to combine a solution for these two issues?
The two issues are completely unrelated.
When you "copy paste a line from vim and paste it on other vim", you are presumably using your terminal emulator's or system's copy/paste feature which have no idea about where what you consider as a line starts and where it ends. The terminal emulator's window is n characters wide so a line is n characters and that's all they care about.
A much better approach would be to use Vim's built-in :help y and :help p, which have the same idea of what a line is as you.
But this creates a second problem: the default Vim is generally not built with clipboard support so you can't really use yy to yank a line in one Vim and p to put it in another one. You will have to install a proper Vim for that: use your package manager for that.
Once you are set, you can yank to clipboard with "+y and put from clipboard with "+p. See :help registers for "+ and :help 'clipboard' if you would like to synchronise Vim's default register with the system clipboard.
That said, why don't you simply open those two files in a single Vim instance?

What's wrong with gVim copy paste between windows?

I'm new to vim and I'm using gVim on Windows. I have two windows open in the same gvim instance and I'm just trying to copy some code from one to another. For some reason when it pastes it replaces the contents of some code with literally this:
list.forEach(function(name){...}------------------------------------------
Obviously, my real code does not have ... or a ton of dashes. What the hell is happening?
The dashes (----------) give it away: The block of code has been folded. (You probably also see the line with different colors (depending on your colorscheme).) Depending on the filetype, folding can be manual or automatic. For your (JavaScript?) code, it's the latter. So when you paste a block of code, Vim automatically detects the block and folds it.
There's a whole lot of commands and options around folding. Read more about it at :help folding. If you find this too confusing (for now), turn it off via
:set nofoldenable
Just press zo on the dashes(-----)
Aside: Use zf on selected (v) lines to fold lines.
zo - Open
zo - Fold

Using AStyle in Vim

I am trying to get AStyle working with Vim so that I can use the "=" key to re-indent various sections of code. For example, I'd like to be able to type my usual =iB to indent the current block of code using AStyle rather than the built in indenter.
I tried just setting equalprg=astyle in my vimrc, but the problem is that astyle only receives the selected block but thinks that it's receiving a whole file. Therefore, the indentation is completely off when I try to only indent a nested class.
I know that I can always reformat an entire file at once, but is there a way to use astyle in vim which completely replicates the original formatting behavior of vim (all my =-movement commands work - and bonus points for autoindent using astyle as well!)?
Unless there is a version of AStyle that has a partial file formatting option, you'll need to apply the extra indentation after you run AStyle.
I'm not sure how you can do this with motions.
With visual selection, you could grab the indentation from the first line, pass the code to equalprg, and then add that indentation to all of the lines:
vnoremap = <Esc>`<dwgv=`<<C-v>`>I<C-r>"<Esc>
Breaking it down:
vnoremap -- so we can use = for equalprg
<Esc>`< -- stop selecting and go to beginning of line at beginning of selection
dw -- grab the initial indentation
gv= -- reselect and indent as normal
`<<C-v>`> -- block select the selection
I<C-r>"<Esc> -- insert the initial indentation
Maybe you can do something similar with motions?
It only works for formatters that have a partial file formatting option, like idbrii already pointed out. An example of a formatter that does this is clang-format.
One way to integrate this into vim is by using vim-autoformat. Using this plugin you can viB and then press your self-defined format key, like <F3>. This will then only format the selected inner code block.

How to prevent Vim indenting wrapped text in parentheses

This has bugged me for a long time, and try as I might I can't find a way round it.
When I'm editing text (specifically latex, but that doesn't matter) files, I want it to auto-wrap at 80 columns. It does this, except if I happen to be in the middle of a parenthetical clause, it indents the text which is very annoying. For example, this works fine
Here is some text... over
two lines.
but this doesn't
Here is some text... (over
two
lines
If anyone can tell me how to turn this off (just for text/latex files) I'd be really grateful. Presumably it has something to do with the fact that this is desired behaviour in C, but I still can't figure out what's wrong.
:set nocindent
The other options do nothing, and the filetype detection doesn't change it.
There are three options you may need to turn off: set noai, set nosi, and setnocin (autoindent, smartindent, and cindent).
This may be related, when pasting from gui into terminal window, vim cannot distinguish paste modes, so to stop any odd things from occuring:
set paste
then paste text
set nopaste
I had similar issues trying to paste xml text, it would just keep indenting. :)
gvim, the gui version of vim, can detect paste modes.
You can have a look at the autoindent option :
autoindent - ai
Copy indent from current line when starting a new line (typing
in Insert mode or when using the "o" or "O" command). If you do not
type anything on the new line except and then type or
, the indent is deleted again. When autoindent is on,
formatting (with the "gq" command or when you reach 'textwidth' in
Insert mode) uses the indentation of the first line. When
'smartindent' or 'cindent' is on the indent is changed in specific
cases. The 'autoindent' option is reset when the 'paste' option is
set. {small difference from Vi: After the indent is deleted when
typing or , the cursor position when moving up or down is
after the deleted indent; Vi puts the cursor somewhere in the deleted
indent}.
From the official Vim documentation
filetype plugin indent on
This switches on three very clever
mechanisms:
Filetype detection. Whenever you start editing a file, Vim will try to
figure out what kind of file this
is. When you edit "main.c", Vim will
see the ".c" extension and
recognize this as a "c" filetype.
When you edit a file that starts with
"#!/bin/sh", Vim will recognize it as
a "sh" filetype. The filetype
detection is used for syntax
highlighting and the other two
items below. See |filetypes|.
Using filetype plugin files Many different filetypes are edited with
different options. For example,
when you edit a "c" file, it's very
useful to set the 'cindent' option to
automatically indent the lines. These
commonly useful option settings are
included with Vim in filetype plugins.
You can also add your own, see
|write-filetype-plugin|.
Using indent files When editing programs, the indent of a line can
often be computed automatically.
Vim comes with these indent rules for
a number of filetypes. See
|:filetype-indent-on| and
'indentexpr'.
:set noai
sets no auto indent tt may be smartindent though. Check out the doc and see if you can find something more
http://www.vim.org/htmldoc/indent.html

Vim / vi Survival Guide

What are the essential vim commands? What does a new-user need to know to keep themselves from getting into trouble? One command per comment, please.
What I find irreplaceable (because it works in vi also, unlike vim's visual mode) are marks. You can mark various spots with m (lower case) and then a letter of your choice (eg x). Then you go elsewhere, and can go back with ``x(backquote letter) to the exact spot, or with'x` (apostrophe letter) to go to the line.
These movements can be used as arguments to commands (yank, delete, etc). For example, you want to delete 10 lines; instead of counting and then moving to the topmost line and entering 10dd, you go to either the start or the end of the block, press mm (mark m), then go to the other end of the block, and press d'm (delete apostrophe m). If you use backquote instead of apostrophe in this example, then the deletion will work character-wise, not line-wise. Try marking in the middle of the line with "mark m", moving to the middle of another line, then entering "d backquote m" and you will see what I mean.
I was very happy the day I learned about using * or # to search, down or up respectively, for the word under the cursor. Make sure to :set incsearch and :set hlsearch first.
I like this QRC!
http://www.fsckin.com/wp-content/uploads/2007/10/vi-vim_cheat_sheet.gif
When you have some repetitive action to take Macros are usually faster than regex.
Just type
q[0-9a-z] in normal mode
Many people use
qq
because it's fast.
Press
q in normal mode
again to stop recording.
Then just type
#[0-9a-z] in normal mode
to repeat what you just recorded.
#q
for the example like above.
Edited to add: you can also repeat the macro. Let's say you programed a macro to jump to the head of a line, insert a tab, and then jump down one line. You then test your macro by typing "#q" to run it once. Then you can repeat the action nine more times by typing "9#q".
:q -> quit
:w -> save
:q! -> quit and don't save
:x -> save and quit
:[number] -> go to line number
G -> go to end of file
dd -> delete line
p -> "put" line
yy -> "copy" line
:s/[searchfor] -> search
I guess those are the basic one to start from
Use the 'J' (J for Join; upper-case) command to delete the newline at the end of a line. You'll find it tricky otherwise.
This recent Vim tutorial from IBM is pretty good
First of all you need to know how to close vi:
ctrl-c : q!
Rest can be found from vimtutor. Launch vimtutor by typing vimtutor at your command line
Although this is a matter of personal preference I've found that one of the essential things to do is to remap Esc to something else.
I find it very uncomfortable to reach for the Esc key to exit insert mode, but the beautiful thing about Vim is that allows key mappings.
I'm currently using the following mapping using Control + S:
inoremap <C-s> <Esc>:w<CR>
This has the advantage of being a key mapping I have already committed to memory and has the added value of saving my work every time I go to normal mode. Yeah, I know it is crazy but I would be hitting the save command that frequently anyway. It's like a bad habit, you know.
" ~/.vimrc
" Turn on line numbering
set nu
" Turn on syntax highlighting
syntax on
" Set 4 space expanding tabs
set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab
"turn off line wrapping
set nowrap
" Map CTRL-N to create a new tab
:map <C-n> <ESC>:tabnew<RETURN>
" Map Tab and CTRL-Tab to move between tabs
:map <Tab> <ESC>:tabn<RETURN>
:map <C-Tab> <ESC>:tabp<RETURN>
If you're using vim, the 'u' command (in command mode) will Undo the last command you typed. You can use this command repeatedly to undo mistakes you may have made before saving the file.
See http://www.rayninfo.co.uk/vimtips.html for a great collection of Vim tips, from the basic can't-live-without to very sophisticated stuff that you might never have thought of trying.
Lots of great commands are listed at the Vim Tips Wiki.
It's also good to run the vimtutor when learning these commands
alias vi nedit :)
all humor aside..
for vi WHEN NOT using nedit..
i (switch to insert mode)
a (append = move to end of line and switch to insert mode)
esc (exit insert mode)
dd delete a line
x delete a character
:wq (save and quit)
/ start a search
n find Next
? search backwards..
yy (yank) copy a line to the buffer
pp (paste) paste it here
r (replace a character)
<N> <command> this is a neat - but aggravating feature that lets you type digits and then a command so
5dd will delete 5 lines
but at this point you might as well
- man vi and refresh your memory
While there are LOTS more, I switched from Vi to nedit several years ago, which I find has more features I can use on a regular basis more easily. Tabbed editing, incremental search bar, column select, copy and paste. sort selected lines, search and destroy within selection, whole doc or all open docs..
tear-off drop down menus..
and it supports syntax highlighting for all the languages I use.. (with pattern files I've used a long time over the years. VIM many now be equivalent, but It has to introduce a feature that Nedit doesn't and an easy way to migrate my pattern files before I switch again.
I like the Vim 5.6 Reference Guide, by Bram Moolenaar and Oleg Raisky.
You can directly print it in booklet form, easy to read, I always have it laying around.
It's a tad old, but what are 8 years in Vi's lifespan ?
:set ignorecase smartcase
Makes searching case-insensitive, unless your search includes a capital letter. Not the most indispensable perhaps, but I find myself setting this option any time I'm editing in a new place. It's in any vimrc file I own.
:%!xxd
View the contents of a buffer in hexadecimal. To revert:
:%!xxd -r
My biggest tip: ctrl+q saves the day when you accidentally hit ctrl+s to save the file you are working on
I have this in my vimrc
set number
set relativenumber
This gives me a line numbering system which makes j, k keys really productive.
I use vi very lightly, and I only use the following commands:
a - switch to insert mode (after the cursor)
esc - return to command mode
:wq - save and quit
:q - quit (no save, only without modification)
:q! - force quit (no save, also with modification)
x - delete one character (in command mode)
dd - delete the whole line (in command mode)
I know there are many many more, but those are enough to get you by.
One of my favourite commands is %G which takes to directly to the end of a file. Especially useful in log-files.
How to switch between modes (i to enter insert mode (one of many ways), esc to exit insert mode, colon for command mode) and how to save and exit. (:wq)
Another useful command is to search something: /
e.g. /Mon will search (and in case of vim highlight) any occurences of Mon in your file.
As a couple of other people have already mentioned, vimtutor is the way to go. It will teach you everything you need to know in vim. The one piece of general advice I would give you is to stay out of insert mode as much as possible. There is enormous power in the other modes, it just takes a little bit of practice to get used to it.
i - insert mode (escape to exit)
dd - delete line
shift-y - 'Yank' (copy) line
p - 'Put' (paste) line(s)
shift-v - Visual mode used to select text (tryin 'yanking' this text and 'putting' it somewhere.
ctrl-w n - create new window (you can open a file or start new file here)
ctrl-w v - split existing window vertically
ctrl-n (in insert mode) - autocomplete (if supported)
:! to run a shell command, usually with standard in as the file or a selection (shift-V)
Useful plugins to look at:
* Buffer Explorer - use \be to view files in the buffer (and select to re-open)
NB vi is not vim! vim is rapidly turning into the emacs of the new century. nvi is probably the closest thing to the original vi. Here's a nice hint: "xp" will exchange two characters (try it).
replace 'foo' with 'bar' everywhere in the file
:%s/foo/bar/gc
The real power is in the searching. Here are the essential commands:
/Steve will find the first instance of "Steve" in the text.
n will find the next "Steve" in the text.
:%s//Stephen/g will replace all those instances of "Steve" you just searched for with "Stephen".
Not to promote myself, but I wrote a blog post on this subject. It focuses on the critical parts of Vim for a beginner.
My favorites:
% find matching bracket/brace
* and # next/previous match
gg top of page
G end of the page
<Ctrl-v> Change to visual mode and select column
<Ctrl-a> increase current number by 1
<Ctrl-x> decrease current number by 1
Running macros

Resources