Rcjp's Weblog


.nexrc for use with nvi

" tabs etc. use  :se sw=1  for common lisp stuff tho
set wraplen=80
set shiftwidth=4
"set tabstop=4
set tabstop=81
set autoindent
set showmode
set showmatch
set nowrapscan
" 10ths of second to wait for susequent key mapping
set keytime=3

" Ignore the case when searching
set ignorecase
set searchincr

" All regexp are like egrep and case insensitive (unless uppercase used)
set extended
set iclower

" if you've just pasted a pathname etc. Ctrl-w will erase nicely
set altwerase

" no flashing or beep .e.g when a non matching ) is inserted
set noerrorbells
set noflash

" write out the file before :n or ! commands
set autowrite

" jump past any initial comment, header
set comment

" show filename in xterm
set windowname

" do filename expansion on colon line with <tab>
" input the following line as 'set filec=<Ctrl-v><tab>'
set filec=\

" edit the colon command history by pressing esc initially
set cedit=^[

"======== Abreviations =======
ab thedate ^M^[:.!date +\%D^MkJA
ab thetime ^M^[:.!date +\%X^MkJA
ab teh the
ab adn and

"========== Mappings =========
" movement
map g :0^M
map! jj ^[
map , :n^M

" spell
map S :w^M:!aspell -c %^M:e!^M^M

" center/right align
map =c 080i ^[$78hd0:s/  / /g^M
map =r 080i ^[$78hd0

" reformat paragraph, email, C code
" map == j{!}fmt -w 80 -u^M}
" rst-fmt knows about bullet points/title etc.
map == j{!}rst-fmt^M}
map =e j{!}fmt -u -p '>'^M}
map =c 1G!Gindent -nut -kr ^M

" join paragraph together (for pasting into other things)
map =j :.,/^$/-1j^M

" reformat lisp (CAUTION! - fails with #., deletes comments etc. and messes up loop)
map -- j{!}sbcl --noinform --no-userinit --no-sysinit --noprint --disable-debugger --eval '(setf *print-case* :downcase)' --eval '(pprint(read))' --eval '(quit)'^M}

" tabs are annoying kill them, kill them all!
map =4 ma1G!Gexpand -t4^M'a
map =8 ma1G!Gexpand -t8^M'a

" wrap word in speech marks, quotes
map ^Ws lBi"^[Ea"^[
map ^Wq lBi'^[Ea'^[

" open line below but stay in command mode
map ^O o^[

" i always seem to be pasting code (ctrl-c on a new line to exit)
map ^K :i!^M
map! ^K ^[:i!^M

" comment/uncomment C code
map ^X ^i/* ^[A */^[^+
map ^Y :s#/\* (.*) \*/$#\1^M+

" great 'insert previous partial word' macro
map! ^P ^[a. ^[hbmmi?\<^[2h"zdt.@z^Mywmx`mPwxi

" find lines with titles, subtitles (show line numbers)
" use '' to go back to where you were
map #= :g/^===/-#^M
map #- :g/^---/-#^M


Used with nvi as a keyboard mapping (see == in .nexrc above) to reformat text with some reStructured text elements – e.g. won’t just wrap bulleted list elements into one big paragraph like fmt would.

#!/usr/bin/env python
import string
import re
import sys

BULLET = re.compile(r'^( *)([o\-\*]) (.*)')
TITLE = re.compile(r'^[~=-]+$') # for some reason ~ must go first ???
SOURCE = sys.stdin

def get_lines (maxlen):
    """ Return lines upto maxlen length """
    for line in SOURCE:
        while len(line) > maxlen:
            # backtrack from maxlen to a space
            i = maxlen
            while not line[i].isspace() and i > 0: i-=1
            if i==0 or line[i:].isspace(): break  # couldn't split, just return it
            yield line[:i]
            line = line[i:]
        yield line

def printline (line, indent):
    if BULLET.match(line):
        print line
        print indent+line

def rst_reformat ():
    """Re-format lines respecting reStructured text elements (heading/lists)"""
    maxline = MAXLINE
    prev = ' '
    indent = ''
    bulletchar = ''
    firstline = True
    for line in get_lines(maxline):
        listitem = BULLET.match(line)
        if firstline:
            firstline = False
            if line.isspace():    # include any initial blank line
                print line.rstrip()
        if listitem:
            if not prev.isspace(): printline(prev, indent)
            indent = listitem.group(1) + '  '
            bulletchar = listitem.group(2)
            prev = listitem.group(1)+bulletchar+' '+' '.join(listitem.group(3).split())
        elif TITLE.match(line):             # title
            print prev
            print line.rstrip()
            if line.startswith('='): print  # blank line after main title
            prev = ' '
        elif line.isspace():                # end of paragraph, reset everything
            if not prev.isspace():
                printline(prev, indent)
                prev = ' '
                indent = ''
                maxline = MAXLINE
        elif prev.isspace():                # start of a paragraph
            prev = ' '.join(line.split())
        elif len(prev) < (maxline-len(indent)):
            # format previous line and add words to it
            words = line.split()            # stitch on words till prev line is full
            i = 0
            m = maxline-len(indent)
            while len(prev) < m and i < len(words):
                if (len(prev) + len(words[i]) + 1) >= m:
                    printline(prev, indent)
                    prev = ' '.join(words[i:])
                prev += ' ' + words[i]
                i += 1
            prev = ' '.join(line.split())
    printline(prev, indent)

if len(sys.argv)>1:
    SOURCE = file(sys.argv[1])  # for testing, specify a testfile

colours day.vim

" Vim color file
" based on iyerns' mellow colours

set background=light hi clear if exists("syntax_on")     syntax reset endif let g:colors_name="day"
hi Normal       guifg=black     guibg=#FFFFCC hi Title        guifg=black     guibg=white     gui=BOLD hi lCursor      guifg=NONE      guibg=Cyan hi Cursor       guifg=#ffffff   guibg=#ff0000
hi LineNr       guifg=white     guibg=#666600
hi Comment      guifg=#b0b0b0                   gui=ITALIC hi Operator     term=NONE       cterm=NONE      gui=NONE
hi Identifier   guifg=#663333                   gui=NONE
hi Statement    guifg=black                     gui=BOLD hi TypeDef      guifg=#c000c8                   gui=NONE hi Type         guifg=#0000c8                   gui=NONE hi Boolean      guifg=#0000aa                   gui=NONE
hi String       guifg=#006666   guibg=yellow
hi Number       guifg=#808880                   gui=NONE hi Constant     guifg=#888080                   gui=NONE
hi Function     guifg=#660000   guibg=NONE hi PreProc      guifg=#808040                   gui=NONE
hi Search       guifg=#FFFF00   guibg=#336600   gui=NONE hi IncSearch                    guibg=#CC6600   gui=NONE
hi cIncluded    guifg=#663333   guibg=NONE hi cFormat      guifg=#006666   guibg=yellow hi cSpecial     guifg=#006666   guibg=yellow hi lispString   guifg=#006666   guibg=NONE      gui=ITALIC hi xmlCData     guifg=purple    guibg=NONE


" Todo...
" to get e.g. stio.h or anything from the path do    :find stio.h
" use fuzzyfinder  ,f
" use surround  see   :help surround
"  Old text                  Command     New text ~
"  "Hello *world!"           ds"         Hello world!
"  <div>Yo!*</div>           dst         Yo!
"  [123+4*56]/2              cs])        (123+456)/2
"  "Look ma, I'm *HTML!"     cs"<q>      <q>Look ma, I'm HTML!</q>
"  <div>Yo!*</div>           cst<p>      <p>Yo!</p>
"  if *x>3 {                 ysW(        if ( x>3 ) {
"  Hello w*orld!             ysiw)       Hello (world)!
"  my $str = *whee!;         vlllls'     my $str = 'whee!';
"The letters w, W, and s correspond to a |word|, a |WORD|, and a |sentence|,
" http://www.vim.org/scripts/script.php?script_id=1697
" remember to do   :helptags ~/.vim/doc to regenerate the helptags
"set nowrap
" :se cuc  to show a vertical line thru the cursor   :se nocuc
" indenting (can do  :args *.c   :argdo exe "normal1G=G" | update
" ctr-6  (should be ^ really) to switch between two files (alternate file #< )
" :vim todo *.c
" :vim \<func\> *.h include/*
" : vim myfunc **/*.c
" :gr foo *.c     uses external grep
" if one set of greps leads to another, go back to the old one with :colder
" do :e %%/  to open a file starting from where the current file is
" zE  to undo any folding
" \tt to align latex, \acom comments and \t= on equal,  see =d below
set nocompatible
set nostartofline               " cursor can extend into none-space
set ignorecase                  " set up searching - ignore case, don't highlight or wrap
set nowrapscan
if v:version > 730
    set undofile                    " remember undo between launches
    set undodir=~/.undo
set smartcase                   " don't ignore case if search contains uppercase
"set backspace=indent,eol,start  " allow backspacing over everything in insert mode
set history=100                 " keep some command line history        
set ruler                       " show the cursor position all the time
set showcmd                     " display incomplete commands
set incsearch                   " do incremental searching
set display+=lastline           " for wrapped lines show last line even if it is incomplete
set printoptions=formfeed:y     " obey ^L
set cedit=<Esc>                 " edit the command line with esc
set noerrorbells
set autoread                    " re-read changed files
set showmatch                   " show the matching paren
set hidden                      " its ok to switch buffers without saving, they are just hidden

filetype plugin on filetype indent on " " Keymaps nmap ,w :w!<cr> nmap ,d :bdelete<CR>  nmap ,b :FufBuffer<cr> nmap ,f :FufFile<cr> nmap ,r :FufMruFile<cr> nmap ,l :FufLine<cr> " symlinks don't work right with vim on windows " if we save a .vimrc it stops being a symlink, gave up trying to fix " have to edit the dropbox file directly if (has('win32') || has('win64'))     nmap ,v :e! ~/Dropbox/.vimrc<cr> else     nmap ,v :e! ~/.vimrc<cr> endif imap jj <ESC> nmap ,cd :cd %:p:h<cr> nmap ,n :cn<cr> nmap ,p :cp<cr> " C stuff etc,  do ,m  then ,n or ,p thr errors   :cc to redisplay error map ,m :make %:p:r<cr><cr>:cc<cr> " show quickfix matches in a window e.g. helpgrep cedit then  ,c  ,n etc.   nmap ,c :botright cw 10<cr>    " in insert mode uppercase word after you've typed it map! <C-F> <Esc>gUiw`]a
" Meta doesn't work in terminal tho grrr " D- is apple key nmap <D-k> mz:m-2<cr>`z                 " Move a line of text up/down nmap <D-j> mz:m+<cr>`z vmap <D-j> :m'>+<cr>`<my`>mzgv`yo`z     " same for visual block vmap <D-k> :m'<-2<cr>`>my`<mzgv`yo`z
nmap ,, :bn<cr> " when wrapping long lines - map keys to go to next visible line etc. map <up> gk imap <up> <c-o>gk map <down> gj imap <down> <c-o>gj map <home> g<home> imap <home> <c-o>g<home> map <end> g<end> imap <end> <C-o>g<end>
" " Exploring " nmap ,e :Explore<cr> " preview with  p   then  Ctrl-w H  (capital!) to switch to horizonal panes " finish with Ctrl-w z  to remove the preview window " :vertical resize 20    to change width
" " Colours (to see the current colour scheme do  :echo g:colors_name) " if has("gui_running")     colorscheme mypablo  "    colorscheme custom     set bg=dark           " or can do   light     " a couple of mods for grey comments and light background on strings     hi Comment guifg=#404040     hi String guifg=black guibg=darkyellow     if has('win32')         set guifont=Inconsolata:h14         :winpos 55 2     elseif has('mac')         set guifont=Inconsolata:h20         :winpos 55 23     elseif has('unix')         set guifont=Inconsolata\ Medium\ 14     endif        set lines=49     set columns=110 "    hi MatchParen gui=bold,italic guifg=NONE guibg=NONE     set guioptions-=T     " no toolbar     set nohlsearch     set statusline=%t%h%m%r%=[%b\ 0x%02B]\ \ \ %l,%c%V\ %P "    set statusline=%2*%n\|%<%*%-.40F%2*\|\ %2*%M\ %3*%=%1*\ %1*%2.6l%2*x%1*%1.9(%c%V%)%2*[%1*%P%2*]%1*%2B     " Always show a status line     set laststatus=2     "make the command line 1 line high     set cmdheight=1 else     colorscheme mypablo      hi StatusLine ctermfg=0 ctermbg=7 " otherwise can't see split windows status line     hi MatchParen cterm=bold ctermfg=6 ctermbg=0 guibg=DarkCyan endif syntax on " " indenting " " make into space by  :se ts=4  then :retab " die tabs, die! with expandtab (need to do :retab to make existing tabs expand) " to do the reverses :se noexpandtab then :retab!   (you need the '!') set shiftwidth=4 set cindent        " smarter than smartindent " gnu style set cinoptions={.5s,:.5s,+.5s,t0,g0,^-2,e-2,n-2,p2s,(0,=.5s formatoptions=croql cindent shiftwidth=4 tabstop=8 set softtabstop=4  " means that delete will see 4 spaces as a tab etc set formatoptions=croqln set expandtab   autocmd FileType make setlocal noexpandtab " " C  " "set path =c:/Novell/ndk/nwsdk/include "set path +=c:/Novell/ndk/nwsdk/include/* "set tags=h:/projects/ed/tags,c:/gpas/modules/tags "set backupdir=c:/tmp autocmd FileType c map <buffer> ,<space> :w<cr>:!gcc %<cr> autocmd FileType c setlocal formatoptions=croq  autocmd BufNewFile,BufRead *.c set makeprg=make\ %:r.o  " :make then works for single files " visual select lines of declartions then  =d  to align map =d \adec vmap <silent> == <ESC>:AlignPush<CR>:AlignCtrl lp1P1<CR>:'<,'>Align =<CR>:AlignPop<CR> vmap <silent> =, <ESC>:AlignPush<CR>:AlignCtrl lp0P1<CR>:'<,'>Align ,<CR>:AlignPop<CR> vmap <silent> =( <ESC>:AlignPush<CR>:AlignCtrl lp0P0<CR>:'<,'>Align (<CR>:AlignPop<CR> " split types into separate lines   int a,b;  into   int a;\n int b; vmap =s \a, " " Python " "  start an ipython sesion with  'screen -S ipython ipython' "  C-a ?  to see screen options, also 'screen -list' autocmd FileType python map <buffer> ,<space> :w!<cr>:!python %<cr> autocmd FileType python set makeprg=python\ -c\ \"import\ py_compile,sys;\ sys.stderr=sys.stdout;\ py_compile.compile(r'%')\" autocmd FileType python set efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m autocmd FileType python set cindent autocmd FileType python map ,m :w<CR>:!screen -x ipython -X stuff $'\%cd %:p:h\n\%run %:t\n'<CR><CR> " hide .pyc files in the file browser let g:explHideFiles='^\.,.*\.pyc$'
" " HTML " " optionaly select some lines with Vjjjj etc. then Alt-l to grab htmlized  " Don't pull out css... put it inline oldstyle so we can just paste a snippet let g:html_use_css = 0 func Convert2HTMLClip(line1, line2)     breakadd here     if a:line2 >= a:line1         let g:html_start_line = a:line1         let g:html_end_line = a:line2     else         let g:html_start_line = a:line2         let g:html_end_line = a:line1     endif     runtime syntax/2html.vim     unlet g:html_start_line     unlet g:html_end_line     normal! gg     " Vim7 spits out different HTML... "    exe ":0,/<pre>/- d"     exe ":0,/<body / d" "    normal! I<code>     normal! I<code><pre>     normal! G "    exe ":?</pre>?+,$ d"     exe ":?</body>?,$ d" "    normal! A</code>     normal! A</pre></code>     exe ":%s/'/\\&#39;/eg"     exe ":%s/&amp;#39;/\\&amp;\\&#35;39;/eg"     exe ":%s/&amp;#35;/\\&amp;\\&#35;35;/eg" "    get rid of <br> except when its the only thing on the line     exe ":%s/^<br>/<br><br>/"     exe ":%s/<br>$//"     normal! ggVG"+y     exe ":bd!" endfunc command -range=% TohtmlClip :call Convert2HTMLClip(<line1><line2>) map <D-l> :TohtmlClip<CR> " " Abbreviations " ab #d #define ab #i #include ab teh the
" do :e %%/  to open a file starting from where the current file is cabbr <expr> %% expand('%:p:h')

autocmd BufNewFile,BufRead *.doc  setf text autocmd BufNewFile,BufRead *.txt  setf text autocmd BufNewFile,BufRead *.xhtml,*.xht setf xhtml autocmd BufNewFile,BufRead *.FOR  setf fortran autocmd BufNewFile *.[tex] 0read ~/safe/skeleton.tex autocmd BufNewFile,BufRead *.lisp set lisp "autocmd BufRead,BufNewFile *.lisp syntax off autocmd BufNewFile,BufRead *.kid  :set filetype=html
" ctrl-_ will close the current html tag autocmd Filetype html,xml,xsl source ~/.vim/scripts/closetag.vim
" only indent :public, :private etc by 1 character autocmd FileType cpp setlocal cino=g1 autocmd FileType go map <C-c> :TC //<cr> augroup vimrcEx     autocmd!     autocmd FileType text setlocal textwidth=78          autocmd FileType text setlocal linebreak      autocmd FileType text setlocal wrap     autocmd FileType text setlocal formatoptions=twan12     " goto last known position     autocmd BufReadPost *                 \ if line("'\"") > 0 && line("'\"") <= line("$") |                 \   exe "normal g`\"" |                 \ endif augroup END autocmd BufRead,BufNewFile *.py syntax on  autocmd BufRead,BufNewFile *.py set ai set completeopt=longest,menuone,preview " make omnicomplete sensible :inoremap <expr> <cr> pumvisible() ? "\<c-y>" : "\<c-g>u\<cr>" :inoremap <expr> <c-n> pumvisible() ? "\<lt>c-n>" : "\<lt>c-n>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>" :inoremap <expr> <m-;> pumvisible() ? "\<lt>c-n>" : "\<lt>c-x>\<lt>c-o>\<lt>c-n>\<lt>c-p>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>" " and less bright hi Pmenu      ctermfg=0 ctermbg=2 gui=NONE hi PmenuSel   ctermfg=0 ctermbg=7 gui=NONE hi PmenuSbar  ctermfg=7 ctermbg=0 gui=NONE hi PmenuThumb ctermfg=0 ctermbg=7 gui=NONE

"map -- :%!gofmt<CR> map -- :Fmt<cr>

Leave a Comment »

No comments yet.

RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: