A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

Jump to

Quick reference

Showing posts with label vi. Show all posts
Showing posts with label vi. Show all posts

Vim mappings for commands like JSON pretty-print and perltidy

imap :!python -m json.tool
map :%!perltidy

?
nmap :%!python -m json.tool

# AB
nmap :%!python -m json.tool
map :!perl -cW %
map :%!perltidy
map :resize +10

Syntax highlight in vim by file extension

How to add file extension syntax highlighting to vi.
Whack this in your ~/.vimrc

au BufNewFile,BufRead *.tt set filetype=perl

(source)

Emacs for a vi user

In the past I've exclusively used vi, but now I want to use Emacs as I've heard it has some useful modes, for example 'font-lock-keywords' mode which is one way to easily highlight certain keywords in a program's console output. I don't want to mess around compiling specialised text highlighting programs, and they're not in my standard repos. Emacs is much more likely to already be available wherever I need it.

Emacs commands:
  • To exit: C-x C-c
  • Turn on syntax highlighting: M-x font-lock-mode

Key:
C = Ctrl
M = Meta (Alt)

Thanks to the rest of the web

UPDATE: It turns out font-lock-keywords can easily be implemented in a 3 line bash script. Call it "highlight":

    # Usage: tail -f error.log | highlight "error"
    RED="$(tput setaf 1)"
    RESET="$(tput setaf 7)"
    sed "s/$1/$RED$1$RESET/"

But I would still like to see the Perl debugger integrated into Emacs

Vim experiment: Disable arrow keys


" EXPERIMENTAL

" Disable the arrow keys so you're forced to use h,j,k,l
" and other key bindings and will therefore be more productive
" an experiment

"  inoremap  <Up>     <NOP>
"  inoremap  <Down>   <NOP>
"  inoremap  <Left>   <NOP>
"  inoremap  <Right>  <NOP>
"  noremap   <Up>     <NOP>
"  noremap   <Down>   <NOP>
"  noremap   <Left>   <NOP>
"  noremap   <Right>  <NOP>

" cf the default statusline: %<%f\ %h%m%r%=%-14.(%l,%c%V%)\ %P
" format markers:
"   %< truncation point
"   %n buffer number
"   %f relative path to file
"   %m modified flag [+] (modified), [-] (unmodifiable) or nothing
"   %r readonly flag [RO]
"   %y filetype [ruby]
"   %= split point for left and right justification
"   %-35. width specification
"   %l current line number
"   %L number of lines in buffer
"   %c current column number
"   %V current virtual column number (-n), if different from %c
"   %P percentage through buffer
"   %) end of width specification
"set statusline=%<\ %n:%f\ %m%r%y%=%-35.(line:\ %l\ of\ %L,\ col:\ %c%V\ (%P)%)

vimdiff fun with git

Step 1: add this to your .gitconfig
[diff]
  external = git_diff_wrapper
[pager]
  diff =


Step 2: create a file named git_diff_wrapper, put it somewhere in your $PATH
#!/bin/sh
vimdiff "$2" "$5"


Still have access to the default git diff behavior with the --no-ext-diff flag. Here’s a function to put in your bash configuration files:
function git_diff() {
  git diff --no-ext-diff -w "$@" | vim -R -
}


Source: http://technotales.wordpress.com/2009/05/17/git-diff-with-vimdiff/

Diff fun with vi and svn

Diff two files side-by-side
(search for this to highlight differences only -- replace ^I with actual tabs -- / <^I| <$| >^I| >$| \|^I )
diff --side-by-side [a] [b] | less

Diff two files side-by-side using vi
(use Ctrl-W+W to switch sides; may need :syntax off to prevent colours clashing)
vimdiff [a] [b]

Subversion diff using vi
Step 1. Create a diff command script for svn (and set the execute bit):
#!/bin/sh
# Subversion provides the paths we need as the sixth and seventh parameters.
LEFT=${6}
RIGHT=${5%    (working copy)}
[ "$RIGHT" == "$5" ] && RIGHT=$7
# Call the diff command (change the following line to make sense for your merge program).
# diffopt+=iwhite ignores whitespace differences
# \<c-w>\<c-w> switches to the right-hand pane
vimdiff "+set diffopt+=iwhite" '+execute "normal \<c-w>\<c-w>"' $LEFT $RIGHT


