How does one align code (braces, parens etc) in vi? - format

How do you prettify / align / format code in vi? What is the command?
I have pasted in a hunk of code and I need to have it all formatted/aligned... obviously I am a vi neophyte.
x

These commands in my answer work in vim. Most people who think they're using vi are using vim. To find out if your 'vi' is really 'vim', open vi and type :version -- if it's vim, it will say so. Otherwise you might just see a version number without the name of the program. Also, when you open vim for the first time you will usually see a splash screen of some sort that says "VIM - VI iMproved"...
Automatic Indentation
To turn auto-indentation on, make sure vim knows the file type you're editing (it usually automatically detects this from the file name extension, but might not figure it out with some file types). You can tell it the filetype using the menus for syntax highlighting. Then, do this:
:filetype indent on
You can disable auto-indentation with
:filetype indent off
Automatically adjusting/correcting indentation
In general, ={motion} will align code to an indentation level.
== align the current line
=i{ align the inner block
=% align to the matching parenthesis/bracket under the cursor
=14j or 14== align the next 14 lines
=G align to the end of the file
vG= same thing, align to the end of the
file (but using visual mode)
vjjj= align four lines (using visual mode)
Manual indentation
If vim is not guessing the indentation level correctly, there are two ways to change it:
If you are in normal mode (where everything is a command), do << to shift a line left, or >> to shift it right by one tab. You can do this with several lines by using the same movement commands I showed above (eg, >i{ indents the current inner code block).
If you are in insert mode, you can indent the line further (without moving the cursor) by doing a Ctrl-T, or un-indent one tab with Ctrl-D
Aligning equals signs, etc
If you want to align equals signs in a list of declarations, you should consider using this vim script: http://www.vim.org/scripts/script.php?script_id=294
Adjusting indentation/tab sizes
If you want vim to use spaces instead of tabs when it indents, run this command (or consider adding it to your vimrc file)
:set expandtab
To set how many spaces equal a tab, I usually do this:
:set expandtab softtabstop=3 tabstop=3 shiftwidth=3
tabstop - how many columns a tab counts for (affects display of existing tab characters)
shiftwidth - controls reindentation size with << and >>, among other commands.
softtabstop - how much space to insert when you press the tab key
expandtab - expand tab keys to spaces
But if you have to work with different amounts of tabs a lot, you could also use this function and keybinding:
function! Ktabs(tabsize)
execute "set softtabstop=" . a:tabsize . " tabstop=" . a:tabsize . " expandtab shiftwidth=" . a:tabsize
"set softtabstop=a:tabsize tabstop=a:tabsize expandtab shiftwidth=a:tabsize
endfunction
noremap <leader><Tab> :call Ktabs(3)<Left>
If you are editing a file with a mix of tabs and spaces, you may want to use this command after setting tab size:
:retab

={motion}
:h =
P.S. You shouldn't use vi if vim is available.

If manually adjusting indents I will open a visual block with V on the first or last line I want to re-indent, move to the brace containing the block, goto the other brace with % then shift the line with > or <
If indents are off by a lot I will shift everything all the way left with < and repeat it with . and then re-indent everything.
Another solution is to use the unix fmt command as described in Your problem with Vim is that you don't grok vi., {!}fmt

Related

Underlining text in vi

Is there a quick way to insert a line with the same number of hyphens or = characters as there are in the current line in vi(m)? That is, to go from:
My Heading
to:
My Heading
==========
without going to the end of the line, reading the number of characters in it from CTRL-G, opening a new line underneath, and typing <n>i= ?
I use the following mappings in my own markdown.vim:
" Level 1 Heading
nnoremap <leader>1 :co.<CR>Vr=A<CR><Esc>
inoremap <leader>1 <Esc>:co.<CR>Vr=A<CR>
The first mapping is for when already in Normal mode while the second Insert mode mapping returns to Insert mode with the cursor at the start of the line underneath the heading.
Use the Ex copy command, :co to copy the line without affecting the contents of any of the Vim registers.
Then select all of the copied line with V.
Finally, r= replaces each of those characters with an equal sign.
For the mapping keys, I use the leader key (defaults to \) followed by the numeral 1 to represent a Level 1 heading in Markdown.

How to move right or left by 'x' characters in Bash?

In bash sometimes I have very long commands where I need to edit some words. Right now I use End/Home to move end/start of the command, but what if I have to move say x characters in a line?
I need something like xb/xw of VI, but instead of words I need to move characters.
What about ditching emacs mode and switching to vi mode editing?
set -o vi
and you have all the power of vi-like command line editing, like 3l to go left three characters and 5B to go back 5 words. The Pos 1 key then becomes 0 and End becomes $.
In emacs mode, you can use Meta3Controlb to move back 3 characters, and Meta3Controlf to move forward 3 characters. For multi digit counts, you need to precede each digit with the Meta key (e.g., to move 10 characters back, Meta1Meta0Controlb).
Meta is usually the Alt key, but may be the Esc key instead (on Mac OS X, for instance).
(Yes, vi-command mode makes it easier.)
There is a command, universal-argument, that allows you to type all the digits at once, but it is unbound by default. Bind it with, say,
bind "\C-a":universal-argument
then typing Control-a will enter you into an "argument" mode, prefixing the current line (arg: 4), and allowing you to type digits to change the argument used by the next non-digit character you type. (See universal-argument in the bash man page for the full details.)
You could use the command as below
Command:
cp some_file1 some_file2 some_file3 /root/Desktop
After executing the command do the following
^some_file2^some_file4
and it will execute the command
cp some_file1 some_file4 some_file3 /root/Desktop ;
What happened is the some_file2 is replaced by some_file4 and the command is executed

Bash keybinding with "bind" - avoid recursion like noremap in Vim

I've remapped the following keys in Bash:
bind '"a" "b"'
bind '"b" "c"'
If I press a or b both times a c will be printed.
How can I map the keys so that by pressing a and b will be printed and only by pressing a and c will be printed (like with Vims **nore**-map)?
You can make a char in the right part a literal with a preceeding "^V":
bind '"x":"^Vx "'
The key sequence to enter the text after colon is:
" Ctrl-v Ctrl-v x space "
In bash "Ctrl-v x" results in a literal x, without key-mapping interpretation .
You may find it useful to build your own keymapping file which maps the numeric signal you get from the keyboard to a character. This is done with the loadkeys command i.e. if you're switching to the dvorak layout you can do (this is a verbose way to show you the location of the map files:
loadkeys /usr/share/keymaps/i386/dvorak/dvorak.map.gz
You could copy the map file for the layout you use and change the relavent chars, and load your modified mapping. I think loadkeys only affects the command line, though there are similar methods for changing the behaviour in X I believe.

Sublime Text 2: Trim trailing white space on demand

I know that Sublime Text 2 can delete the trailing white space on files upon saving.
When working in a team and commiting a change to a file this tends to produce huge diffs which make peer code review more cumbersome. For that reason I prefer to only do the white space cleaning when I'm commiting huge changes to a file anyway and leave whitespace as it is for the minor changes.
I would like to know if there's any command for executing the trimming of the white space on demand on a file, other than "Activate trimming on save > Save file > Deactivate trimming".
Searching in the Documentation and on stackoverflow didn't show anything relevant, all the links seem to talk about the auto trimming on save.
I use these steps for a quick on-demand solution within Sublime Text:
Find > Replace...
Find What: [ \t]+\n
Replace With: \n
Replace All
You could also do this for a large set of files via
Find > Find in Files...
Find: [ \t]+\n
Where:
Replace: \n
Replace
Beware: using this plugin makes Sublime Text significantly slower
I use TrailingSpaces plugin for this.
Highlight trailing spaces and delete them in a flash.
ST2 provides a way to automatically delete trailing spaces upon file
save. Depending on your settings, it may be more handy to just
highlight them and/or delete them by hand. This plugin provides just
that!
Usage: click "Edit / Trailing Spaces / Delete".
To add a key binding, open "Preferences / Key Bindings - User" and add:
{ "keys": ["ctrl+alt+t"], "command": "delete_trailing_spaces" }
You can simply use a regex to remove trailing whitespaces:
Find > Replace...
Find what: [^\S\r\n]+$
Replace with: leave empty.
Click 'Replace All'
[^\S\r\n]+$ is Regex for "at least one whitespace character (so spaces and tabs but not newlines, using a double negation) followed by the end of the line"
Regular Expression must be enabled:
This method isn't perfect, but uses no plugins or settings and works in most situations.
Multi-Select and move cursor to the end of every line
Hold CTRL-Shift, Press Left, Right
The spaces and tabs at the end of the lines should now be selected. Press Delete or Backspace
Note - Special characters such as ( and + may also be selected at the end of the line at this point, not just spaces.
How to Multi-Select all lines:
One way is to use the middle mouse key to select vertically then hit the End Key if it's a small selection.
With hot-keys:
CTRL-A (select all)
CTRL-SHIFT-L (place cursor on all lines selected)
END (Go to end of lines)
You can also use the find function to find something that will be in every line, like the space character:
\s (using regex)
Click Find All
Press the "End" key to get multiple cursors at the end of each line
Sample Text:
text and number 44 more text and a space
text and number 44 more text and 2 tabs
text and number 44 more text and no space or tab
text and number 44 more text after a line feed
I found a soulution here:
http://www.sublimetext.com/forum/viewtopic.php?f=4&t=4958
You can modify the package
trim_trailing_white_space.py
located in the default packages directory, this way:
import sublime, sublime_plugin
def trim_trailing_white_space(view):
trailing_white_space = view.find_all("[\t ]+$")
trailing_white_space.reverse()
edit = view.begin_edit()
for r in trailing_white_space:
view.erase(edit, r)
view.end_edit(edit)
class TrimTrailingWhiteSpaceCommand(sublime_plugin.TextCommand):
def run(self, edit):
trim_trailing_white_space(self.view)
class TrimTrailingWhiteSpace(sublime_plugin.EventListener):
def on_pre_save(self, view):
if view.settings().get("trim_trailing_white_space_on_save") == True:
trim_trailing_white_space(view)
class EnsureNewlineAtEof(sublime_plugin.EventListener):
def on_pre_save(self, view):
if view.settings().get("ensure_newline_at_eof_on_save") == True:
if view.size() > 0 and view.substr(view.size() - 1) != '\n':
edit = view.begin_edit()
view.insert(edit, view.size(), "\n")
view.end_edit(edit)
Now you can add the command to your keymap configuration:
{ "keys": ["your_shortcut"], "command": "trim_trailing_white_space" }

How would you do a cut and paste with this in VIM?

Say you had this text:
SOMETHING_XXXXXXXXXXXXXX_ELSE
SOMETHING_XXXXXXXXXXXXXX_ELSE2
SOMETHING_XXXXXXXXXXXXXX_ELSE3
SOMETHING_XXXXXXXXXXXXXX_ELSE4
And you wanted to replace all XXX..XXX with this word:
HELLOWORLD
If I go into visual mode, then yank the word, how could I then replace the XXX..XXX in the 4 lines above using cut and paste?
If I try, what happens is the X gets into my 'clipboard' and then I'm stuck to just typing it out manually.
I'm not sure if it will work in viemu, but in VIM you can do the following...
Using Yank and Paste
Yank the text to a specific register. Select the text in visual mode and use the command "ay to yank the text to the register a. Then when pasting call the command "ap, which pastes the contents of the a register.
Using Normal Command
But I would strongly prefer to use the normal command. Just select the lines
SOMETHING_XXXXXXXXXXXXXX_ELSE
SOMETHING_XXXXXXXXXXXXXX_ELSE2
SOMETHING_XXXXXXXXXXXXXX_ELSE3
SOMETHING_XXXXXXXXXXXXXX_ELSE4
using line visual mode (<C-v>) and then issue this command: :'<,'>normal fXct_HELLOWORLD. Then you'll have
SOMETHING_HELLOWORLD_ELSE
SOMETHING_HELLOWORLD_ELSE2
SOMETHING_HELLOWORLD_ELSE3
SOMETHING_HELLOWORLD_ELSE4
This means that it will run the command fXct_HELLOWORLD for each line. Let me explain the command:
fX - moves the cursor until the first X;
ct_ - deletes everything untill _ and puts you in insert mode;
HELLOWORLD - the word which will substitute XXXXXXXXXXXXXX;
One way would be to visually select all the code you want to replace and change it at once
Ctrl+v 3jt_cHELLOWORLD[Esc]
Note: it takes a couple of seconds for all lines to be updated
Another way to be by creating a macro:
record macro:
q10fXct_HELLOWORLD[esc]q
run macro on other lines:
j#1j#1j#1
q1 records a macro on character 1
#1 replays macro
But search and replace is a good alternative for your question
Highlight the four lines in visual mode, then
:'<,'>s/X\+/HELLOWORLD/g
Via this question: How do I use vim registers? I found ^R in command mode will paste from a register.
For example, with XXXX highlighted then yanked into the " register:
:s/^R"/HELLOWORLD/g

Resources