Showing posts with label xVim. Show all posts
Showing posts with label xVim. Show all posts

Monday, April 11, 2011

Making Vim copy all yanked text to the system clipboard

In addition to the usual cut and paste operations found in most other editors, Vim has a 'yank' command that can be followed by a motion operator.

So you can type yw to copy a word to the clipboard, or y3w to copy three words, or yip to copy the current paragraph to the clipboard, and so on.

Which is useful. But by default the text copied by the yank command is only accessible from within that same instance of Vim.

So if you've opened another instance of Vim in a new window[1] and you want to paste the text into that, or you want to paste it into another program, you can't.

An IMO problematic solution is to set 'unnamed' in the 'clipboard' option in your .vimrc / _vimrc, like so

set clipboard+=unnamed

this works but it has a downside - it also means all deleted text gets sent to the system clipboard.

Most of the time I delete text because I just want to get rid of it. When I tried setting this option I kept overwriting the clipboard contents (that I did want) with the deleted text that I didn't want.

And if you do actually want to delete text _and_ copy it to the clipboard you can use a cut command - i.e. C-x. So set clipboard+=unnamed doesn't seem like a good idea.

Here's a better solution, that just ensures yanked text is copied to the system clipboard. Just add the following line to your .vimrc / _vimrc:

nnoremap y "+y

The "+ tells Vim to yank into the + register, which is the system register.




[1] I know many people like to work within one Vim instance and use splits/buffers and tabs to arrange their files, and may want to suggest this as an alternative, but I find it very useful to work with multiple Vim instances. It's a long story, but I like to be able to spatially arrange the (OS)windows in a certain way that reflects the relationship between the files in them, and you can't achieve what I want with a single Vim instance.

Monday, February 22, 2010

My Vim setup

[updated: 02.03.14; 11.4.10; 23.2.10; 17.1.10; 29.8.09; 31.8.09]
vimrc
(UNIX/Mac: ~/.vimrc; Windows: $VIM/_vimrc)

" vim:fo-=a


set nocompatible


"== pathogen
call pathogen#runtime_append_all_bundles() 


filetype plugin indent on 



set autowriteall   " auto save the file on things like :next

set switchbuf=usetab,newtab


" Make shift-insert work like in Xterm
map  
map!  

if version >= 500

  " highlight strings inside C comments
  let c_comment_strings=1

  " Switch on syntax highlighting if it wasn't on yet.
  if !exists("syntax_on")
    syntax on
  endif

  " Switch on search pattern highlighting.
  set hlsearch

endif



set shiftwidth=4
set softtabstop=4
set expandtab

set linebreak      " dont linebreak inside words
set mousehide    " hide the mouse when typing text
set splitbelow


"== search related
set ignorecase smartcase
set incsearch
function! NoHLSearch(pat)
   call search(a:pat)
   set nohls
   set hls
endfunction
" command -nargs=1 S :call NoHLSearch()
" F5 - toggle highlight search
map  :set hls!set hls?


" unicode - for hars pasted from web-pages, PDFs etc (see usr_45.txt)
set encoding=utf-8


" ** actualyl these sould be defined in vimrc and called in there to set
" the default that is set when vim is run.
function! NormalWritingModeLinesAndLinespace()
    set lines=36
    set linespace=4
endfunction

function! DraftingWritingModeLinesAndLinespace()
    set lines=21
    set linespace=13
endfunction


"== syntax/display
set columns=75
" set lines=38
" now setting it to less as i've increased linespace
" set lines=32
" set linespace=5
call NormalWritingModeLinesAndLinespace()
set ch=2  " Make command line two lines high
set laststatus=2   " so last remaining window always has a statusline
" make closed folds less visually prominent
highlight Folded guifg=LightBlue
function! MyFoldText()
    let leadingSpaces = "                                                                   "
    return leadingSpaces . "\\" . (v:foldend - v:foldstart)
