Mercurial > hg > dml-home
changeset 3:19d1235ce229
More stigg.
author | samer |
---|---|
date | Sun, 18 Jan 2015 18:35:47 +0000 |
parents | 3255717f4e6b |
children | b2cd63c14b92 |
files | .hgignore .vim/.netrwhist .vim/bundle/vim-commentary/CONTRIBUTING.markdown .vim/bundle/vim-commentary/README.markdown .vim/bundle/vim-commentary/doc/commentary.txt .vim/bundle/vim-commentary/plugin/commentary.vim .vim/ftplugin/humdrum.vim .vim/indent/prolog.vim .vim/plugin/commentary.vim .vim/plugin/filebrowser.vim .vim/plugin/imaps.vim .vim/syntax/humdrum.vim .vimrc etc/setup_as_dml.sh lib/kern |
diffstat | 15 files changed, 1654 insertions(+), 10 deletions(-) [+] |
line wrap: on
line diff
--- a/.hgignore Sun Jan 18 17:33:25 2015 +0000 +++ b/.hgignore Sun Jan 18 18:35:47 2015 +0000 @@ -14,9 +14,11 @@ .ssh .config .gitconfig +.gitignore .swipl-dir-history lib/charm var/dml/.swipl_history var/dml/storage var/dml/users.db var/log +/.git$
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.vim/.netrwhist Sun Jan 18 18:35:47 2015 +0000 @@ -0,0 +1,7 @@ +let g:netrw_dirhistmax =10 +let g:netrw_dirhist_cnt =5 +let g:netrw_dirhist_1='/usr/local/lib/swipl-7.1.24/library/unicode' +let g:netrw_dirhist_2='/home/dml/lab/dml/config-enabled' +let g:netrw_dirhist_3='/home/dml/.vim' +let g:netrw_dirhist_4='/home/dml/src/hg/dml-cliopatria/cpack/dml/fluid/rc' +let g:netrw_dirhist_5='/home/dml/src/hg/dml-cliopatria/cpack/dml/fluid/sf2'
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.vim/bundle/vim-commentary/CONTRIBUTING.markdown Sun Jan 18 18:35:47 2015 +0000 @@ -0,0 +1,1 @@ +See the [contribution guidelines for pathogen.vim](https://github.com/tpope/vim-pathogen/blob/master/CONTRIBUTING.markdown).
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.vim/bundle/vim-commentary/README.markdown Sun Jan 18 18:35:47 2015 +0000 @@ -0,0 +1,51 @@ +# commentary.vim + +Comment stuff out. Use `gcc` to comment out a line (takes a count), +`gc` to comment out the target of a motion (for example, `gcap` to +comment out a paragraph), `gc` in visual mode to comment out the selection, +and `gc` in operator pending mode to target a comment. You can also use +it as a command, either with a range like `:7,17Commentary`, or as part of a +`:global` invocation like with `:g/TODO/Commentary`. That's it. + +I wrote this because 5 years after Vim added support for mapping an +operator, I still couldn't find a commenting plugin that leveraged that +feature (I overlooked +[tcomment.vim](https://github.com/tomtom/tcomment_vim)). Striving for +minimalism, it weighs in at under 100 lines of code. + +Oh, and it uncomments, too. The above maps actually toggle, and `gcgc` +uncomments a set of adjacent commented lines. + +## Installation + +If you don't have a preferred installation method, I recommend +installing [pathogen.vim](https://github.com/tpope/vim-pathogen), and +then simply copy and paste: + + cd ~/.vim/bundle + git clone git://github.com/tpope/vim-commentary.git + +Once help tags have been generated, you can view the manual with +`:help commentary`. + +## FAQ + +> My favorite file type isn't supported! + +Relax! You just have to adjust `'commentstring'`: + + autocmd FileType apache set commentstring=#\ %s + +## Self-Promotion + +Like commentary.vim? Follow the repository on +[GitHub](https://github.com/tpope/vim-commentary) and vote for it on +[vim.org](http://www.vim.org/scripts/script.php?script_id=3695). And if +you're feeling especially charitable, follow [tpope](http://tpo.pe/) on +[Twitter](http://twitter.com/tpope) and +[GitHub](https://github.com/tpope). + +## License + +Copyright (c) Tim Pope. Distributed under the same terms as Vim itself. +See `:help license`.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.vim/bundle/vim-commentary/doc/commentary.txt Sun Jan 18 18:35:47 2015 +0000 @@ -0,0 +1,35 @@ +*commentary.txt* Comment stuff out + +Author: Tim Pope <http://tpo.pe/> +License: Same terms as Vim itself (see |license|) + +Comment stuff out. Then uncomment it later. Relies on 'commentstring' to be +correctly set, or uses b:commentary_format if it is set. + +The gc mappings are preferred, while the \\ mappings are provided for +backwards compatibility. + + *gc* +gc{motion} Comment or uncomment lines that {motion} moves over. + + *gcc* +gcc Comment or uncomment [count] lines. + + *v_gc* +{Visual}gc Comment or uncomment the highlighted lines. + + *o_gc* +gc Text object for a comment (operator pending mode + only.) + + *gcgc* *gcu* +gcgc Uncomment the current and adjacent commented lines. +gcu + + *:Commentary* +:[range]Commentary Comment or uncomment [range] lines + +The |User| CommentaryPost autocommand fires after a successful operation and +can be used for advanced customization. + + vim:tw=78:et:ft=help:norl:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.vim/bundle/vim-commentary/plugin/commentary.vim Sun Jan 18 18:35:47 2015 +0000 @@ -0,0 +1,99 @@ +" commentary.vim - Comment stuff out +" Maintainer: Tim Pope <http://tpo.pe/> +" Version: 1.2 +" GetLatestVimScripts: 3695 1 :AutoInstall: commentary.vim + +if exists("g:loaded_commentary") || &cp || v:version < 700 + finish +endif +let g:loaded_commentary = 1 + +function! s:surroundings() abort + return split(get(b:, 'commentary_format', substitute(substitute( + \ &commentstring, '\S\zs%s',' %s','') ,'%s\ze\S', '%s ', '')), '%s', 1) +endfunction + +function! s:go(type,...) abort + if a:0 + let [lnum1, lnum2] = [a:type, a:1] + else + let [lnum1, lnum2] = [line("'["), line("']")] + endif + + let [l, r] = s:surroundings() + let uncomment = 2 + for lnum in range(lnum1,lnum2) + let line = matchstr(getline(lnum),'\S.*\s\@<!') + if line != '' && (stridx(line,l) || line[strlen(line)-strlen(r) : -1] != r) + let uncomment = 0 + endif + endfor + + for lnum in range(lnum1,lnum2) + let line = getline(lnum) + if strlen(r) > 2 && l.r !~# '\\' + let line = substitute(line, + \'\M'.r[0:-2].'\zs\d\*\ze'.r[-1:-1].'\|'.l[0].'\zs\d\*\ze'.l[1:-1], + \'\=substitute(submatch(0)+1-uncomment,"^0$\\|^-\\d*$","","")','g') + endif + if uncomment + let line = substitute(line,'\S.*\s\@<!','\=submatch(0)[strlen(l):-strlen(r)-1]','') + else + let line = substitute(line,'^\%('.matchstr(getline(lnum1),'^\s*').'\|\s*\)\zs.*\S\@<=','\=l.submatch(0).r','') + endif + call setline(lnum,line) + endfor + let modelines = &modelines + try + set modelines=0 + silent doautocmd User CommentaryPost + finally + let &modelines = modelines + endtry +endfunction + +function! s:textobject(inner) abort + let [l, r] = s:surroundings() + let lnums = [line('.')+1, line('.')-2] + for [index, dir, bound, line] in [[0, -1, 1, ''], [1, 1, line('$'), '']] + while lnums[index] != bound && line ==# '' || !(stridx(line,l) || line[strlen(line)-strlen(r) : -1] != r) + let lnums[index] += dir + let line = matchstr(getline(lnums[index]+dir),'\S.*\s\@<!') + endwhile + endfor + while (a:inner || lnums[1] != line('$')) && empty(getline(lnums[0])) + let lnums[0] += 1 + endwhile + while a:inner && empty(getline(lnums[1])) + let lnums[1] -= 1 + endwhile + if lnums[0] <= lnums[1] + execute 'normal! 'lnums[0].'GV'.lnums[1].'G' + endif +endfunction + +xnoremap <silent> <Plug>Commentary :<C-U>call <SID>go(line("'<"),line("'>"))<CR> +nnoremap <silent> <Plug>Commentary :<C-U>set opfunc=<SID>go<CR>g@ +nnoremap <silent> <Plug>CommentaryLine :<C-U>set opfunc=<SID>go<Bar>exe 'norm! 'v:count1.'g@_'<CR> +onoremap <silent> <Plug>Commentary :<C-U>call <SID>textobject(0)<CR> +nnoremap <silent> <Plug>ChangeCommentary c:<C-U>call <SID>textobject(1)<CR> +nmap <silent> <Plug>CommentaryUndo <Plug>Commentary<Plug>Commentary +command! -range -bar Commentary call s:go(<line1>,<line2>) + +if !hasmapto('<Plug>Commentary') || maparg('gc','n') ==# '' + xmap gc <Plug>Commentary + nmap gc <Plug>Commentary + omap gc <Plug>Commentary + nmap gcc <Plug>CommentaryLine + nmap cgc <Plug>ChangeCommentary + nmap gcu <Plug>Commentary<Plug>Commentary +endif + +if maparg('\\','n') ==# '' && maparg('\','n') ==# '' && get(g:, 'commentary_map_backslash', 1) + xmap \\ <Plug>Commentary:echomsg '\\ is deprecated. Use gc'<CR> + nmap \\ :echomsg '\\ is deprecated. Use gc'<CR><Plug>Commentary + nmap \\\ <Plug>CommentaryLine:echomsg '\\ is deprecated. Use gc'<CR> + nmap \\u <Plug>CommentaryUndo:echomsg '\\ is deprecated. Use gc'<CR> +endif + +" vim:set et sw=2:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.vim/ftplugin/humdrum.vim Sun Jan 18 18:35:47 2015 +0000 @@ -0,0 +1,3 @@ +set shiftwidth=20 +set tabstop=20 +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.vim/indent/prolog.vim Sun Jan 18 18:35:47 2015 +0000 @@ -0,0 +1,58 @@ +" vim: set sw=4 sts=4: +" Maintainer : Gergely Kontra <kgergely@mcl.hu> +" Revised on : 2002.02.18. 23:34:05 +" Language : Prolog + +" TODO: +" checking with respect to syntax highlighting +" ignoring multiline comments +" detecting multiline strings + +" Only load this indent file when no other was loaded. +if exists("b:did_indent") + finish +endif + +let b:did_indent = 1 + +setlocal indentexpr=GetPrologIndent() +setlocal indentkeys-=:,0# +setlocal indentkeys+=0%,0;,0) + +" Only define the function once. +"if exists("*GetPrologIndent") +" finish +"endif + +function! GetPrologIndent() + " Find a non-blank line above the current line. + let pnum = prevnonblank(v:lnum - 1) + " Hit the start of the file, use zero indent. + if pnum == 0 + return 0 + endif + let line = getline(v:lnum) + let pline = getline(pnum) + + let ind = indent(pnum) + " Previous line was comment -> use previous line's indent + if pline =~ '^\s*%' + retu ind + endif + " Check for clause head on previous line + if pline =~ ':-\s*\(%.*\)\?$' + let ind = ind + &sw + " Check for end of clause on previous line + elseif pline =~ '\.\s*\(%.*\)\?$' + let ind = ind - &sw + endif + " Check for opening conditional on previous line + if pline =~ '^\s*\([(;]\|->\)' + let ind = ind + &sw + endif + " Check for closing an unclosed paren, or middle ; or -> + if line =~ '^\s*\([);]\|->\)' + let ind = ind - &sw + endif + return ind +endfunction
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.vim/plugin/commentary.vim Sun Jan 18 18:35:47 2015 +0000 @@ -0,0 +1,75 @@ +" commentary.vim - Comment stuff out +" Maintainer: Tim Pope <http://tpo.pe/> +" Version: 1.1 +" GetLatestVimScripts: 3695 1 :AutoInstall: commentary.vim + +if exists("g:loaded_commentary") || &cp || v:version < 700 + finish +endif +let g:loaded_commentary = 1 + +function! s:go(type,...) abort + if a:0 + let [lnum1, lnum2] = [a:type, a:1] + else + let [lnum1, lnum2] = [line("'["), line("']")] + endif + + let [l, r] = split(substitute(substitute(&commentstring,'\S\zs%s',' %s',''),'%s\ze\S','%s ',''),'%s',1) + let uncomment = 2 + for lnum in range(lnum1,lnum2) + let line = matchstr(getline(lnum),'\S.*\s\@<!') + if line != '' && (stridx(line,l) || line[strlen(line)-strlen(r) : -1] != r) + let uncomment = 0 + endif + endfor + + for lnum in range(lnum1,lnum2) + let line = getline(lnum) + if strlen(r) > 2 && l.r !~# '\\' + let line = substitute(line, + \'\M'.r[0:-2].'\zs\d\*\ze'.r[-1:-1].'\|'.l[0].'\zs\d\*\ze'.l[1:-1], + \'\=substitute(submatch(0)+1-uncomment,"^0$\\|^-\\d*$","","")','g') + endif + if uncomment + let line = substitute(line,'\S.*\s\@<!','\=submatch(0)[strlen(l):-strlen(r)-1]','') + else + let line = substitute(line,'^\%('.matchstr(getline(lnum1),'^\s*').'\|\s*\)\zs.*\S\@<=','\=l.submatch(0).r','') + endif + call setline(lnum,line) + endfor +endfunction + +function! s:undo() + let [l, r] = split(substitute(substitute(&commentstring,'\S\zs%s',' %s',''),'%s\ze\S','%s ',''),'%s',1) + let lnums = [line('.')+1, line('.')-2] + for [index, dir, bound, line] in [[0, -1, 1, ''], [1, 1, line('$'), '']] + while lnums[index] != bound && line ==# '' || !(stridx(line,l) || line[strlen(line)-strlen(r) : -1] != r) + let lnums[index] += dir + let line = matchstr(getline(lnums[index]+dir),'\S.*\s\@<!') + endwhile + endfor + call s:go(lnums[0], lnums[1]) + silent! call repeat#set("\<Plug>CommentaryUndo") +endfunction + +xnoremap <silent> <Plug>Commentary :<C-U>call <SID>go(line("'<"),line("'>"))<CR> +nnoremap <silent> <Plug>Commentary :<C-U>set opfunc=<SID>go<CR>g@ +nnoremap <silent> <Plug>CommentaryLine :<C-U>set opfunc=<SID>go<Bar>exe 'norm! 'v:count1.'g@_'<CR> +nnoremap <silent> <Plug>CommentaryUndo :<C-U>call <SID>undo()<CR> + +if !hasmapto('<Plug>Commentary') || maparg('gc','n') ==# '' + xmap gc <Plug>Commentary + nmap gc <Plug>Commentary + nmap gcc <Plug>CommentaryLine + nmap gcu <Plug>CommentaryUndo +endif + +if maparg('\\','n') ==# '' && maparg('\','n') ==# '' + xmap \\ <Plug>Commentary + nmap \\ <Plug>Commentary + nmap \\\ <Plug>CommentaryLine + nmap \\u <Plug>CommentaryUndo +endif + +" vim:set et sw=2:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.vim/plugin/filebrowser.vim Sun Jan 18 18:35:47 2015 +0000 @@ -0,0 +1,250 @@ +" filebrowser.vim: utility file for vim 6.2+ +" +" Copyright: Srinath Avadhanula <srinath AT fastmail DOT fm> +" Parts of this file are taken from explorer.vim which is a plugin file +" distributed with vim under the Vim charityware license. +" License: distributed under the Vim charityware license. +" +" Settings: +" FB_CallBackFunction: the function name which gets called when the user +" presses <cr> on a file-name in the file browser. +" FB_AllowRegexp: A filename has to match this regexp to be displayed. +" FB_RejectRegexp: If a filename matches this regexp, then its not displayed. +" (Both these regexps are '' by default which means no filtering is +" done). + +" line continuation used here. +let s:save_cpo = &cpo +set cpo&vim + +"====================================================================== +" Globally visible functions (API) +"====================================================================== +" FB_OpenFileBrowser: opens a new buffer and displays the file list {{{ +" Description: +function! FB_OpenFileBrowser(dir) + if !isdirectory(a:dir) + return + endif + if exists('s:FB_BufferNumber') + if bufwinnr(s:FB_BufferNumber) != -1 + execute bufwinnr(s:FB_BufferNumber).' wincmd w' + return + endif + execute 'aboveleft split #'.s:FB_BufferNumber + else + aboveleft split __Choose_File__ + let s:FB_BufferNumber = bufnr('%') + endif + call FB_DisplayFiles(a:dir) +endfunction " }}} +" FB_DisplayFiles: displays the files in a given directory {{{ +" Description: +" Call this function only when the cursor is in a temporary buffer +function! FB_DisplayFiles(dir) + if !isdirectory(a:dir) + return + endif + call s:FB_SetSilentSettings() + " make this a "scratch" buffer + call s:FB_SetScratchSettings() + + let allowRegexp = s:FB_GetVar('FB_AllowRegexp', '') + let rejectRegexp = s:FB_GetVar('FB_RejectRegexp', '') + + " change to the directory to make processing simpler. + execute "lcd ".a:dir + " delete everything in the buffer. + " IMPORTANT: we need to be in a scratch buffer + 0,$ d_ + + let allFilenames = glob('*') + let dispFiles = "" + let subDirs = "../\n" + + let allFilenames = allFilenames."\n" + let start = 0 + while 1 + let next = stridx(allFilenames, "\n", start) + let filename = strpart(allFilenames, start, next-start) + if filename == "" + break + endif + + if isdirectory(filename) + let subDirs = subDirs.filename."/\n" + else + if allowRegexp != '' && filename !~ allowRegexp + elseif rejectRegexp != '' && filename =~ rejectRegexp + else + let dispFiles = dispFiles.filename."\n" + endif + endif + + let start = next + 1 + endwhile + + 0put!=dispFiles + 0put!=subDirs + " delte the last empty line resulting from the put + $ d_ + + call s:FB_SetHighlighting() + call s:FB_DisplayHelp() + call s:FB_SetMaps() + + " goto the first file/directory + 0 + call search('^"=', 'w') + normal! j:<bs> + + set nomodified nomodifiable + + call s:FB_ResetSilentSettings() +endfunction " }}} +" FB_SetVar: sets script local variables from outside this script {{{ +" Description: +function! FB_SetVar(varname, value) + let s:{a:varname} = a:value +endfunction " }}} + +" ============================================================================== +" Script local functions below this +" ============================================================================== +" FB_SetHighlighting: sets syntax highlighting for the buffer {{{ +" Description: +" Origin: from explorer.vim in vim +function! <SID>FB_SetHighlighting() + " Set up syntax highlighting + " Something wrong with the evaluation of the conditional though... + if has("syntax") && exists("g:syntax_on") && !has("syntax_items") + syn match browseSynopsis "^\"[ -].*" + syn match browseDirectory "[^\"].*/ " + syn match browseDirectory "[^\"].*/$" + syn match browseCurDir "^\"= .*$" + syn match browseSortBy "^\" Sorted by .*$" contains=browseSuffixInfo + syn match browseSuffixInfo "(.*)$" contained + syn match browseFilter "^\" Not Showing:.*$" + syn match browseFiletime "«\d\+$" + + "hi def link browseSynopsis PreProc + hi def link browseSynopsis Special + hi def link browseDirectory Directory + hi def link browseCurDir Statement + hi def link browseSortBy String + hi def link browseSuffixInfo Type + hi def link browseFilter String + hi def link browseFiletime Ignore + hi def link browseSuffixes Type + endif +endfunction " }}} +" FB_SetMaps: sets buffer local maps {{{ +" Description: +function! <SID>FB_SetMaps() + nnoremap <buffer> <silent> q :bdelete<cr> + nnoremap <buffer> <silent> C :call FB_DisplayFiles(getcwd())<CR> + nnoremap <buffer> <silent> <esc> :bdelete<cr> + nnoremap <buffer> <silent> <CR> :call <SID>FB_EditEntry()<CR> + nnoremap <buffer> <silent> ? :call <SID>FB_ToggleHelp()<CR> + + " lock the user in this window + nnoremap <buffer> <C-w> <nop> +endfunction " }}} +" FB_SetSilentSettings: some settings which make things silent {{{ +" Description: +" Origin: from explorer.vim distributed with vim. +function! <SID>FB_SetSilentSettings() + let s:save_report=&report + let s:save_showcmd = &sc + set report=10000 noshowcmd +endfunction +" FB_ResetSilentSettings: reset settings set by FB_SetSilentSettings +" Description: +function! <SID>FB_ResetSilentSettings() + let &report=s:save_report + let &showcmd = s:save_showcmd +endfunction " }}} +" FB_SetScratchSettings: makes the present buffer a scratch buffer {{{ +" Description: +function! <SID>FB_SetScratchSettings() + " Turn off the swapfile, set the buffer type so that it won't get + " written, and so that it will get deleted when it gets hidden. + setlocal noreadonly modifiable + setlocal noswapfile + setlocal buftype=nowrite + setlocal bufhidden=delete + " Don't wrap around long lines + setlocal nowrap +endfunction + +" }}} +" FB_ToggleHelp: toggles verbosity of help {{{ +" Description: +function! <SID>FB_ToggleHelp() + let s:FB_VerboseHelp = 1 - s:FB_GetVar('FB_VerboseHelp', 0) + + call FB_DisplayFiles('.') +endfunction " }}} +" FB_DisplayHelp: displays a helpful header {{{ +" Description: +function! <SID>FB_DisplayHelp() + let verboseHelp = s:FB_GetVar('FB_VerboseHelp', 0) + if verboseHelp + let txt = + \ "\" <cr>: on file, choose the file and quit\n" + \ ."\" on dir, enter directory\n" + \ ."\" q/<esc>: quit without choosing\n" + \ ."\" C: change directory to getcwd()\n" + \ ."\" ?: toggle help verbosity\n" + \ ."\"= ".getcwd() + else + let txt = "\" ?: toggle help verbosity\n" + \ ."\"= ".getcwd() + endif + 0put!=txt +endfunction " }}} +" FB_EditEntry: handles the user pressing <enter> on a line {{{ +" Description: +function! <SID>FB_EditEntry() + let line = getline('.') + + if isdirectory(line) + call FB_DisplayFiles(line) + endif + + " If the user has a call back function defined on choosing a file, handle + " it. + let cbf = s:FB_GetVar('FB_CallBackFunction', '') + if cbf != '' && line !~ '^" ' && filereadable(line) + let fname = fnamemodify(line, ':p') + bdelete + + let arguments = s:FB_GetVar('FB_CallBackFunctionArgs', '') + if arguments != '' + let arguments = ','.arguments + endif + call Tex_Debug('arguments = '.arguments, 'fb') + call Tex_Debug("call ".cbf."('".fname."'".arguments.')', 'fb') + exec "call ".cbf."('".fname."'".arguments.')' + endif +endfunction " }}} +" FB_GetVar: gets the most local value of a variable {{{ +function! <SID>FB_GetVar(name, default) + if exists('s:'.a:name) + return s:{a:name} + elseif exists('w:'.a:name) + return w:{a:name} + elseif exists('b:'.a:name) + return b:{a:name} + elseif exists('g:'.a:name) + return g:{a:name} + else + return a:default + endif +endfunction + +" }}} + +let &cpo = s:save_cpo + +" vim:fdm=marker:ff=unix:noet:ts=4:sw=4:nowrap
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.vim/plugin/imaps.vim Sun Jan 18 18:35:47 2015 +0000 @@ -0,0 +1,831 @@ +" File: imaps.vim +" Authors: Srinath Avadhanula <srinath AT fastmail.fm> +" Benji Fisher <benji AT member.AMS.org> +" +" WWW: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/vim-latex/vimfiles/plugin/imaps.vim?only_with_tag=MAIN +" +" Description: insert mode template expander with cursor placement +" while preserving filetype indentation. +" +" $Id: imaps.vim 997 2006-03-20 09:45:45Z srinathava $ +" +" Documentation: {{{ +" +" Motivation: +" this script provides a way to generate insert mode mappings which do not +" suffer from some of the problem of mappings and abbreviations while allowing +" cursor placement after the expansion. It can alternatively be thought of as +" a template expander. +" +" Consider an example. If you do +" +" imap lhs something +" +" then a mapping is set up. However, there will be the following problems: +" 1. the 'ttimeout' option will generally limit how easily you can type the +" lhs. if you type the left hand side too slowly, then the mapping will not +" be activated. +" 2. if you mistype one of the letters of the lhs, then the mapping is +" deactivated as soon as you backspace to correct the mistake. +" +" If, in order to take care of the above problems, you do instead +" +" iab lhs something +" +" then the timeout problem is solved and so is the problem of mistyping. +" however, abbreviations are only expanded after typing a non-word character. +" which causes problems of cursor placement after the expansion and invariably +" spurious spaces are inserted. +" +" Usage Example: +" this script attempts to solve all these problems by providing an emulation +" of imaps wchich does not suffer from its attendant problems. Because maps +" are activated without having to press additional characters, therefore +" cursor placement is possible. furthermore, file-type specific indentation is +" preserved, because the rhs is expanded as if the rhs is typed in literally +" by the user. +" +" The script already provides some default mappings. each "mapping" is of the +" form: +" +" call IMAP (lhs, rhs, ft) +" +" Some characters in the RHS have special meaning which help in cursor +" placement. +" +" Example One: +" +" call IMAP ("bit`", "\\begin{itemize}\<cr>\\item <++>\<cr>\\end{itemize}<++>", "tex") +" +" This effectively sets up the map for "bit`" whenever you edit a latex file. +" When you type in this sequence of letters, the following text is inserted: +" +" \begin{itemize} +" \item * +" \end{itemize}<++> +" +" where * shows the cursor position. The cursor position after inserting the +" text is decided by the position of the first "place-holder". Place holders +" are special characters which decide cursor placement and movement. In the +" example above, the place holder characters are <+ and +>. After you have typed +" in the item, press <C-j> and you will be taken to the next set of <++>'s. +" Therefore by placing the <++> characters appropriately, you can minimize the +" use of movement keys. +" +" NOTE: Set g:Imap_UsePlaceHolders to 0 to disable placeholders altogether. +" Set +" g:Imap_PlaceHolderStart and g:Imap_PlaceHolderEnd +" to something else if you want different place holder characters. +" Also, b:Imap_PlaceHolderStart and b:Imap_PlaceHolderEnd override the values +" of g:Imap_PlaceHolderStart and g:Imap_PlaceHolderEnd respectively. This is +" useful for setting buffer specific place hoders. +" +" Example Two: +" You can use the <C-r> command to insert dynamic elements such as dates. +" call IMAP ('date`', "\<c-r>=strftime('%b %d %Y')\<cr>", '') +" +" sets up the map for date` to insert the current date. +" +"--------------------------------------%<-------------------------------------- +" Bonus: This script also provides a command Snip which puts tearoff strings, +" '----%<----' above and below the visually selected range of lines. The +" length of the string is chosen to be equal to the longest line in the range. +" Recommended Usage: +" '<,'>Snip +"--------------------------------------%<-------------------------------------- +" }}} + +" line continuation used here. +let s:save_cpo = &cpo +set cpo&vim + +" ============================================================================== +" Script Options / Variables +" ============================================================================== +" Options {{{ +if !exists('g:Imap_StickyPlaceHolders') + let g:Imap_StickyPlaceHolders = 1 +endif +if !exists('g:Imap_DeleteEmptyPlaceHolders') + let g:Imap_DeleteEmptyPlaceHolders = 1 +endif +" }}} +" Variables {{{ +" s:LHS_{ft}_{char} will be generated automatically. It will look like +" s:LHS_tex_o = 'fo\|foo\|boo' and contain all mapped sequences ending in "o". +" s:Map_{ft}_{lhs} will be generated automatically. It will look like +" s:Map_c_foo = 'for(<++>; <++>; <++>)', the mapping for "foo". +" +" }}} + +" ============================================================================== +" functions for easy insert mode mappings. +" ============================================================================== +" IMAP: Adds a "fake" insert mode mapping. {{{ +" For example, doing +" IMAP('abc', 'def' ft) +" will mean that if the letters abc are pressed in insert mode, then +" they will be replaced by def. If ft != '', then the "mapping" will be +" specific to the files of type ft. +" +" Using IMAP has a few advantages over simply doing: +" imap abc def +" 1. with imap, if you begin typing abc, the cursor will not advance and +" long as there is a possible completion, the letters a, b, c will be +" displayed on on top of the other. using this function avoids that. +" 2. with imap, if a backspace or arrow key is pressed before completing +" the word, then the mapping is lost. this function allows movement. +" (this ofcourse means that this function is only limited to +" left-hand-sides which do not have movement keys or unprintable +" characters) +" It works by only mapping the last character of the left-hand side. +" when this character is typed in, then a reverse lookup is done and if +" the previous characters consititute the left hand side of the mapping, +" the previously typed characters and erased and the right hand side is +" inserted + +" IMAP: set up a filetype specific mapping. +" Description: +" "maps" the lhs to rhs in files of type 'ft'. If supplied with 2 +" additional arguments, then those are assumed to be the placeholder +" characters in rhs. If unspecified, then the placeholder characters +" are assumed to be '<+' and '+>' These placeholder characters in +" a:rhs are replaced with the users setting of +" [bg]:Imap_PlaceHolderStart and [bg]:Imap_PlaceHolderEnd settings. +" +function! IMAP(lhs, rhs, ft, ...) + + " Find the place holders to save for IMAP_PutTextWithMovement() . + if a:0 < 2 + let phs = '<+' + let phe = '+>' + else + let phs = a:1 + let phe = a:2 + endif + + let hash = s:Hash(a:lhs) + let s:Map_{a:ft}_{hash} = a:rhs + let s:phs_{a:ft}_{hash} = phs + let s:phe_{a:ft}_{hash} = phe + + " Add a:lhs to the list of left-hand sides that end with lastLHSChar: + let lastLHSChar = a:lhs[strlen(a:lhs)-1] + let hash = s:Hash(lastLHSChar) + if !exists("s:LHS_" . a:ft . "_" . hash) + let s:LHS_{a:ft}_{hash} = escape(a:lhs, '\') + else + let s:LHS_{a:ft}_{hash} = escape(a:lhs, '\') .'\|'. s:LHS_{a:ft}_{hash} + endif + + " map only the last character of the left-hand side. + if lastLHSChar == ' ' + let lastLHSChar = '<space>' + end + exe 'inoremap <silent>' + \ escape(lastLHSChar, '|') + \ '<C-r>=<SID>LookupCharacter("' . + \ escape(lastLHSChar, '\|"') . + \ '")<CR>' +endfunction + +" }}} +" IMAP_list: list the rhs and place holders corresponding to a:lhs {{{ +" +" Added mainly for debugging purposes, but maybe worth keeping. +function! IMAP_list(lhs) + let char = a:lhs[strlen(a:lhs)-1] + let charHash = s:Hash(char) + if exists("s:LHS_" . &ft ."_". charHash) && a:lhs =~ s:LHS_{&ft}_{charHash} + let ft = &ft + elseif exists("s:LHS__" . charHash) && a:lhs =~ s:LHS__{charHash} + let ft = "" + else + return "" + endif + let hash = s:Hash(a:lhs) + return "rhs = " . s:Map_{ft}_{hash} . " place holders = " . + \ s:phs_{ft}_{hash} . " and " . s:phe_{ft}_{hash} +endfunction +" }}} +" LookupCharacter: inserts mapping corresponding to this character {{{ +" +" This function extracts from s:LHS_{&ft}_{a:char} or s:LHS__{a:char} +" the longest lhs matching the current text. Then it replaces lhs with the +" corresponding rhs saved in s:Map_{ft}_{lhs} . +" The place-holder variables are passed to IMAP_PutTextWithMovement() . +function! s:LookupCharacter(char) + if IMAP_GetVal('Imap_FreezeImap', 0) == 1 + return a:char + endif + let charHash = s:Hash(a:char) + + " The line so far, including the character that triggered this function: + let text = strpart(getline("."), 0, col(".")-1) . a:char + " Prefer a local map to a global one, even if the local map is shorter. + " Is this what we want? Do we care? + " Use '\V' (very no-magic) so that only '\' is special, and it was already + " escaped when building up s:LHS_{&ft}_{charHash} . + if exists("s:LHS_" . &ft . "_" . charHash) + \ && text =~ "\\C\\V\\(" . s:LHS_{&ft}_{charHash} . "\\)\\$" + let ft = &ft + elseif exists("s:LHS__" . charHash) + \ && text =~ "\\C\\V\\(" . s:LHS__{charHash} . "\\)\\$" + let ft = "" + else + " If this is a character which could have been used to trigger an + " abbreviation, check if an abbreviation exists. + if a:char !~ '\k' + let lastword = matchstr(getline('.'), '\k\+$', '') + call IMAP_Debug('getting lastword = ['.lastword.']', 'imap') + if lastword != '' + " An extremeley wierd way to get around the fact that vim + " doesn't have the equivalent of the :mapcheck() function for + " abbreviations. + let _a = @a + exec "redir @a | silent! iab ".lastword." | redir END" + let abbreviationRHS = matchstr(@a."\n", "\n".'i\s\+'.lastword.'\s\+@\?\zs.*\ze'."\n") + + call IMAP_Debug('getting abbreviationRHS = ['.abbreviationRHS.']', 'imap') + + if @a =~ "No abbreviation found" || abbreviationRHS == "" + let @a = _a + return a:char + endif + + let @a = _a + let abbreviationRHS = escape(abbreviationRHS, '\<"') + exec 'let abbreviationRHS = "'.abbreviationRHS.'"' + + let lhs = lastword.a:char + let rhs = abbreviationRHS.a:char + let phs = IMAP_GetPlaceHolderStart() + let phe = IMAP_GetPlaceHolderEnd() + else + return a:char + endif + else + return a:char + endif + endif + " Find the longest left-hand side that matches the line so far. + " matchstr() returns the match that starts first. This automatically + " ensures that the longest LHS is used for the mapping. + if !exists('lhs') || !exists('rhs') + let lhs = matchstr(text, "\\C\\V\\(" . s:LHS_{ft}_{charHash} . "\\)\\$") + let hash = s:Hash(lhs) + let rhs = s:Map_{ft}_{hash} + let phs = s:phs_{ft}_{hash} + let phe = s:phe_{ft}_{hash} + endif + + if strlen(lhs) == 0 + return a:char + endif + " enough back-spaces to erase the left-hand side; -1 for the last + " character typed: + let bs = substitute(strpart(lhs, 1), ".", "\<bs>", "g") + return bs . IMAP_PutTextWithMovement(rhs, phs, phe) +endfunction + +" }}} +" IMAP_PutTextWithMovement: returns the string with movement appended {{{ +" Description: +" If a:str contains "placeholders", then appends movement commands to +" str in a way that the user moves to the first placeholder and enters +" insert or select mode. If supplied with 2 additional arguments, then +" they are assumed to be the placeholder specs. Otherwise, they are +" assumed to be '<+' and '+>'. These placeholder chars are replaced +" with the users settings of [bg]:Imap_PlaceHolderStart and +" [bg]:Imap_PlaceHolderEnd. +function! IMAP_PutTextWithMovement(str, ...) + + " The placeholders used in the particular input string. These can be + " different from what the user wants to use. + if a:0 < 2 + let phs = '<+' + let phe = '+>' + else + let phs = escape(a:1, '\') + let phe = escape(a:2, '\') + endif + + let text = a:str + + " The user's placeholder settings. + let phsUser = IMAP_GetPlaceHolderStart() + let pheUser = IMAP_GetPlaceHolderEnd() + + " Problem: depending on the setting of the 'encoding' option, a character + " such as "\xab" may not match itself. We try to get around this by + " changing the encoding of all our strings. At the end, we have to + " convert text back. + let phsEnc = s:Iconv(phs, "encode") + let pheEnc = s:Iconv(phe, "encode") + let phsUserEnc = s:Iconv(phsUser, "encode") + let pheUserEnc = s:Iconv(pheUser, "encode") + let textEnc = s:Iconv(text, "encode") + if textEnc != text + let textEncoded = 1 + else + let textEncoded = 0 + endif + + let pattern = '\V\(\.\{-}\)' .phs. '\(\.\{-}\)' .phe. '\(\.\*\)' + " If there are no placeholders, just return the text. + if textEnc !~ pattern + call IMAP_Debug('Not getting '.phs.' and '.phe.' in '.textEnc, 'imap') + return text + endif + " Break text up into "initial <+template+> final"; any piece may be empty. + let initialEnc = substitute(textEnc, pattern, '\1', '') + let templateEnc = substitute(textEnc, pattern, '\2', '') + let finalEnc = substitute(textEnc, pattern, '\3', '') + + " If the user does not want to use placeholders, then remove all but the + " first placeholder. + " Otherwise, replace all occurences of the placeholders here with the + " user's choice of placeholder settings. + if exists('g:Imap_UsePlaceHolders') && !g:Imap_UsePlaceHolders + let finalEnc = substitute(finalEnc, '\V'.phs.'\.\{-}'.phe, '', 'g') + else + let finalEnc = substitute(finalEnc, '\V'.phs.'\(\.\{-}\)'.phe, + \ phsUserEnc.'\1'.pheUserEnc, 'g') + endif + + " The substitutions are done, so convert back, if necessary. + if textEncoded + let initial = s:Iconv(initialEnc, "decode") + let template = s:Iconv(templateEnc, "decode") + let final = s:Iconv(finalEnc, "decode") + else + let initial = initialEnc + let template = templateEnc + let final = finalEnc + endif + + " Build up the text to insert: + " 1. the initial text plus an extra character; + " 2. go to Normal mode with <C-\><C-N>, so it works even if 'insertmode' + " is set, and mark the position; + " 3. replace the extra character with tamplate and final; + " 4. back to Normal mode and restore the cursor position; + " 5. call IMAP_Jumpfunc(). + let template = phsUser . template . pheUser + " Old trick: insert and delete a character to get the same behavior at + " start, middle, or end of line and on empty lines. + let text = initial . "X\<C-\>\<C-N>:call IMAP_Mark('set')\<CR>\"_s" + let text = text . template . final + let text = text . "\<C-\>\<C-N>:call IMAP_Mark('go')\<CR>" + let text = text . "i\<C-r>=IMAP_Jumpfunc('', 1)\<CR>" + + call IMAP_Debug('IMAP_PutTextWithMovement: text = ['.text.']', 'imap') + return text +endfunction + +" }}} +" IMAP_Jumpfunc: takes user to next <+place-holder+> {{{ +" Author: Luc Hermitte +" Arguments: +" direction: flag for the search() function. If set to '', search forwards, +" if 'b', then search backwards. See the {flags} argument of the +" |search()| function for valid values. +" inclusive: In vim, the search() function is 'exclusive', i.e we always goto +" next cursor match even if there is a match starting from the +" current cursor position. Setting this argument to 1 makes +" IMAP_Jumpfunc() also respect a match at the current cursor +" position. 'inclusive'ness is necessary for IMAP() because a +" placeholder string can occur at the very beginning of a map which +" we want to select. +" We use a non-zero value only in special conditions. Most mappings +" should use a zero value. +function! IMAP_Jumpfunc(direction, inclusive) + + " The user's placeholder settings. + let phsUser = IMAP_GetPlaceHolderStart() + let pheUser = IMAP_GetPlaceHolderEnd() + + let searchString = '' + " If this is not an inclusive search or if it is inclusive, but the + " current cursor position does not contain a placeholder character, then + " search for the placeholder characters. + if !a:inclusive || strpart(getline('.'), col('.')-1) !~ '\V\^'.phsUser + let searchString = '\V'.phsUser.'\_.\{-}'.pheUser + endif + + " If we didn't find any placeholders return quietly. + if searchString != '' && !search(searchString, a:direction) + return '' + endif + + " Open any closed folds and make this part of the text visible. + silent! foldopen! + + " Calculate if we have an empty placeholder or if it contains some + " description. + let template = + \ matchstr(strpart(getline('.'), col('.')-1), + \ '\V\^'.phsUser.'\zs\.\{-}\ze\('.pheUser.'\|\$\)') + let placeHolderEmpty = !strlen(template) + + " If we are selecting in exclusive mode, then we need to move one step to + " the right + let extramove = '' + if &selection == 'exclusive' + let extramove = 'l' + endif + + " Select till the end placeholder character. + let movement = "\<C-o>v/\\V".pheUser."/e\<CR>".extramove + + " First remember what the search pattern was. s:RemoveLastHistoryItem will + " reset @/ to this pattern so we do not create new highlighting. + let g:Tex_LastSearchPattern = @/ + + " Now either goto insert mode or select mode. + if placeHolderEmpty && g:Imap_DeleteEmptyPlaceHolders + " delete the empty placeholder into the blackhole. + return movement."\"_c\<C-o>:".s:RemoveLastHistoryItem."\<CR>" + else + return movement."\<C-\>\<C-N>:".s:RemoveLastHistoryItem."\<CR>gv\<C-g>" + endif + +endfunction + +" }}} +" Maps for IMAP_Jumpfunc {{{ +" +" These mappings use <Plug> and thus provide for easy user customization. When +" the user wants to map some other key to jump forward, he can do for +" instance: +" nmap ,f <plug>IMAP_JumpForward +" etc. + +" jumping forward and back in insert mode. +imap <silent> <Plug>IMAP_JumpForward <c-r>=IMAP_Jumpfunc('', 0)<CR> +imap <silent> <Plug>IMAP_JumpBack <c-r>=IMAP_Jumpfunc('b', 0)<CR> + +" jumping in normal mode +nmap <silent> <Plug>IMAP_JumpForward i<c-r>=IMAP_Jumpfunc('', 0)<CR> +nmap <silent> <Plug>IMAP_JumpBack i<c-r>=IMAP_Jumpfunc('b', 0)<CR> + +" deleting the present selection and then jumping forward. +vmap <silent> <Plug>IMAP_DeleteAndJumpForward "_<Del>i<c-r>=IMAP_Jumpfunc('', 0)<CR> +vmap <silent> <Plug>IMAP_DeleteAndJumpBack "_<Del>i<c-r>=IMAP_Jumpfunc('b', 0)<CR> + +" jumping forward without deleting present selection. +vmap <silent> <Plug>IMAP_JumpForward <C-\><C-N>i<c-r>=IMAP_Jumpfunc('', 0)<CR> +vmap <silent> <Plug>IMAP_JumpBack <C-\><C-N>`<i<c-r>=IMAP_Jumpfunc('b', 0)<CR> + +" }}} +" Default maps for IMAP_Jumpfunc {{{ +" map only if there is no mapping already. allows for user customization. +" NOTE: Default mappings for jumping to the previous placeholder are not +" provided. It is assumed that if the user will create such mappings +" hself if e so desires. +if !hasmapto('<Plug>IMAP_JumpForward', 'i') + imap <C-J> <Plug>IMAP_JumpForward +endif +if !hasmapto('<Plug>IMAP_JumpForward', 'n') + nmap <C-J> <Plug>IMAP_JumpForward +endif +if exists('g:Imap_StickyPlaceHolders') && g:Imap_StickyPlaceHolders + if !hasmapto('<Plug>IMAP_JumpForward', 'v') + vmap <C-J> <Plug>IMAP_JumpForward + endif +else + if !hasmapto('<Plug>IMAP_DeleteAndJumpForward', 'v') + vmap <C-J> <Plug>IMAP_DeleteAndJumpForward + endif +endif +" }}} + +nmap <silent> <script> <plug><+SelectRegion+> `<v`> + +" ============================================================================== +" enclosing selected region. +" ============================================================================== +" VEnclose: encloses the visually selected region with given arguments {{{ +" Description: allows for differing action based on visual line wise +" selection or visual characterwise selection. preserves the +" marks and search history. +function! VEnclose(vstart, vend, VStart, VEnd) + + " its characterwise if + " 1. characterwise selection and valid values for vstart and vend. + " OR + " 2. linewise selection and invalid values for VStart and VEnd + if (visualmode() == 'v' && (a:vstart != '' || a:vend != '')) || (a:VStart == '' && a:VEnd == '') + + let newline = "" + let _r = @r + + let normcmd = "normal! \<C-\>\<C-n>`<v`>\"_s" + + exe "normal! \<C-\>\<C-n>`<v`>\"ry" + if @r =~ "\n$" + let newline = "\n" + let @r = substitute(@r, "\n$", '', '') + endif + + " In exclusive selection, we need to select an extra character. + if &selection == 'exclusive' + let movement = 8 + else + let movement = 7 + endif + let normcmd = normcmd. + \ a:vstart."!!mark!!".a:vend.newline. + \ "\<C-\>\<C-N>?!!mark!!\<CR>v".movement."l\"_s\<C-r>r\<C-\>\<C-n>" + + " this little if statement is because till very recently, vim used to + " report col("'>") > length of selected line when `> is $. on some + " systems it reports a -ve number. + if col("'>") < 0 || col("'>") > strlen(getline("'>")) + let lastcol = strlen(getline("'>")) + else + let lastcol = col("'>") + endif + if lastcol - col("'<") != 0 + let len = lastcol - col("'<") + else + let len = '' + endif + + " the next normal! is for restoring the marks. + let normcmd = normcmd."`<v".len."l\<C-\>\<C-N>" + + " First remember what the search pattern was. s:RemoveLastHistoryItem + " will reset @/ to this pattern so we do not create new highlighting. + let g:Tex_LastSearchPattern = @/ + + silent! exe normcmd + " this is to restore the r register. + let @r = _r + " and finally, this is to restore the search history. + execute s:RemoveLastHistoryItem + + else + + exec 'normal! `<O'.a:VStart."\<C-\>\<C-n>" + exec 'normal! `>o'.a:VEnd."\<C-\>\<C-n>" + if &indentexpr != '' + silent! normal! `<kV`>j= + endif + silent! normal! `> + endif +endfunction + +" }}} +" ExecMap: adds the ability to correct an normal/visual mode mapping. {{{ +" Author: Hari Krishna Dara <hari_vim@yahoo.com> +" Reads a normal mode mapping at the command line and executes it with the +" given prefix. Press <BS> to correct and <Esc> to cancel. +function! ExecMap(prefix, mode) + " Temporarily remove the mapping, otherwise it will interfere with the + " mapcheck call below: + let myMap = maparg(a:prefix, a:mode) + exec a:mode."unmap ".a:prefix + + " Generate a line with spaces to clear the previous message. + let i = 1 + let clearLine = "\r" + while i < &columns + let clearLine = clearLine . ' ' + let i = i + 1 + endwhile + + let mapCmd = a:prefix + let foundMap = 0 + let breakLoop = 0 + echon "\rEnter Map: " . mapCmd + while !breakLoop + let char = getchar() + if char !~ '^\d\+$' + if char == "\<BS>" + let mapCmd = strpart(mapCmd, 0, strlen(mapCmd) - 1) + endif + else " It is the ascii code. + let char = nr2char(char) + if char == "\<Esc>" + let breakLoop = 1 + else + let mapCmd = mapCmd . char + if maparg(mapCmd, a:mode) != "" + let foundMap = 1 + let breakLoop = 1 + elseif mapcheck(mapCmd, a:mode) == "" + let mapCmd = strpart(mapCmd, 0, strlen(mapCmd) - 1) + endif + endif + endif + echon clearLine + echon "\rEnter Map: " . mapCmd + endwhile + if foundMap + if a:mode == 'v' + " use a plug to select the region instead of using something like + " `<v`> to avoid problems caused by some of the characters in + " '`<v`>' being mapped. + let gotoc = "\<plug><+SelectRegion+>" + else + let gotoc = '' + endif + exec "normal ".gotoc.mapCmd + endif + exec a:mode.'noremap '.a:prefix.' '.myMap +endfunction + +" }}} + +" ============================================================================== +" helper functions +" ============================================================================== +" Strntok: extract the n^th token from a list {{{ +" example: Strntok('1,23,3', ',', 2) = 23 +fun! <SID>Strntok(s, tok, n) + return matchstr( a:s.a:tok[0], '\v(\zs([^'.a:tok.']*)\ze['.a:tok.']){'.a:n.'}') +endfun + +" }}} +" s:RemoveLastHistoryItem: removes last search item from search history {{{ +" Description: Execute this string to clean up the search history. +let s:RemoveLastHistoryItem = ':call histdel("/", -1)|let @/=g:Tex_LastSearchPattern' + +" }}} +" s:Hash: Return a version of a string that can be used as part of a variable" {{{ +" name. +" Converts every non alphanumeric character into _{ascii}_ where {ascii} is +" the ASCII code for that character... +fun! s:Hash(text) + return substitute(a:text, '\([^[:alnum:]]\)', + \ '\="_".char2nr(submatch(1))."_"', 'g') +endfun +"" }}} +" IMAP_GetPlaceHolderStart and IMAP_GetPlaceHolderEnd: "{{{ +" return the buffer local placeholder variables, or the global one, or the default. +function! IMAP_GetPlaceHolderStart() + if exists("b:Imap_PlaceHolderStart") && strlen(b:Imap_PlaceHolderEnd) + return b:Imap_PlaceHolderStart + elseif exists("g:Imap_PlaceHolderStart") && strlen(g:Imap_PlaceHolderEnd) + return g:Imap_PlaceHolderStart + else + return "<+" +endfun +function! IMAP_GetPlaceHolderEnd() + if exists("b:Imap_PlaceHolderEnd") && strlen(b:Imap_PlaceHolderEnd) + return b:Imap_PlaceHolderEnd + elseif exists("g:Imap_PlaceHolderEnd") && strlen(g:Imap_PlaceHolderEnd) + return g:Imap_PlaceHolderEnd + else + return "+>" +endfun +" }}} +" s:Iconv: a wrapper for iconv()" {{{ +" Problem: after +" let text = "\xab" +" (or using the raw 8-bit ASCII character in a file with 'fenc' set to +" "latin1") if 'encoding' is set to utf-8, then text does not match itself: +" echo text =~ text +" returns 0. +" Solution: When this happens, a re-encoded version of text does match text: +" echo iconv(text, "latin1", "utf8") =~ text +" returns 1. In this case, convert text to utf-8 with iconv(). +" TODO: Is it better to use &encoding instead of "utf8"? Internally, vim +" uses utf-8, and can convert between latin1 and utf-8 even when compiled with +" -iconv, so let's try using utf-8. +" Arguments: +" a:text = text to be encoded or decoded +" a:mode = "encode" (latin1 to utf8) or "decode" (utf8 to latin1) +" Caution: do not encode and then decode without checking whether the text +" has changed, becuase of the :if clause in encoding! +function! s:Iconv(text, mode) + if a:mode == "decode" + return iconv(a:text, "utf8", "latin1") + endif + if a:text =~ '\V\^' . escape(a:text, '\') . '\$' + return a:text + endif + let textEnc = iconv(a:text, "latin1", "utf8") + if textEnc !~ '\V\^' . escape(a:text, '\') . '\$' + call IMAP_Debug('Encoding problems with text '.a:text.' ', 'imap') + endif + return textEnc +endfun +"" }}} +" IMAP_Debug: interface to Tex_Debug if available, otherwise emulate it {{{ +" Description: +" Do not want a memory leak! Set this to zero so that imaps always +" starts out in a non-debugging mode. +if !exists('g:Imap_Debug') + let g:Imap_Debug = 0 +endif +function! IMAP_Debug(string, pattern) + if !g:Imap_Debug + return + endif + if exists('*Tex_Debug') + call Tex_Debug(a:string, a:pattern) + else + if !exists('s:debug_'.a:pattern) + let s:debug_{a:pattern} = a:string + else + let s:debug_{a:pattern} = s:debug_{a:pattern}.a:string + endif + endif +endfunction " }}} +" IMAP_DebugClear: interface to Tex_DebugClear if avaialable, otherwise emulate it {{{ +" Description: +function! IMAP_DebugClear(pattern) + if exists('*Tex_DebugClear') + call Tex_DebugClear(a:pattern) + else + let s:debug_{a:pattern} = '' + endif +endfunction " }}} +" IMAP_PrintDebug: interface to Tex_DebugPrint if avaialable, otherwise emulate it {{{ +" Description: +function! IMAP_PrintDebug(pattern) + if exists('*Tex_PrintDebug') + call Tex_PrintDebug(a:pattern) + else + if exists('s:debug_'.a:pattern) + echo s:debug_{a:pattern} + endif + endif +endfunction " }}} +" IMAP_Mark: Save the cursor position (if a:action == 'set') in a" {{{ +" script-local variable; restore this position if a:action == 'go'. +let s:Mark = "(0,0)" +let s:initBlanks = '' +function! IMAP_Mark(action) + if a:action == 'set' + let s:Mark = "(" . line(".") . "," . col(".") . ")" + let s:initBlanks = matchstr(getline('.'), '^\s*') + elseif a:action == 'go' + execute "call cursor" s:Mark + let blanksNow = matchstr(getline('.'), '^\s*') + if strlen(blanksNow) > strlen(s:initBlanks) + execute 'silent! normal! '.(strlen(blanksNow) - strlen(s:initBlanks)).'l' + elseif strlen(blanksNow) < strlen(s:initBlanks) + execute 'silent! normal! '.(strlen(s:initBlanks) - strlen(blanksNow)).'h' + endif + endif +endfunction "" }}} +" IMAP_GetVal: gets the value of a variable {{{ +" Description: first checks window local, then buffer local etc. +function! IMAP_GetVal(name, ...) + if a:0 > 0 + let default = a:1 + else + let default = '' + endif + if exists('w:'.a:name) + return w:{a:name} + elseif exists('b:'.a:name) + return b:{a:name} + elseif exists('g:'.a:name) + return g:{a:name} + else + return default + endif +endfunction " }}} + +" ============================================================================== +" A bonus function: Snip() +" ============================================================================== +" Snip: puts a scissor string above and below block of text {{{ +" Desciption: +"-------------------------------------%<------------------------------------- +" this puts a the string "--------%<---------" above and below the visually +" selected block of lines. the length of the 'tearoff' string depends on the +" maximum string length in the selected range. this is an aesthetically more +" pleasing alternative instead of hardcoding a length. +"-------------------------------------%<------------------------------------- +function! <SID>Snip() range + let i = a:firstline + let maxlen = -2 + " find out the maximum virtual length of each line. + while i <= a:lastline + exe i + let length = virtcol('$') + let maxlen = (length > maxlen ? length : maxlen) + let i = i + 1 + endwhile + let maxlen = (maxlen > &tw && &tw != 0 ? &tw : maxlen) + let half = maxlen/2 + exe a:lastline + " put a string below + exe "norm! o\<esc>".(half - 1)."a-\<esc>A%<\<esc>".(half - 1)."a-" + " and above. its necessary to put the string below the block of lines + " first because that way the first line number doesnt change... + exe a:firstline + exe "norm! O\<esc>".(half - 1)."a-\<esc>A%<\<esc>".(half - 1)."a-" +endfunction + +com! -nargs=0 -range Snip :<line1>,<line2>call <SID>Snip() +" }}} + +let &cpo = s:save_cpo + +" vim:ft=vim:ts=4:sw=4:noet:fdm=marker:commentstring=\"\ %s:nowrap
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.vim/syntax/humdrum.vim Sun Jan 18 18:35:47 2015 +0000 @@ -0,0 +1,59 @@ +" Vim 5.6 syntax file +" Language: Humdrum file +" Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> +" Web Page: http://www.ccarh.org/software/humdrum/vi/syntax +" Creation Date: Fri Dec 8 11:41:45 PST 2000 +" Last Change: Fri Dec 8 13:57:53 PST 2000 +" + +" Remove any old syntax stuff hanging around +syntax clear + + +syntax match Data "^[^!\*]" contains=BadTabbing,Chord +syntax match Chord "[^\t][^\t]* [^\t]*" contains=ExtraSpace +syntax match ExtraSpace "^ " +syntax match ExtraSpace " $" +syntax match ExtraSpace " *\t" +syntax match ExtraSpace "\t *" +syntax match ExtraSpace " *" +syntax match BadTabbing "\t\t\t*" +syntax match BadTabbing "^\t" +syntax match BadTabbing "\t$" +syntax match GlobalComment "^!![^!].*$" +syntax match BibRecord "^!!![^ ].*:.*$" +syntax match Interpretation "^\*.*$" contains=BadTabbing,Exclusive +syntax match Measure "^=[^\t]*[\t]?" contains=BadTabbing +syntax match Measure "=[^\t]*[\t]" contains=BadTabbing +syntax match Measure "=[^\t]*$" contains=BadTabbing +syntax match LocalComment "^![^!].*$" contains=BadTabbing +syntax match Exclusive "\*\*[^\t]*" + + +if !exists("did_humdrum_syntax_inits") + let did_humdrum_syntax_inits = 1 + " The default methods for highlighting. Can be overridden later + hi darkgreen ctermfg=darkgreen guifg=darkgreen + hi darkblue ctermfg=darkblue guifg=darkblue + hi red ctermfg=red guifg=red + hi yellow ctermfg=yellow guifg=yellow + hi white ctermfg=white guifg=white + hi cyan ctermfg=cyan guifg=cyan + hi magenta ctermfg=magenta guifg=magenta + hi measure ctermfg=darkgrey ctermbg=lightgrey guifg=lightgrey guibg=black + hi space ctermbg=darkblue guibg=darkblue + hi link GlobalComment cyan + hi link LocalComment darkblue + hi link Interpretation magenta + hi link Measure measure + hi link Exclusive red + hi link Chord white + hi link BadTabbing Error + hi link ExtraSpace space + hi link BibRecord darkgreen +endif + + +let b:current_syntax = "humdrum" + +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.vimrc Sun Jan 18 18:35:47 2015 +0000 @@ -0,0 +1,165 @@ +" An example for a vimrc file. +" +" Maintainer: Bram Moolenaar <Bram@vim.org> +" Last change: 2001 Jul 18 +" +" To use it, copy it to +" for Unix and OS/2: ~/.vimrc +" for Amiga: s:.vimrc +" for MS-DOS and Win32: $VIM\_vimrc +" for OpenVMS: sys$login:.vimrc + +" samer: +set showmatch " show matching brackets +set ignorecase " case insensitive search... +set smartcase " ...except if string includes upper-case + +" When started as "evim", evim.vim will already have done these settings. +if v:progname =~? "evim" + finish +endif + +" Use Vim settings, rather then Vi settings (much better!). +" This must be first, because it changes other options as a side effect. +set nocompatible + +" allow backspacing over everything in insert mode +set backspace=indent,eol,start + +set autoindent " always set autoindenting on +if has("vms") + set nobackup " do not keep a backup file, use versions instead +else + set backup " keep a backup file +endif +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 + +" For Win32 GUI: remove 't' flag from 'guioptions': no tearoff menu entries +" let &guioptions = substitute(&guioptions, "t", "", "g") + +" Don't use Ex mode, use Q for formatting +map Q gq + +" Make p in Visual mode replace the selected text with the "" register. +vnoremap p <Esc>:let current_reg = @"<CR>gvs<C-R>=current_reg<CR><Esc> + +" This is an alternative that also works in block mode, but the deleted +" text is lost and it only works for putting the current register. +"vnoremap p "_dp + +" Switch syntax highlighting on, when the terminal has colors +" Also switch on highlighting the last used search pattern. +" if &t_Co > 2 || has("gui_running") + syntax on + set hlsearch +" endif + +" Only do this part when compiled with support for autocommands. +if has("autocmd") + + " Enable file type detection. + " Use the default filetype settings, so that mail gets 'tw' set to 72, + " 'cindent' is on in C files, etc. + " Also load indent files, to automatically do language-dependent indenting. + filetype plugin indent on + + " For all text files set 'textwidth' to 78 characters. + autocmd FileType text setlocal textwidth=78 + autocmd FileType python setlocal tabstop=4|set shiftwidth=4|set expandtab + autocmd FileType cs setlocal tabstop=4|set shiftwidth=4|set expandtab + autocmd FileType scheme setlocal expandtab|set tabstop=2 + autocmd FileType ocaml setlocal tabstop=2|set shiftwidth=2|set expandtab + autocmd FileType haskell setlocal tabstop=2|set shiftwidth=2|set expandtab + autocmd FileType prolog setlocal tabstop=3|set shiftwidth=3|set expandtab + autocmd Syntax ocaml set commentstring=(*%s*) + autocmd Syntax scheme set commentstring=;%s + autocmd FileType matlab setlocal tabstop=2|set shiftwidth=2 + + " When editing a file, always jump to the last known cursor position. + " Don't do it when the position is invalid or when inside an event handler + " (happens when dropping a file on gvim). + autocmd BufReadPost * + \ if line("'\"") > 0 && line("'\"") <= line("$") | + \ exe "normal g`\"" | + \ endif + +endif " has("autocmd") + +" Original vimrc from Mac OS X bundle +" System vimrc file for Mac OS X +" Author: Benji Fisher <benji@member.AMS.org> +" Last modified: 5 April 2003 + +" Get a good value for $PATH. For example, if teTeX is installed, this +" should add the path to tex, pdflatex, etc. +" This should only make a difference when vim is started from the Finder or +" with open. +let $PATH = system("printenv PATH") +let $PATH = substitute($PATH, "\<C-J>$", "", "") + +" If running in a Terminal window, set the terminal type to allow syntax +" highlighting. +" Otherwise, change directory on startup. +if !has("gui_running") + set term=xterm-color +else + autocmd VimEnter * if getcwd()=="/" | if strlen(@%) | cd %:p:h | else | cd | endif | endif +endif + +set title +set mouse=a +set mousefocus=on +set tabstop=3 +set softtabstop=3 +set shiftwidth=3 +set smarttab +" set ignorecase + +set nobackup " do not keep a backup file, use versions instead +" set backup " keep a backup file + +" Fix search highlighting colors and customise status bar and vertical split +hi clear Search +hi clear StatusLine +hi clear StatusLineNC +hi clear VertSplit + +hi Search term=underline cterm=underline gui=NONE +hi StatusLine term=bold,underline cterm=underline,bold gui=bold guifg=blue guibg=white +hi StatusLineNC term=underline cterm=underline guifg=white guibg=blue +hi VertSplit term=bold cterm=bold +hi MatchParen term=underline cterm=bold ctermbg=none gui=underline + +au BufWinEnter,BufNewFile,BufRead *.lytex set filetype=tex +au BufWinEnter,BufNewFile,BufRead *.icl set filetype=prolog +au BufWinEnter,BufNewFile,BufRead *.pha set filetype=prolog +au BufWinEnter,BufNewFile,BufRead *.psm set filetype=prolog +au BufWinEnter,BufNewFile,BufRead *.chr set filetype=prolog +au BufWinEnter,BufNewFile,BufRead *.yap set filetype=prolog +au BufWinEnter,BufNewFile,BufRead *.chrism set filetype=prolog +au BufWinEnter,BufNewFile,BufRead *.curry set filetype=haskell +au BufWinEnter,BufNewFile,BufRead *.kern set filetype=humdrum +au BufWinEnter,BufNewFile,BufRead *.krn set filetype=humdrum +au BufWinEnter,BufNewFile,BufRead *.church set filetype=scheme +au BufWinEnter,BufNewFile,BufRead .ocamlinit set filetype=ocaml + +" for vim-latex +set grepprg=grep\ -nH\ $* +set wildmenu +let g:Tex_AutoFolding=0 +let g:tex_flavor='latex' +let mapleader="\\" + +" for pasting code +set pastetoggle=<F2> + +cmap w!! w !sudo tee % >/dev/null<CR>:e!<CR><CR> +" activate visual mode in normal mode +nmap <S-Up> V +nmap <S-Down> V +" " these are mapped in visual mode +vmap <S-Up> k +vmap <S-Down> j
--- a/etc/setup_as_dml.sh Sun Jan 18 17:33:25 2015 +0000 +++ b/etc/setup_as_dml.sh Sun Jan 18 18:35:47 2015 +0000 @@ -3,23 +3,30 @@ echo 'THIS IS NOT READY YET!' exit 1 +function install_swi { + cd ~/src + wget http://www.swi-prolog.org/download/devel/src/pl-7.1.28.tar.gz + tar xzf pl-7.1.28.tar.gz + cd pl-7.1.28 + cp build.templ build + patch build ~/etc/swipl-build.patch + ./build +} + #build SWI Prolog -cd /tmp -wget http://www.swi-prolog.org/download/devel/src/pl-7.1.28.tar.gz -tar xzf pl-7.1.28.tar.gz -cd pl-7.1.28 -cp build.templ build -patch build ~/etc/swipl-build.patch -./build +install_swi # DOWNLOADS FROM REPOs - cd ~/src/github +git clone https://samer--/ClioPatria git clone --recursive https://github.com/humdrum-tools/humdrum-tools cd ~/src/hg -hg clone <dml-cliopatria> -hg clone <ishara> +hg clone https://code.soundsoftware.ac.uk/hg/dml-cliopatria +hg clone https://code.soundsoftware.ac.uk/hg/ishara +hg clone https://code.soundsoftware.ac.uk/hg/kernscores-utf8 +ln -s ~/src/hg/kernscores-utf8 ~/lib/kern +