Step 2. Create a diff script for you to use:
#!/bin/bash
# Call the diff command (change the following line to make sense for your merge program).
# "-x -w" ignores all whitespace
svn diff -x -w --diff-cmd /path/to/diff/command/script/above $1


Step 3. Run the diff script
name_of_your_script [file in workspace]

Using vim's viewports

  • :sp [filename] will split the Vim window horizontally
    • Can be written out entirely as :split
    • [filename] is optional, if it's omitted then the current file is loaded in the new viewport
  • :vsp [filename] will split the Vim window vertically
    • Can be written out as :vsplit
  • Ctrl-e [filename] loads a new file into the current viewport
  • Ctrl-w Ctrl-w moves between Vim viewports.
  • Ctrl-w j moves one viewport down.
  • Ctrl-w k moves one viewport up.
  • Ctrl-w h moves one viewport to the left.
  • Ctrl-w l moves one viewport to the right.
    • Can also use the arrow keys instead of h/j/k/l
  • Ctrl-w = tells Vim to resize viewports to be of equal size.
  • Ctrl-w - reduce active viewport by one line.
  • Ctrl-w 10- reduce active viewport by ten lines.
  • Ctrl-w + increase active viewport by one line.
  • Ctrl-w 10+ increase active viewport by ten lines.
  • Ctrl-w q will close the active window.
  • Ctrl-w r will rotate windows to the right.
  • Ctrl-w R will rotate windows to the left.


Full article

Run bash in a viewport, with this plugin (easy installation).

Dedupe lines in place

in vim, select a list of values with shift-V (visual mode), and then type :sort u to sort them and remove duplicates.

Toggle comments in vi

Add a comment for one line only:
&

Vim features


  • Auto-complete (for Perl files): start typing, then press Ctrl-Shift-P

Vim navigation

1. Vim Line Navigation
Following are the four navigation that can be done line by line.
  • k – navigate upwards
  • j – navigate downwards
  • l – navigate right side
  • h – navigate left side
By using the repeat factor in VIM we can do this operation for N times. For example, when you want to
go down by 10 lines, then type “10j”.

Within a line if you want to navigate to different position, you have 4 other options.
  • 0 – go to the starting of the current line.
  • ^ – go to the first non blank character of the line.
  • $ – go to the end of the current line.
  • g_ – go to the last non blank character of the line.

2. Vim Screen Navigation

Following are the three navigation which can be done in relation to text shown in the screen.
  • H – Go to the first line of current screen.
  • M – Go to the middle line of current screen.
  • L – Go to the last line of current screen.
  • ctrl+f – Jump forward one full screen.
  • ctrl+b – Jump backwards one full screen
  • ctrl+d – Jump forward (down) a half screen
  • ctrl+u – Jump back (up) one half screen

3. Vim Special Navigation

You may want to do some special navigation inside a file, which are:
  • N% – Go to the Nth percentage line of the file.
  • NG – Go to the Nth line of the file.
  • G – Go to the end of the file.
  • `” – Go to the position where you were in NORMAL MODE while last closing the file.
  • `^ – Go to the position where you were in INSERT MODE while last closing the file.
  • gg – Go to the beginning of the file.

4. Vim Word Navigation

You may want to do several navigation in relation to the words, such as:
  • e – go to the end of the current word.
  • E – go to the end of the current WORD.
  • b – go to the previous (before) word.
  • B – go to the previous (before) WORD.
  • w – go to the next word.
  • W – go to the next WORD.

5. Vim Paragraph Navigation

  • { – Go to the beginning of the current paragraph. By pressing { again and again move to the previous paragraph beginnings.
  • } – Go to the end of the current paragraph. By pressing } again and again move to the next paragraph end, and again.

6. Vim Search Navigation

  • /i – Search for a pattern which will you take you to the next occurrence of it.
  • ?i – Search for a pattern which will you take you to the previous occurrence of it.
  • - Go to the next occurrence of the current word under the cursor.
  • - Go to the previous occurrence of the current word under the cursor.