endfunction
set foldtext=MyFoldText()
" note that the following has a backslash followed by one space
set fillchars=fold:\ 
highlight statusline guibg=LightGray guifg=DarkGray gui=none
set statusline=
set statusline+=%{getline(search(\"^[:#]\",\ \"bnW\"))}   " show curr heading
set statusline+=%=                                     " show rest right justified.
set statusline+=\ \ %c\,\ %l\ (%L)                     " col, line (tot lines)
highlight CursorLine guibg=#D9D9D9
"colorscheme morning
"set background=light " dark   " for solarized
if has("gui_macvim")
    colorscheme solarized
else
    colorscheme morning
endif



set backup          " turn on backup
set backupdir=/Temp/vimFileBackups    " dir for tilde files
set dir=/Temp/vimSwapFiles     " dir for swap files 
" mustn't have trailing slash. otherwise subsequent additions wont work 
set path+=~/Notes
set path+=~/PhD


set autoindent


set browsedir=current       " open file browser in current dir 

set selectmode=key



"== snipmate options
let g:snips_author = "James Cole" 


"== taglist options
let g:Tlist_Auto_Open=1
set updatetime=100
let Tlist_WinWidth = 40
let tlist_text_settings  = 'text;h:headings'
nnoremap   :TlistToggle
" To not display the Vim fold column in the taglist window
let g:Tlist_Enable_Fold_Column = 0
" only show contents of the current file in current tab
let g:Tlist_Show_One_File = 1

" weird, my computer crashed and after restarting it would no longer 
" generate the tags. it'd say 
" Taglist: Failed to generate tags for /my/path/to/file
"   ctags: illegal option -- -^@usage: ctags [-BFadtuwvx] [-f tagsfile] file ...
" Taglist FAQ says this is coz its not using the exuberant ctags file.
" if i type ctags in shell it gets exuberant one...
" but anyway i recently installed oh-my-zsh, which might be somehow the 
" problem.  setting the following var fixes the prob
" This seems to be about this problem (though I didn't it all):
" http://vim.1045645.n5.nabble.com/MacVim-and-PATH-td3388705.html
let Tlist_Ctags_Cmd = '/usr/local/bin/ctags'



" assume it gets a valid filename and path 
function! GetMarkdownHtmlFilename()
    let b:htmlFileNameForMarkdownDoc = expand('%:t:r') . ".html"
    let dialogPrompt = "Name and location for HTML file"
    let b:htmlFileNameForMarkdownDoc = 
        \ inputdialog( dialogPrompt, expand('%:p:h') .  "/" .  b:htmlFileNameForMarkdownDoc) 
    let menuTypeAndLoc = "amenu 900.107 "
    let menuItemName = "&Personal.A&uto\\-generate\\ HTML\\ on\\ save"
    let menuCall = ":silent call GetMarkdownHtmlFilename()"
    let menuDef = menuTypeAndLoc . menuItemName . menuCall
    execute(menuDef)
endfunction

" let markdownUtilName = "multimarkdown"
let markdownUtilName = "peg-markdown"
function! SaveFile()
    w
    TlistUpdate
    if exists("b:htmlFileNameForMarkdownDoc")
        execute("!" . g:markdownUtilName . " % > " . b:htmlFileNameForMarkdownDoc)
    endif
endfunction

nnoremap   :silent call SaveFile()
inoremap   :silent call SaveFile()
vnoremap   :silent call SaveFile()gv


"== tabbar options
let g:tagbar_expand = 1
let g:tagbar_updateonsave_maxlines = 7000



"== scrolling 
imap  
set sidescroll=1   " smooth horizontal scrolling - 1 char at a time
set scrolloff=1


"== cut and paste
" set clipboard+=unnamed    " copy yanks and deletions to system clipboard 
" send all yanked text to the system clipboard
nnoremap y "+y
" a 'cut' operator that can be used with text-objects, where cut text
" is placed on the system clipboard.
nmap \u "+d


" F4 - show list of headings in document
map  :g/^:/

" F6 - change all the non-displayed chars to plain-text equivs
"    (note how have to escape pipes between commands, and
"     double escape pipes within replace commands)
map  :%s/—/--/ge \| %s/…/.../ge  \| %s/“\\|”/"/ge  \|  %s/‘\\|’/'/ge


" F7 - to condense selected lines
" very quick a dirty way to do it, should put all the words in a datastructure
" and handle words and their variants ending with s better
map   :s/\/\&/ge  \| '<,'>s/\/tt/ge \| '<,'>s/\/b\/ween/ge \| '<,'>s/\/w\//ge \| '<,'>s/\/info/ge \| '<,'>s/\/compu/ge \| '<,'>s/\/r/ge \| '<,'>s/\/pic/ge \| '<,'>s/\/2/ge \| '<,'>s/\/in2/ge \| '<,'>s/\/b/ge \| '<,'>s/\/defn'd/ge \| '<,'>s/\/4/ge \| '<,'>s/\/Howevr/ge \| '<,'>s/\/defn /ge \| '<,'>s/\/partic/ge \| '<,'>s/\/thng/ge \| '<,'>s/\/thngs/ge \| '<,'>s/\/whch/ge \| '<,'>s/\/prt/ge \| '<,'>s/\/arg/ge \| '<,'>s/\/u/ge\| '<,'>s/\/wnt/ge \| '<,'>s/\/othr/ge \| '<,'>s/\/corresp/ge \| '<,'>s/\/4/ge\| '<,'>s/\/reps/ge \| '<,'>s/\/abve/ge \| '<,'>s/\/char/ge \| '<,'>s/\/chars/ge \| '<,'>s/\/req'd/ge \| '<,'>s/\/undef'd/ge \| '<,'>s/\/replacemnt/ge \| '<,'>s/\/dest/ge \| '<,'>s/\/src/ge \| '<,'>s/\/ure/ge \| '<,'>s/\/langs/ge \| '<,'>s/\/frm/ge \| '<,'>s/\/orig/ge \| '<,'>s/\/abt/ge \| '<,'>s/\/prop/ge \| '<,'>s/\/attrib/ge \| '<,'>s/\/qu/ge \| '<,'>s/\/diff/ge \| '<,'>s/\/philos/ge \| '<,'>s/\/impl/ge \| '<,'>s/\/req'd/ge \| '<,'>s/\/elems/ge \| '<,'>s/\/elem/ge


" insert '.x' at the start of the line - i've got syntax highlighting so
" that this line is 'crossed off' (as a plain text equiv so strikethrough)
" i use it for my planning docs and the 'to do' sorts of items in it
map  I.x 


" pump out lines below the cursor 
" orig ver: nnoremap  ok
" newer ver that supports counts - see http://vim.wikia.com/wiki/Mapping_keys_in_Vim_-_Tutorial_(Part_2)
" nnoremap  @='ok'


" execute the selected lines on the ex-line 
" e.g. if those lines contain a function you're coding, or a map
" so you don't have to copy those lines then type ':@"' 
vnoremap x "xy:@x





" note that we may have already deleted some of the files created today..... 
"   e.g. the files from today left might be 
"          100423.txt
"          100423--3.txt
"          100423--4.txt
" and we don't really want to just find the first available sequence num....
" but actually the first one after the current greatest sequence num
function! SaveNewPhdFile()    
    let today = strftime("%y%m%d") 
    let newFileName = today
    let theFileNames = glob(newFileName . "*.txt")
    let suffixes = []
    for fileName in split(theFileNames, "\n")
        let res = matchlist(fileName, "--\\(\\d\\+\\)")
        if res != []
            call add(suffixes, res[1]) 
        " assume it is the unsuffixed file for this date
        else 
            call add(suffixes, 1)        
        endif
    endfor
    " note: max rets 0 on an empty list, which will be case when none of the files had suffixes
    let suffix = max(suffixes) + 1  
    if (suffix > 1)
        let newFileName = newFileName . "--" . suffix . ".txt"
        " ^ for some reason += isnt working  ??
    else
        let newFileName = newFileName . ".txt"
    endif
    exec "w " . newFileName
endfunction

command CreatePhdDocument :call SaveNewPhdFile()

" improvement: hmm, i think i could exec both of these in the one command... and
" whatever is used to separate two commands.. like an ampersand i
" think...thatd guarntee that one only happens after the other and that
" only a single window is used.
function! AddFileToGit()
    exec "silent !git add " . expand("%:p")
    exec "silent !git commit " . expand("%:p") . " -m 'added'"
endfunction
command AddFileToGit :call AddFileToGit()



" @nextAvailable - if '1' attempt to delete the next block of whitespace lines
"   in the given direction, not just any immediately above current line
function! DeleteBlankLinesAboveOrBelow(direction, nextAvailable)
    let currLineNum = getpos(".")[1]
    if (a:nextAvailable == 1)
        let currLineNum = GetNextWhiteSpaceLine(currLineNum, a:direction)
    else
        let currLineNum = Next(currLineNum, a:direction)
    endif
    while (WithinDocument(currLineNum))
        if getline(currLineNum) =~ "^\\s*$"
            exec currLineNum . "delete"
            " note that if we're deleting lines below (direction == 0)
            " then the line numbers below will be one less each time we
            " delete a line
            if (a:direction == 1)
                let currLineNum = Next(currLineNum, a:direction)
            endif
        else
            break
        endif
    endwhile
endfunction

    "  ^ the problem i was having was coz i wasnt reading the documentation of
    "   delete closely enough. i thought you put the line number (or rather,
    "   range) /after/ the delete text. 
    

" the maps stand for 'delete blanks above/below' 
nmap  dba :call DeleteBlankLinesAboveOrBelow(1, 0)
nmap  dbA :call DeleteBlankLinesAboveOrBelow(1, 1)
nmap  dbb :call DeleteBlankLinesAboveOrBelow(0, 0)
nmap  dbB :call DeleteBlankLinesAboveOrBelow(0, 1)

" ^ hmm, if you have these maps as 
"       dsa     (delete space above, etc etc)
"       dsA
"       dsb
"       dsB
"   then for some unknonw reason when you 
"   type 'dd' it pauses before doing it, as if you could be typing 
"   some other thing after it - but none of these start with 'dd' ??
"   but then why can surround.vim not have this effect??


    " @direction:  1 - up, 0 - down
    function! Next(item, direction)
        if (a:direction == 1)
            return a:item - 1
        else
            return a:item + 1
        endif
    endfunction


    function! WithinDocument(lineNum)
        return a:lineNum >= 1 && a:lineNum <= getpos("$")[1]
    endfunction


    function! GetNextWhiteSpaceLine(currLineNum, direction)
        " cases (just in the upwards direction)
        "     - 1. next line above *is* whitespace
        "     - 2. next line above isnt whitespace
        "         - 2.1 whitespace line is N lines above
        "         - 2.2 there are *no* lines of whitespace above
        " 
        "     - 1 & 2 r both handled coz it is passed the line the cursor was
        "       on when deletion command was called, and it just starts looking
        "       from that line 
        "     - the code in general handles 2.1
        "     - the uses of WithinDocument handle 2.2
        let newLineNum = Next(a:currLineNum, a:direction) 
        while ( getline(newLineNum) !~ "^\\s*$" && WithinDocument(newLineNum) )
            let newLineNum = Next(newLineNum, a:direction)
        endwhile
        if !WithinDocument(newLineNum)
            return a:currLineNum
        else
            return newLineNum
        endif
    endfunction
     " *** should really put the regex for whitespace lines into a var!
    " testing map  :echo(GetNextWhiteSpaceLine(getpos(".")[1], 1))


function! FormatXml()
   % !xmllint.exe % --format
endfunction
command FormatXml :call FormatXml()



function! SOnPlural(num)
    if a:num == 1 || a:num == -1
        return ""
    else
        return "s"
endfunction


cd ~/PhD/working/2013/

" show the 'cued-up' keys as you type them, eg as you type 3d
set showcmd

" Highlight from start of fileEdit
" most accurate but slowest 
" see http://vim.wikia.com/wiki/Fix_syntax_highlighting 
" autocmd BufEnter * :syntax sync fromstart

set textwidth=9000
set formatoptions-=a

autocmd FileType text set textwidth=75
" auto-format as you insert text
autocmd FileType text set formatoptions+=a
" With this, a linebreak means a new para, unless trailing whitespace at 
" end of line.  It means that the 'a' option doesn't auto join lines 
" separated by a linebreak.
autocmd FileType text set formatoptions+=w

set hidden
set switchbuf=useopen,usetab

set tabpagemax=35

let g:gitgutter_enabled = 0

set foldmethod=manual


gvimrc
(UNIX/Mac: ~/.gvimrc; Windows: $VIM/_gvimrc)
" vim:fo-=a if has("win16") || has("win32") || has("win64")|| has("win95") " get normal ALT-SPACE behavior map :simalt ~ set gfn=Lucida_Sans_Typewriter:h18:cANSI elseif has("gui_macvim") set gfn=Menlo:h15 endif set cursorline " highlight line cursor is on set guioptions-=T " no toolbar " must be set in vimrc rather than vimrc - they're values are reset when " gvim starts set vb t_vb= function! SubsituteTildeForHomeDir(path) " " want the trailing slash to avoid case of a file in " parent of homedir starting with homedir's name " e.g. if homedir is /users/James " if there was a file called /users/JamesNotex.txt " let homeDir = expand("~") . "/" let newPath = substitute(a:path, "^" . homeDir, "~/", "") return newPath endfunction " sets window title that shows, in this order, these details: " - for unnamed files " - '[No Name]' " - a '+' if buffer has been modified " - current working directory " - vim server instance name " - for named files " - filename " - a '+' if buffer has been modified " - path " - if we're currently auto-generating HTML for this markup, " indicate name+path of that file " - vim server instance name " in any paths, a tilde is substituted for the home directory " function! JamesTitleString() " get list of nums of the buffers assoc'd w/ each window in curr tab page. let l:bufnrlist = tabpagebuflist() let fileNameAndPath = bufname(l:bufnrlist[tabpagewinnr(tabpagenr()) - 1]) " show only the filename (get rid of all the path details) let fileName = substitute(fileNameAndPath, ".*/", "", "") " 'escape' ampersands, so they 1) aren't hidden " & 2) make character following them underlined let fileName = substitute(fileName, "&", "&&", "g") if fileNameAndPath == "" let title = "[No Name]" else let title = fileName endif " Add '+' if the current buffer in the tab page is modified if getbufvar(l:bufnrlist[tabpagewinnr(tabpagenr()) - 1], "&modified") let title = title . ' +' endif if fileNameAndPath == "" let title = title . " (CWD: " . SubsituteTildeForHomeDir(getcwd()) . ")" endif if fileNameAndPath != "" let title = title . " (" let title = title . SubsituteTildeForHomeDir(expand("%:h")) let title = title . ")" endif " if we're currently auto-generating HTML for this markup, indicate name+path of that file if exists("b:htmlFileNameForMarkdownDoc") let title = title . " [->" . b:htmlFileNameForMarkdownDoc . "]" endif let title = title . " - " . v:servername return title endfunction set title set titlestring=%{JamesTitleString()} " max size of titlestring set titlelen=100 function! JamesTabLabel() let label = '' let bufnrlist = tabpagebuflist(v:lnum) " Add '+' if one of the buffers in the tab page is modified for bufnr in bufnrlist if getbufvar(bufnr, "&modified") let label = '+' break endif endfor " Append the number of windows in the tab page if more than one " let wincount = tabpagewinnr(v:lnum, '$') " if wincount > 1 " let label .= wincount " endif " if label != '' " let label .= ' ' " endif " ^ commented out because it includes taglist window in count " an enhancement would be to filter it out let fileName = bufname(bufnrlist[tabpagewinnr(v:lnum) - 1]) " show only the filename (get rid of all the path details) let fileName = substitute(fileName, ".*/", "", "") " 'escape' ampersands, so they 1) aren't hidden " & 2) make character following them underlined let fileName = substitute(fileName, "&", "&&", "g") " don't show '.txt' extensions let fileName = substitute(fileName, "\\.txt$", "", "") let label = label . fileName return label endfunction set guitablabel=%{JamesTabLabel()} function! OpenMyFiles() " note that for filepaths, must use forwards-slashes let notesDir = "~/Notes" let phdWorkingDir = "~/PhD/working" let dropBoxDir = "~/Dropbox" let fileList = [ \ notesDir . "/2014-plan.txt", \ notesDir . "/2014-days.txt", \ dropBoxDir . "/Apps/PlainText\\ 2/plan.txt", \ notesDir . "/vim.txt", \ notesDir . "/biograph.txt", \ notesDir . "/food&drinks.txt", \ notesDir . "/artsRelated.txt", \ phdWorkingDir . "/phdNotesInclSources.txt", \ notesDir . "/projectsToWorkOn.txt", \ notesDir . "/doAndGet-ideas.txt", \ notesDir . "/media-ideas.txt", \ notesDir . "/presents-ideas.txt" \ ] " \ notesDir . "/compu.txt", " \ notesDir . "/aiya,univData.txt", " \ notesDir . "/thinking&Knowl.txt", " \ notesDir . "/writing.txt", " \ notesDir . "/postQueue.txt", " \ notesDir . "/otherIdeas.txt", " \ notesDir . "/I-F&Games.txt", for fileName in fileList exec "e " . fileName exec "tabe" endfor exec "tabc" exec "tabdo :TlistToggle" " now, put the focus on the days file exec "normal! 2gt" set columns=135 endfunction " dev notes: " originally I didnt have the command there to join the lines, and it " didnt work properly. the reason was that you can't call exec like that " when there are a range of lines specified on the command line, as there " will be because there is a selection - and that sucks. the only " reasonable option would be if i could just put the 's' command there " without putting it as an arg to the exec...which i tried but it didnt " seem to work. if you use the substitute function, it only works on a " per-line basis, which'd be a pain. " could ask vim-use if there's a better way to do this. function! ConvertStringToFileName() normal! gv normal! J exec "s#\\<\\l#\\u&#ge" normal! gv exec "s/ //ge" exec "s/:/-/ge" endfunction " kinda silly way to impl this - I dont know how to define it as a string " and just insert that string. dont know how to encode the linebreaks. but " it works. function! InsertNotesFileFields() let oldFo = &fo set fo-=a normal! O normal! otitle= normal! oauthor= normal! otype= normal! oyear= normal! otopics= normal! oread= normal! o normal! o normal! o---------- normal! o let &fo = oldFo endfunction " requires the input text to be visual selection function! CleanTranslinkResult() let stringsToRemove = "Take Bus\\|\\t\\|(.\\{-})\\|daily timetable\\|trip timetable\\|Departing\\|Arriving\\|Zones travelled in:.*$\\|Fares for this journey.*$\\|Fare included in the next trip.*$" normal! gv exec "'<,'>s/" . stringsToRemove . "//ge" endfunction function! WrapAllLines() let oldTw = &tw let &tw = 9000 normal! gg normal! gqG let &tw = oldTw endfunction function! CloseTlistAndSetColumns() TlistClose set columns=76 endfunction function! GetLevel(theLine) if a:theLine =~ "^:" return 0 else return 1 endif endfunction function! FoldOnColonHeadings() setlocal foldmethod=expr " Make all the text within each section a fold " note that you dont call that func you just spec the func name setlocal setlocal foldexpr=GetLevel(getline(v:lnum)) " set columns=77 " setlocal foldcolumn=2 normal! zR endfunction "== menus function! OpenMyFiles_MenuItem() call OpenMyFiles() amenu disable &Personal.&Open\ Standard\ Files endfunction amenu 900.100 &Personal.&Open\ Standard\ Files :silent call OpenMyFiles_MenuItem() amenu 900.105 &Personal.C&lose\ Tlist\ and\ Set\ Columns :silent call CloseTlistAndSetColumns() amenu 900.107 &Personal.A&uto\-generate\ HTML\ on\ save :silent call GetMarkdownHtmlFilename() amenu 900.109 &Personal.Toggle\ GitGutter :GitGutterToggle amenu 900.110 &Personal.&Format\ XML :silent call FormatXml() amenu 900.120 &Personal.&Convert\ String\ To\ File\ Name :silent call ConvertStringToFileName() amenu 900.140 &Personal.Clean\ &Translink\ Result :silent call CleanTranslinkResult() amenu 900.150 &Personal.&Insert\ Notes\ File\ Fields :silent call InsertNotesFileFields() amenu 900.160 &Personal.&Wrap\ All\ Lines :silent call WrapAllLines() " eventually i want to put ticks next to the selected ones ✓ amenu 900.170 &Personal.W&riting\ Mode.&Normal :silent call NormalWritingModeLinesAndLinespace() amenu 900.180 &Personal.W&riting\ Mode.&Drafting :silent call DraftingWritingModeLinesAndLinespace() colorscheme solarized set background=light " for solarized " its set to dark in vimrc, as light is unreadable in terminal " make the highlighting of search terms less prominent " this is a lighter shade of brown " highlight Search guifg=#cbac4c highlight Search guifg=#dac47f


Autocommand for setting filetype of .txt files
(UNIX/MAC: ~/.vim/bundle/myadditions/ftdetect/txt.vim; Windows: $VIM/vimfiles/bundle/myadditions/ftdetect/txt.vim)
au BufNewFile,BufRead *.txt setf txt


$HOME/ctags.cnf (unix/mac: $HOME/.ctags. ctags website).
--langdef=txt
--langmap=txt:.txt
--txt-kinds=+h
--regex-txt=/^(:.*)$/\1/h,headings/

($HOME is an environment variable ctags uses; that's where it looks for the configuration file - I've set mine to same dir as $VIM)


$VIM/vimfiles/syntax/txt.vim
syntax match lvl1Heading /^:[^:].*$/
syntax match lvl2Heading /^::[^:].*$/
syntax match lvl3Heading /^:::[^:].*$/
syntax match lvl4Heading /^::::[^:].*$/
syntax match lvl5Heading /^:::::.*$/

highlight lvl1Heading guifg=#0000FF
highlight lvl2Heading guifg=#0075FF
highlight lvl3Heading guifg=#0095FF
highlight lvl4Heading guifg=#60B9FF
highlight lvl5Heading guifg=#90DCFF


syntax match crossedOutLine /^\s*\.x.*$/
highlight crossedOutLine guifg=#AAAAAA



Add-on scripts
  • matchit
  • three related ones by Tim Pope
  • snipMate - TextMate-style snippets for Vim
    • though i haven't used this one much yet
  • taglist
    • for this i've installed ctags, and put it in my PATH environment variable (in my case in c:\programs\ctags58)
    • to get it to work properly with tabs (the 'tabs' for selecting different files, not the 'tabs' for indenting) apply the following patch
      --- plugin/taglist.vim 2008-08-13 19:04:48 +0000
      +++ plugin/taglist.vim 2008-08-27 19:24:49 +0000
      @@ -4097,6 +4097,12 @@
      " window. Used after entering a tab. If this is not done, then the folds
      " are not properly created for taglist windows displayed in multiple
      tabs.
      function! s:Tlist_Refresh_Folds()
      +
      + " Not needed when one file is displayed.
      + if g:Tlist_Show_One_File
      + return
      + endif
      +
      let winnum = bufwinnr(g:TagList_title)
      if winnum == -1
      return
  • renamer - rename multiple files by editing a text document
    • Allows you to use the familiar editing techniques like regexs and using visual-block mode to rename multiple files, and also not have to deal with the escaping you have to do with a shell
    • I came across this in a discussion thread about the editor-agnostic massren util, which allows you to do a similar thing. I ended up using renamer as I couldn't get massren running properly on my system.



How I've dealt with Vim's temp files

Details here.

Saturday, January 02, 2010

The iPhone analogue of Vim-like editing?

What'd b the iPhone/touchscreen analogue of Vim-like editing?  

The most obvious thing would b to have modes.

This might not seem that useful. After all a lot of the benefit of having modes is being able to explicitly specify positions in the text or blocks of text, such as 'the end of this sentence' or 'this paragraph', whih is less of a benefit with a touchscreen coz u can directly point at and select things.  

Still I wouldn't be surprised if it turned out to b easier to specify certain text positions/ranges in a vim-like way.

Another benefit of modal editing is dealing with structure such as markup or code.  

Coz the iPhone has a virtual keyboard it could have different virtual keyboards for each mode. At least it'd be interesting to see if this made things better.
   
You could poss also use gestures (or maybe even phone movements) to specify certain commands. 

And I wonder if such an editor could help w/ coding on phone ala Y-Combinator's RFS 5: Development on Handhelds.  

Sunday, August 09, 2009

The internet is good for Vim

I think Vim is a great text editor and one that's well worth learning. But it's certainly a bit of effort to learn all the commands and get used to working in different modes. A lot of people seem to be put off by that initial frustration.

You're editing a file and there'll be something, often fairly simple, that you want to do but don't know how. And while the Vim help is quite good it can be hard to find info on the specific thing you want to do, so it’s easy to get stuck. At least that was the situation 10-15 years ago. But these days you can just put details of what you’re trying to do into Google and you’ll likely get a good answer. And the net contains a number of Vim cheatsheets.

Of all the editors, Vim probably has the largest initial hump to get over before getting to proficiency, but also one of the largest payoffs for doing so, and the internet is making it a lot easier to get over that hump. And for that reason we might see a resurgence in its use.

Monday, October 27, 2008

How to get rid of Vim's temp files

The default behavior in Vim when you save a file is to also put temporary files in the save directory. I'll explain how you can stop it from doing this. (I don't know Vim that well, but the following works).

What happens is that if you save a file called 'weeklyReport.txt' it also stores a temporary file with the same name appended with a tilde 'weeklyReport.txt~'. It also stores a swapfile there.

I found this really annoying, as it makes it awkward to scan the list of files in the directory (and the files were getting into my version control system - and yes, I'm sure I could find a way to avoid them getting in there, but I think the better solution is to not have them in the directory in the first place).

Here's a solution I found (I'm using it on Windows, but the only difference on other systems should be the file system syntax for specifying directories).

Open or create your settings file.

Here's some deails if you're not familiar with doing this.

When you install Vim, you've effectively installed two programs: Vim (the terminal version), and gVim (the GUI version), and each has its own settings file. For Vim, it's <VimDirectory>/_vimrc. For gVim it's <VimDirectory>/_gvimrc.

A note on what I mean by <VimDirectory>: the actual exectuable files are stored in a directory containing the vim version number - on my computer it is C:\Program Files\Vim\vim72. This is not the <VimDirectory> I'm referring to - the one I'm referring to is the parent directory of that, in my case C:\Program Files\Vim
Add the following lines to it (it shouldn't matter where):
" turn on backup
set backup

" Set where to store backups
set backupdir=c:\temp

" Set where to store swap files
set dir=c:\temp
This will store the tilde and swap files in c:\temp - you can change the directory location to wherever you want.



I found this soultion here, via this, and that via a google search.