Rcjp’s Weblog

vi

.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


bin/rst-fmt

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

MAXLINE = 80
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
    else:
        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)
                print
                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:])
                    break
                prev += ' ' + words[i]
                i += 1
        else:
            printline(prev,indent)
            prev = ' '.join(line.split())
    printline(prev, indent)

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


.vim/colors/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=#c0c0c0                   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


.vimrc

this is messy and not really tested… and uses other scripts ToggleCommentify

"set nowrap
set nostartofline               " cursor can extend into none-space
set ignorecase                  " set up searching - ignore case, don't highlight or wrap
set smartcase                   " don't ignore case if search contains uppercase
set nohlsearch
set nowrapscan

set backspace=indent,eol,start  " allow backspacing over everything in insert mode
set history=50                  " keep 50 lines of 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 nocompatible
set noerrorbells
set history=400
set autoread                    " re-read changed files
set showmatch
set autoread
set hidden

filetype plugin on
filetype indent on

" Normal maps
nmap ,w :w!<cr>
nmap ,d :bdelete<CR> 
nmap ,f :find<cr>
nmap ,v :e! ~/.vimrc<cr>
imap jj <ESC>
nmap ,cd :cd %:p:h<cr>
nmap ,n :cn<cr>
nmap ,p :cp<cr>
nmap ,c :botright cw 10<cr>   " e.g. helpgrep cedit then  ,c
nmap <c-u> <c-l><c-j>:q<cr>:botright cw 10<cr>

nmap <M-k> mz:m-2<cr>`z                 " Move a line of text up/down
nmap <M-j> mz:m+<cr>`z
vmap <M-j> :m'>+<cr>`<my`>mzgv`yo`z     " same for visual block
vmap <M-k> :m'<-2<cr>`>my`<mzgv`yo`z

map <f5> :explore<cr>
map <f11> :bn<cr>
map <f12> :bp<cr>
map <m-c> :call togglecommentify()<cr>j
imap <m-c> <esc>:call togglecommentify()<cr>j
" 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>


" Colours (to see the current colour scheme do  :echo g:colors_name)

syntax on
if has("gui_running")
    colorscheme day 
    set guifont=Monaco\ 12
    set guicursor=n-i-v:block-Cursor-blinkon0
    set lines=60 columns=102
    set guioptions-=T     " no toolbar
else
    colorscheme pablo 
    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

" indenting (can do  :args *.c   :argdo exe "normal1G=G" | update

set shiftwidth=4
set 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    " die tabs, die! (:retab  to get back)

" 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 
au BufNewFile,BufRead *.c set makeprg=make\ %:r.o  " :make then works for single files

" Python

au FileType python map <buffer> ,<space> :w!<cr>:!python %<cr>
au FileType python set makeprg=python\ -c\ \"import\ py_compile,sys;\ sys.stderr=sys.stdout;\ py_compile.compile(r'%')\"
au FileType python set efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m
au FileType python set cindent

" html

func Convert2HTMLClip(line1, line2)
    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"
    normal! ggVG"+y
    exe ":bd!"
endfunc
command -range=% TohtmlClip :call Convert2HTMLClip(<line1>, <line2>)
map <M-l> :TohtmlClip<CR>

" Abbreviations

ab #d #define
ab #i #include
ab teh the


au BufNewFile,BufRead *.doc  setf text
au BufNewFile,BufRead *.txt  setf text
au BufNewFile,BufRead *.xhtml,*.xht setf xhtml
au BufNewFile,BufRead *.FOR  setf fortran
au BufNewFile *.[tex] 0read ~/safe/skeleton.tex
au BufNewFile,BufRead *.lisp set lisp
au BufRead,BufNewFile *.lisp syntax off

" only indent :public, :private etc by 1 character
autocmd FileType cpp setlocal cino=g1
augroup vimrcEx
    au!
    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

No Comments Yet »

No comments yet.

RSS feed for comments on this post.

Leave a comment

Blog at WordPress.com.