7. Vim Code Navigation

% – Go to the matching braces, or parenthesis inside code.

8. Vim Navigation from Command Line

Vim +N filename: Go to the Nth line of the file after opening it.
vim +10 /etc/passwd

An easy way to browse the file system is the command:
:Sex
Really!

Perl sub name in vi status line

" Thanks Ovid!
" http://blogs.perl.org/users/ovid/2011/01/show-perl-subname-in-vim-statusline.html


:set laststatus=2


if ! exists("g:did_perl_statusline")
    setlocal statusline+=%(\ %{StatusLineIndexLine()}%)
    setlocal statusline+=%=
    setlocal statusline+=%f\ 
    setlocal statusline+=%P
    let g:did_perl_statusline = 1
endif


if has( 'perl' )
perl << EOP
    use strict;
    sub current_sub {

        my $curwin = $main::curwin;
        my $curbuf = $main::curbuf;


        my @document = map { $curbuf->Get($_) } 0 .. $curbuf->Count;
        my ( $line_number, $column  ) = $curwin->Cursor;


        my $sub_name;
        # for modules, display the current sub name
        for my $i ( reverse ( 1 .. $line_number  -1 ) ) {
            my $line = $document[$i];
            if ( $line =~ /^\s*sub\s+(\w+)\b/ ) {
                $sub_name = $1;
                last;
            }
        }
        # for templates, display the current block starting line
        if (not $sub_name) {
            for my $i ( reverse ( 1 .. $line_number  -1 ) ) {
                my $line = $document[$i];
                # if ($input_state eq 'next_disc_at_station') {
                if ( $line =~ /^}/ ) {
                    # we're below a block
                    last;
                }
                elsif ( $line =~ /^(\S.+{)\s*$/ ) {
                    $sub_name = $1;
                    $sub_name =~ s/'/''/g; #' # escape single quotes for vim function
                    last;
                }
            }
        }
        # TODO:
        # * Reset sub name if we're out of the sub (check for closing bracket: })
        # * Search upwards vertically in the same column for nested blocks
        $sub_name ||= '..';
        VIM::DoCommand "let subName='$line_number: $sub_name'";
    }
EOP


function! StatusLineIndexLine()
  perl current_sub()
  return subName
endfunction
endif

Set an option in vim

:set cmdheight=3
or
:set ch=3

navigation in vim

vi keybindings

Summary:
  • h - move left
  • l - move right
  • j - move down
  • k - move up
  • g, then j or k - move only one screen line (for long lines)
  • w - go forward one word
  • e - go to end of word
  • b - go to beginning of word
  • { - jump up to next blank line
  • } - jump down to next blank line
  • m? - set mark ? (where ? is a lowercase letter a-z)
  • '? - jump to mark ? (where ? is a-z) NOTE: This is a single quote mark followed by a lowercase letter

    My vim config

    Superceded by https://github.com/willsheppard/dotfiles/blob/master/.vimrc

    in ~/.vimrc:

    " TABS
    " make tabs 4 characters wide
    :set tabstop=4
    " make > and < keys shift by 4 characters
    :set shiftwidth=4
    " turn tabs into 4 spaces
    :set expandtab

    " automatically tab to the right place, after pressing enter                     
    :set autoindent

    " COLOURS
    " less bright colours
    :set background=light 
    " set colour of comments
    :highlight Comment ctermfg=Green

    " syncronise syntax highlighting properly
    :syntax on
    autocmd BufEnter * :syntax sync fromstart 
    " highlight terms for which you've searched
    :set hlsearch


    " SCRIPTS
    " allow Shift-K to look up stuff
    ":set keywordprg=/path/to/a/script




    " PLUGINS
    " For Taglist: http://vim-taglist.sourceforge.net/
    " Show name of current subroutine

    map q :TlistShowTag<Enter>
    " Show list of all subroutines

    nnoremap <silent> <tab> :TlistToggle<Enter>




    " Enable code folding for perl subroutines
    :let perl_fold=1
    " don't fold the whole package up, just subroutines (type zazO with cursor on the package name to unfold everything)
    ":set foldlevelstart=1
    " don't fold anything (type za while in a subroutine to fold it up)
    :set foldlevelstart=99




    " EXAMPLE of mapping a keypress to a sequence of other keypresses
    " map CTRL-E to end-of-line (while in insert mode)
    imap <C-e> <esc>$i<right>


    " Also set .vim/ftplugin/perl.vim to display the current Perl subroutine name in the status line



    " save local marks a-z for up to 100 files ('100), save global marks A-Z upon exit (f1)
    set viminfo='100,f1


    " don't clear the screen upon exiting vim
    set t_ti= t_te=

    " load custom filetypes
    :filetype on
    au BufNewFile,BufRead *.tt set filetype=html

    Insert non-printable characters in vi

    • Ctrl-V, then Ctrl-[X]
    Where [X] is A-F

    Have vi detect perl mason .html files

    In ~/.vim/ftdetect/mason.vim:

    " Mason detection
    au BufRead,BufNewFile *
    \   if search('^\s*<%\(args\|once\|init\|perl\|shared\|attr\)>\s*$','n')
    \|    set filetype=mason
    \|  endif
    

    Perl tools

    Perl Needs Better Tools

    IDEs

    • Padre is free, supposedly it knows more about Perl internals than other IDEs.
      • Syntax highlighting: View|Style|Evening
      • Current line highlight colour: Tools|Preferences|Appearance|Editor Current Line Background Colour
    • Eclipse is free but, seems very heavyweight. Extensible with plugins (Version control, etc. See EPIC for Perl)
    • Komodo is paid, but is explicitly designed for Perl. It has a remote debugging feature, which works! You have to install a script on the remote server, and have access to the remote fileystem to display the source code.
    • NetBeans is free
    • IntelliJ IDEA is paid, and has no Perl plugin
    Text editors
    • vim - I use this a lot. It has keyword lookup (if you can configure it), a powerful but difficult-to-use scripting language, and tabs, but no debugging support. Lots of scripts/add-ons available.
    • Emacs - some of my colleagues use it, can be very powerful with add-ons/perl modules
    • UltraEdit
    • Textpad - Windows only. Nice to use, has plugins
    • Sublime - A nice text editor
    Further reading

    • Why should I use an IDE?
    • TODO: [an article on coding horror or somewhere "what would a good IDE look like?"] where is it?

    Make vi recognise different filetypes

    In ~/.vimrc:

    " load custom filetypes
    :filetype on
    au BufNewFile,BufRead *.tt set filetype=html

    Eclipse plugins

    Eclipse 3.5
        • Target Management (Remote file browsing, via SSH): http://www.eclipse.org/dsdp/tm/
          • works great (but sshfs is simpler)
          • Instead of that, see also http://wills-tech-notes.blogspot.com/2010/07/remote-file-browsing.html
        • XSLT: http://www.eclipse.org/webtools/
          • can't download through update manager, it's too slow
          • supposed to offer XML/XSL features, but I can't see any
        • Oxygen XML/XSLT: http://www.oxygenxml.com/download_oxygenxml_editor.html#Eclipse
          • Works. To use step-through debugging,you need to open the 'Debug Scenario' in the XML or XSL menu (it appears when you open an XML or XSL file)
        • vim -- why not use vim editor inside Eclipse? No good solution, apparently (none of these were tested):
          • http://www.viplugin.com/viplugin/ (2009 - costs a few pounds)
          • http://eclim.org/vim/ (recent)
          • http://vrapper.sourceforge.net/ (recent)
          • http://sourceforge.net/projects/vimplugin/ (2007, but states it supports syntax files)
        • Full Screen: http://code.google.com/p/eclipse-fullscreen/ (just works) 
        • P4WSAD: Perforce plugin: http://www.perforce.com/perforce/products/p4wsad.html (had to download zip file from FTP site and install manually, as automatic install URL was too slow)
          • Plugin can be slow to use if you browse the repository directly, but is faster if you check out, then do right-click | Import as project, and use the standard Eclipse Navigator or Project tab to work with the files.