diff --git a/.gitmodules b/.gitmodules index aa1e11a..1efcfd6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -97,3 +97,6 @@ [submodule "vim/bundle/skwp-vim-colors-solarized"] path = vim/bundle/skwp-vim-colors-solarized url = https://github.com/skwp/vim-colors-solarized +[submodule "vim/bundle/rson-vim-conque"] + path = vim/bundle/rson-vim-conque + url = https://github.com/rson/vim-conque.git diff --git a/vim/autoload/conque_term.vim b/vim/autoload/conque_term.vim deleted file mode 100644 index 607a876..0000000 --- a/vim/autoload/conque_term.vim +++ /dev/null @@ -1,1508 +0,0 @@ -" FILE: autoload/conque_term.vim {{{ -" AUTHOR: Nico Raffo -" WEBSITE: http://conque.googlecode.com -" MODIFIED: 2011-09-02 -" VERSION: 2.3, for Vim 7.0 -" LICENSE: -" Conque - Vim terminal/console emulator -" Copyright (C) 2009-2011 Nico Raffo -" -" MIT License -" -" Permission is hereby granted, free of charge, to any person obtaining a copy -" of this software and associated documentation files (the "Software"), to deal -" in the Software without restriction, including without limitation the rights -" to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -" copies of the Software, and to permit persons to whom the Software is -" furnished to do so, subject to the following conditions: -" -" The above copyright notice and this permission notice shall be included in -" all copies or substantial portions of the Software. -" -" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -" OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -" THE SOFTWARE. -" }}} - -" ********************************************************************************************************** -" **** GLOBAL INITIALIZATION ******************************************************************************* -" ********************************************************************************************************** - -" {{{ - -" load plugin file if it hasn't already been loaded (e.g. conque_term#foo() is used in .vimrc) -if !exists('g:ConqueTerm_Loaded') - runtime! plugin/conque_term.vim -endif - -" path to conque install directories -let s:scriptdir = expand(":h") . '/' -let s:scriptdirpy = expand(":h") . '/conque_term/' - -" global list of terminal instances -let s:term_obj = {'idx': 1, 'var': '', 'is_buffer': 1, 'active': 1, 'buffer_name': '', 'command': ''} -let g:ConqueTerm_Terminals = {} - -" global lists of registered functions -let s:hooks = { 'after_startup': [], 'buffer_enter': [], 'buffer_leave': [], 'after_keymap': [] } - -" required for session support -if g:ConqueTerm_SessionSupport == 1 - set sessionoptions+=globals - try - sil! let s:saved_terminals = eval(g:ConqueTerm_TerminalsString) - catch - let s:saved_terminals = {} - endtry -endif - -" more session support -let g:ConqueTerm_TerminalsString = '' - -" init terminal counter -let g:ConqueTerm_Idx = 0 - -" we clobber this value later -let s:save_updatetime = &updatetime - -" have we called the init() function yet? -let s:initialized = 0 - - -" }}} - -" ********************************************************************************************************** -" **** SYSTEM DETECTION ************************************************************************************ -" ********************************************************************************************************** - -" {{{ - -" Display various error messages -function! conque_term#fail(feature) " {{{ - - " create a new buffer - new - setlocal buftype=nofile - setlocal nonumber - setlocal foldcolumn=0 - setlocal wrap - setlocal noswapfile - - " missing vim features - if a:feature == 'python' - - call append('$', 'Conque ERROR: Python interface cannot be loaded') - call append('$', '') - - if !executable("python") - call append('$', 'Your version of Vim appears to be installed without the Python interface. In ') - call append('$', 'addition, you may need to install Python.') - else - call append('$', 'Your version of Vim appears to be installed without the Python interface.') - endif - - call append('$', '') - - if has('unix') == 1 - call append('$', "You are using a Unix-like operating system. Most, if not all, of the popular ") - call append('$', "Linux package managers have Python-enabled Vim available. For example ") - call append('$', "vim-gnome or vim-gtk on Ubuntu will get you everything you need.") - call append('$', "") - call append('$', "If you are compiling Vim from source, make sure you use the --enable-pythoninterp ") - call append('$', "configure option. You will also need to install Python and the Python headers.") - call append('$', "") - call append('$', "If you are using OS X, MacVim will give you Python support by default.") - else - call append('$', "You appear to be using Windows. The official Vim 7.3 installer available at ") - call append('$', "http://www.vim.org comes with the required Python interfaces. You will also ") - call append('$', "need to install Python 2.7 and/or Python 3.1, both available at http://www.python.org") - endif - - elseif a:feature == 'python_exe' - - call append('$', "Conque ERROR: Can't find Python executable") - call append('$', "") - call append('$', "Conque needs to know the full path to python.exe on Windows systems. By default, ") - call append('$', "Conque will check your system path as well as the most common installation path ") - call append('$', "C:\\PythonXX\\python.exe. To fix this error either:") - call append('$', "") - call append('$', "Set the g:ConqueTerm_PyExe option in your .vimrc. E.g.") - call append('$', " let g:ConqueTerm_PyExe = 'C:\Program Files\Python27\python.exe'") - call append('$', "") - call append('$', "Add the directory where you installed python to your system path. This isn't a bad ") - call append('$', "idea in general.") - - elseif a:feature == 'ctypes' - - call append('$', 'Conque ERROR: Python cannot load the ctypes module') - call append('$', "") - call append('$', "Conque requires the 'ctypes' python module. This has been a standard module since Python 2.5.") - call append('$', "") - call append('$', "The recommended fix is to make sure you're using the latest official GVim version 7.3, ") - call append('$', "and have at least one of the two compatible versions of Python installed, ") - call append('$', "2.7 or 3.1. You can download the GVim 7.3 installer from http://www.vim.org. You ") - call append('$', "can download the Python 2.7 or 3.1 installer from http://www.python.org") - - endif - -endfunction " }}} - -" Go through various system checks before attempting to launch conque -function! conque_term#dependency_check() " {{{ - - " don't recheck the second time 'round - if s:initialized == 1 - return 1 - endif - - " choose a python version - let s:py = '' - if g:ConqueTerm_PyVersion == 3 - let pytest = 'python3' - else - let pytest = 'python' - let g:ConqueTerm_PyVersion = 2 - endif - - " first test the requested version - if has(pytest) - if pytest == 'python3' - let s:py = 'py3' - else - let s:py = 'py' - endif - - " otherwise use the other version - else - let py_alternate = 5 - g:ConqueTerm_PyVersion - if py_alternate == 3 - let pytest = 'python3' - else - let pytest = 'python' - endif - if has(pytest) - echohl WarningMsg | echomsg "Python " . g:ConqueTerm_PyVersion . " interface is not installed, using Python " . py_alternate . " instead" | echohl None - let g:ConqueTerm_PyVersion = py_alternate - if pytest == 'python3' - let s:py = 'py3' - else - let s:py = 'py' - endif - endif - endif - - " test if we actually found a python version - if s:py == '' - call conque_term#fail('python') - return 0 - endif - - " quick and dirty platform declaration - if has('unix') == 1 - let s:platform = 'unix' - sil exe s:py . " CONQUE_PLATFORM = 'unix'" - else - let s:platform = 'windows' - sil exe s:py . " CONQUE_PLATFORM = 'windows'" - endif - - " if we're using Windows, make sure ctypes is available - if s:platform == 'windows' - try - sil exe s:py . " import ctypes" - catch - call conque_term#fail('ctypes') - return 0 - endtry - endif - - " if we're using Windows, make sure we can finde python executable - if s:platform == 'windows' && conque_term#find_python_exe() == '' - call conque_term#fail('python_exe') - return 0 - endif - - " check for global cursorhold/cursormove events - let o = '' - silent redir => o - silent autocmd CursorHoldI,CursorMovedI - redir END - for line in split(o, "\n") - if line =~ '^ ' || line =~ '^--' || line =~ 'matchparen' - continue - endif - if g:ConqueTerm_StartMessages - echohl WarningMsg | echomsg "Warning: Global CursorHoldI and CursorMovedI autocommands may cause ConqueTerm to run slowly." | echohl None - endif - endfor - - " check for compatible mode - if &compatible == 1 - echohl WarningMsg | echomsg "Warning: Conque may not function normally in 'compatible' mode." | echohl None - endif - - " check for fast mode - if g:ConqueTerm_FastMode - sil exe s:py . " CONQUE_FAST_MODE = True" - else - sil exe s:py . " CONQUE_FAST_MODE = False" - endif - - " if we're all good, load python files - call conque_term#load_python() - - return 1 - -endfunction " }}} - -" }}} - -" ********************************************************************************************************** -" **** STARTUP MESSAGES ************************************************************************************ -" ********************************************************************************************************** - -" {{{ -"if g:ConqueTerm_StartMessages -" let msg_file = s:scriptdirpy . 'version.vim' -" let msg_show = 1 -" let msg_ct = 1 -" -" " we can write to conque_term directory -" if filewritable(s:scriptdirpy) == 2 -" -" if filewritable(msg_file) -" -" " read current message file -" try -" silent execute "source " . msg_file -" if exists('g:ConqueTerm_MsgCt') && exists('g:ConqueTerm_MsgVer') -" if g:ConqueTerm_MsgVer == g:ConqueTerm_Version && g:ConqueTerm_MsgCt > 2 -" let msg_show = 0 -" else -" let msg_ct = g:ConqueTerm_MsgCt + 1 -" endif -" endif -" catch -" endtry -" endif -" -" " update message file -" if msg_show -" let file_contents = ['let g:ConqueTerm_MsgCt = ' . msg_ct, 'let g:ConqueTerm_MsgVer = ' . g:ConqueTerm_Version] -" call writefile(file_contents, msg_file) -" endif -" endif -" -" " save our final decision -" let g:ConqueTerm_StartMessages = msg_show -"endif -" }}} - -" ********************************************************************************************************** -" **** WINDOWS VK CODES ************************************************************************************ -" ********************************************************************************************************** - -" Windows Virtual Key Codes {{{ -let s:windows_vk = { -\ 'VK_ADD' : 107, -\ 'VK_APPS' : 93, -\ 'VK_ATTN' : 246, -\ 'VK_BACK' : 8, -\ 'VK_BROWSER_BACK' : 166, -\ 'VK_BROWSER_FORWARD' : 167, -\ 'VK_CANCEL' : 3, -\ 'VK_CAPITAL' : 20, -\ 'VK_CLEAR' : 12, -\ 'VK_CONTROL' : 17, -\ 'VK_CONVERT' : 28, -\ 'VK_CRSEL' : 247, -\ 'VK_DECIMAL' : 110, -\ 'VK_DELETE' : 46, -\ 'VK_DIVIDE' : 111, -\ 'VK_DOWN' : 40, -\ 'VK_DOWN_CTL' : '40;1024', -\ 'VK_END' : 35, -\ 'VK_EREOF' : 249, -\ 'VK_ESCAPE' : 27, -\ 'VK_EXECUTE' : 43, -\ 'VK_EXSEL' : 248, -\ 'VK_F1' : 112, -\ 'VK_F10' : 121, -\ 'VK_F11' : 122, -\ 'VK_F12' : 123, -\ 'VK_F13' : 124, -\ 'VK_F14' : 125, -\ 'VK_F15' : 126, -\ 'VK_F16' : 127, -\ 'VK_F17' : 128, -\ 'VK_F18' : 129, -\ 'VK_F19' : 130, -\ 'VK_F2' : 113, -\ 'VK_F20' : 131, -\ 'VK_F21' : 132, -\ 'VK_F22' : 133, -\ 'VK_F23' : 134, -\ 'VK_F24' : 135, -\ 'VK_F3' : 114, -\ 'VK_F4' : 115, -\ 'VK_F5' : 116, -\ 'VK_F6' : 117, -\ 'VK_F7' : 118, -\ 'VK_F8' : 119, -\ 'VK_F9' : 120, -\ 'VK_FINAL' : 24, -\ 'VK_HANGEUL' : 21, -\ 'VK_HANGUL' : 21, -\ 'VK_HANJA' : 25, -\ 'VK_HELP' : 47, -\ 'VK_HOME' : 36, -\ 'VK_INSERT' : 45, -\ 'VK_JUNJA' : 23, -\ 'VK_KANA' : 21, -\ 'VK_KANJI' : 25, -\ 'VK_LBUTTON' : 1, -\ 'VK_LCONTROL' : 162, -\ 'VK_LEFT' : 37, -\ 'VK_LEFT_CTL' : '37;1024', -\ 'VK_LMENU' : 164, -\ 'VK_LSHIFT' : 160, -\ 'VK_LWIN' : 91, -\ 'VK_MBUTTON' : 4, -\ 'VK_MEDIA_NEXT_TRACK' : 176, -\ 'VK_MEDIA_PLAY_PAUSE' : 179, -\ 'VK_MEDIA_PREV_TRACK' : 177, -\ 'VK_MENU' : 18, -\ 'VK_MODECHANGE' : 31, -\ 'VK_MULTIPLY' : 106, -\ 'VK_NEXT' : 34, -\ 'VK_NONAME' : 252, -\ 'VK_NONCONVERT' : 29, -\ 'VK_NUMLOCK' : 144, -\ 'VK_NUMPAD0' : 96, -\ 'VK_NUMPAD1' : 97, -\ 'VK_NUMPAD2' : 98, -\ 'VK_NUMPAD3' : 99, -\ 'VK_NUMPAD4' : 100, -\ 'VK_NUMPAD5' : 101, -\ 'VK_NUMPAD6' : 102, -\ 'VK_NUMPAD7' : 103, -\ 'VK_NUMPAD8' : 104, -\ 'VK_NUMPAD9' : 105, -\ 'VK_OEM_CLEAR' : 254, -\ 'VK_PA1' : 253, -\ 'VK_PAUSE' : 19, -\ 'VK_PLAY' : 250, -\ 'VK_PRINT' : 42, -\ 'VK_PRIOR' : 33, -\ 'VK_PROCESSKEY' : 229, -\ 'VK_RBUTTON' : 2, -\ 'VK_RCONTROL' : 163, -\ 'VK_RETURN' : 13, -\ 'VK_RIGHT' : 39, -\ 'VK_RIGHT_CTL' : '39;1024', -\ 'VK_RMENU' : 165, -\ 'VK_RSHIFT' : 161, -\ 'VK_RWIN' : 92, -\ 'VK_SCROLL' : 145, -\ 'VK_SELECT' : 41, -\ 'VK_SEPARATOR' : 108, -\ 'VK_SHIFT' : 16, -\ 'VK_SNAPSHOT' : 44, -\ 'VK_SPACE' : 32, -\ 'VK_SUBTRACT' : 109, -\ 'VK_TAB' : 9, -\ 'VK_UP' : 38, -\ 'VK_UP_CTL' : '38;1024', -\ 'VK_VOLUME_DOWN' : 174, -\ 'VK_VOLUME_MUTE' : 173, -\ 'VK_VOLUME_UP' : 175, -\ 'VK_XBUTTON1' : 5, -\ 'VK_XBUTTON2' : 6, -\ 'VK_ZOOM' : 251 -\ } -" }}} - -" ********************************************************************************************************** -" **** ACTUAL CONQUE FUNCTIONS! *************************************************************************** -" ********************************************************************************************************** - -" {{{ - -" launch conque -function! conque_term#open(...) "{{{ - let command = get(a:000, 0, '') - let vim_startup_commands = get(a:000, 1, []) - let return_to_current = get(a:000, 2, 0) - let is_buffer = get(a:000, 3, 1) - - " dependency check - if !conque_term#dependency_check() - return 0 - endif - - " switch to buffer if needed - if is_buffer && return_to_current - let save_sb = &switchbuf - sil set switchbuf=usetab - let current_buffer = bufname("%") - endif - - " bare minimum validation - if s:py == '' - echohl WarningMsg | echomsg "Conque requires the Python interface to be installed. See :help ConqueTerm for more information." | echohl None - return 0 - endif - if empty(command) - echohl WarningMsg | echomsg "Invalid usage: no program path given. Use :ConqueTerm YOUR PROGRAM, e.g. :ConqueTerm ipython" | echohl None - return 0 - else - let cmd_args = split(command, '[^\\]\@<=\s') - let cmd_args[0] = substitute(cmd_args[0], '\\ ', ' ', 'g') - if !executable(cmd_args[0]) - echohl WarningMsg | echomsg "Not an executable: " . cmd_args[0] | echohl None - return 0 - endif - endif - - " initialize global identifiers - let g:ConqueTerm_Idx += 1 - let g:ConqueTerm_Var = 'ConqueTerm_' . g:ConqueTerm_Idx - let g:ConqueTerm_BufName = substitute(command, ' ', '\\ ', 'g') . "\\ -\\ " . g:ConqueTerm_Idx - - " initialize global mappings if needed - call conque_term#init() - - " set Vim buffer window options - if is_buffer - call conque_term#set_buffer_settings(command, vim_startup_commands) - - let b:ConqueTerm_Idx = g:ConqueTerm_Idx - let b:ConqueTerm_Var = g:ConqueTerm_Var - endif - - " save terminal instance - let t_obj = conque_term#create_terminal_object(g:ConqueTerm_Idx, is_buffer, g:ConqueTerm_BufName, command) - let g:ConqueTerm_Terminals[g:ConqueTerm_Idx] = t_obj - - " required for session support - let g:ConqueTerm_TerminalsString = string(g:ConqueTerm_Terminals) - - " open command - try - let options = {} - let options["TERM"] = g:ConqueTerm_TERM - let options["CODE_PAGE"] = g:ConqueTerm_CodePage - let options["color"] = g:ConqueTerm_Color - let options["offset"] = 0 " g:ConqueTerm_StartMessages * 10 - - if s:platform == 'unix' - execute s:py . ' ' . g:ConqueTerm_Var . ' = Conque()' - execute s:py . ' ' . g:ConqueTerm_Var . ".open()" - else - " find python.exe and communicator - let py_exe = conque_term#find_python_exe() - let py_vim = s:scriptdirpy . 'conque_sole_communicator.py' - execute s:py . ' ' . g:ConqueTerm_Var . ' = ConqueSole()' - execute s:py . ' ' . g:ConqueTerm_Var . ".open()" - - if g:ConqueTerm_ColorMode == 'conceal' - call conque_term#init_conceal_color() - endif - endif - catch - echohl WarningMsg | echomsg "An error occurred: " . command | echohl None - return 0 - endtry - - " set key mappings and auto commands - if is_buffer - call conque_term#set_mappings('start') - endif - - " call user defined functions - call conque_term#call_hooks('after_startup', t_obj) - - " switch to buffer if needed - if is_buffer && return_to_current - sil exe ":sb " . current_buffer - sil exe ":set switchbuf=" . save_sb - elseif is_buffer - startinsert! - endif - - return t_obj - -endfunction "}}} - -" open(), but no buffer -function! conque_term#subprocess(command) " {{{ - - let t_obj = conque_term#open(a:command, [], 0, 0) - if !exists('b:ConqueTerm_Var') - call conque_term#on_blur() - sil exe s:py . ' ' . g:ConqueTerm_Var . '.idle()' - endif - return t_obj - -endfunction " }}} - -" set buffer options -function! conque_term#set_buffer_settings(command, vim_startup_commands) "{{{ - - " optional hooks to execute, e.g. 'split' - for h in a:vim_startup_commands - sil exe h - endfor - sil exe 'edit ++enc=utf-8 ' . g:ConqueTerm_BufName - - " buffer settings - setlocal fileencoding=utf-8 " file encoding, even tho there's no file - setlocal nopaste " conque won't work in paste mode - setlocal buftype=nofile " this buffer is not a file, you can't save it - setlocal nonumber " hide line numbers - if v:version >= 703 - setlocal norelativenumber " hide relative line numbers (VIM >= 7.3) - endif - setlocal foldcolumn=0 " reasonable left margin - setlocal nowrap " default to no wrap (esp with MySQL) - setlocal noswapfile " don't bother creating a .swp file - setlocal scrolloff=0 " don't use buffer lines. it makes the 'clear' command not work as expected - setlocal sidescrolloff=0 " don't use buffer lines. it makes the 'clear' command not work as expected - setlocal sidescroll=1 " don't use buffer lines. it makes the 'clear' command not work as expected - setlocal foldmethod=manual " don't fold on {{{}}} and stuff - setlocal bufhidden=hide " when buffer is no longer displayed, don't wipe it out - setlocal noreadonly " this is not actually a readonly buffer - if v:version >= 703 - setlocal conceallevel=3 - setlocal concealcursor=nic - endif - if g:ConqueTerm_ReadUnfocused - set cpoptions+=I " Don't remove autoindent when moving cursor up and down - endif - setfiletype conque_term " useful - sil exe "setlocal syntax=" . g:ConqueTerm_Syntax - - " temporary global settings go in here - call conque_term#on_focus(1) - -endfunction " }}} - -" send normal character key press to terminal -function! conque_term#key_press() "{{{ - sil exe s:py . ' ' . b:ConqueTerm_Var . ".write_buffered_ord(" . char2nr(v:char) . ")" - sil let v:char = '' -endfunction " }}} - -" set key mappings and auto commands -function! conque_term#set_mappings(action) "{{{ - - " set action {{{ - if a:action == 'toggle' - if exists('b:conque_on') && b:conque_on == 1 - let l:action = 'stop' - echohl WarningMsg | echomsg "Terminal is paused" | echohl None - else - let l:action = 'start' - echohl WarningMsg | echomsg "Terminal is resumed" | echohl None - endif - else - let l:action = a:action - endif - - " if mappings are being removed, add 'un' - let map_modifier = 'nore' - if l:action == 'stop' - let map_modifier = 'un' - endif - " }}} - - " auto commands {{{ - if l:action == 'stop' - sil exe 'autocmd! ' . b:ConqueTerm_Var - - else - sil exe 'augroup ' . b:ConqueTerm_Var - - " handle unexpected closing of shell, passes HUP to parent and all child processes - sil exe 'autocmd ' . b:ConqueTerm_Var . ' BufDelete call g:ConqueTerm_Terminals[' . b:ConqueTerm_Idx . '].close()' - sil exe 'autocmd ' . b:ConqueTerm_Var . ' BufUnload call g:ConqueTerm_Terminals[' . b:ConqueTerm_Idx . '].close()' - - " check for resized/scrolled buffer when entering buffer - sil exe 'autocmd ' . b:ConqueTerm_Var . ' BufEnter ' . s:py . ' ' . b:ConqueTerm_Var . '.update_window_size()' - sil exe 'autocmd ' . b:ConqueTerm_Var . ' VimResized ' . s:py . ' ' . b:ConqueTerm_Var . '.update_window_size()' - - " set/reset updatetime on entering/exiting buffer - sil exe 'autocmd ' . b:ConqueTerm_Var . ' BufEnter call conque_term#on_focus()' - sil exe 'autocmd ' . b:ConqueTerm_Var . ' BufLeave call conque_term#on_blur()' - - " reposition cursor when going into insert mode - sil exe 'autocmd ' . b:ConqueTerm_Var . ' InsertEnter ' . s:py . ' ' . b:ConqueTerm_Var . '.insert_enter()' - - " poll for more output - sil exe 'autocmd ' . b:ConqueTerm_Var . ' CursorHoldI ' . s:py . ' ' . b:ConqueTerm_Var . '.auto_read()' - endif - " }}} - - " map ASCII 1-31 {{{ - for c in range(1, 31) - " - if c == 27 || c == 3 - continue - endif - if l:action == 'start' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_ord(' . c . ')' - else - sil exe 'i' . map_modifier . 'map ' - endif - endfor - " bonus mapping: send in normal mode to terminal as well for panic interrupts - if l:action == 'start' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_ord(3)' - sil exe 'n' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_ord(3)' - else - sil exe 'i' . map_modifier . 'map ' - sil exe 'n' . map_modifier . 'map ' - endif - - " leave insert mode - if !exists('g:ConqueTerm_EscKey') || g:ConqueTerm_EscKey == '' - " use to send to terminal - if l:action == 'start' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_ord(27)' - else - sil exe 'i' . map_modifier . 'map ' - endif - else - " use to send to terminal - if l:action == 'start' - sil exe 'i' . map_modifier . 'map ' . g:ConqueTerm_EscKey . ' ' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_ord(27)' - else - sil exe 'i' . map_modifier . 'map ' . g:ConqueTerm_EscKey - sil exe 'i' . map_modifier . 'map ' - endif - endif - - " Map in insert mode - if exists('g:ConqueTerm_CWInsert') && g:ConqueTerm_CWInsert == 1 - inoremap - endif - " }}} - - " map 33 and beyond {{{ - if exists('##InsertCharPre') && g:ConqueTerm_InsertCharPre == 1 - if l:action == 'start' - autocmd InsertCharPre call conque_term#key_press() - else - autocmd! InsertCharPre - endif - else - for i in range(33, 127) - " - if i == 124 - if l:action == 'start' - sil exe "i" . map_modifier . "map :" . s:py . ' ' . b:ConqueTerm_Var . ".write_ord(124)" - else - sil exe "i" . map_modifier . "map " - endif - continue - endif - if l:action == 'start' - sil exe "i" . map_modifier . "map " . nr2char(i) . " :" . s:py . ' ' . b:ConqueTerm_Var . ".write_ord(" . i . ")" - else - sil exe "i" . map_modifier . "map " . nr2char(i) - endif - endfor - endif - " }}} - - " Special keys {{{ - if l:action == 'start' - if s:platform == 'unix' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x08"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u(" "))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x08"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u(" "))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[A"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[B"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[C"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[D"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1bOH"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1bOF"))' - else - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x08"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u(" "))' - - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x08"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u(" "))' - - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_UP . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_DOWN . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_RIGHT . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_LEFT . ')' - - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk("' . s:windows_vk.VK_UP_CTL . '")' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk("' . s:windows_vk.VK_DOWN_CTL . '")' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk("' . s:windows_vk.VK_RIGHT_CTL . '")' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk("' . s:windows_vk.VK_LEFT_CTL . '")' - - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_DELETE . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_HOME . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_END . ')' - endif - else - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - endif - " }}} - - " keys {{{ - if g:ConqueTerm_SendFunctionKeys - if l:action == 'start' - if s:platform == 'unix' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[11~"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[12~"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("1b[13~"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[14~"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[15~"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[17~"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[18~"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[19~"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[20~"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[21~"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[23~"))' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write(u("\x1b[24~"))' - else - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_F1 . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_F2 . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_F3 . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_F4 . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_F5 . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_F6 . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_F7 . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_F8 . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_F9 . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_F10 . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_F11 . ')' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_vk(' . s:windows_vk.VK_F12 . ')' - endif - else - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - endif - endif - " }}} - - " various global mappings {{{ - " don't overwrite existing mappings - if l:action == 'start' - if maparg(g:ConqueTerm_SendVisKey, 'v') == '' - sil exe 'v' . map_modifier . 'map ' . g:ConqueTerm_SendVisKey . ' :call conque_term#send_selected(visualmode())' - endif - if maparg(g:ConqueTerm_SendFileKey, 'n') == '' - sil exe 'n' . map_modifier . 'map ' . g:ConqueTerm_SendFileKey . ' :call conque_term#send_file()' - endif - endif - " }}} - - " remap paste keys {{{ - if l:action == 'start' - sil exe 'n' . map_modifier . 'map p :' . s:py . ' ' . b:ConqueTerm_Var . '.write_expr("@@")a' - sil exe 'n' . map_modifier . 'map P :' . s:py . ' ' . b:ConqueTerm_Var . '.write_expr("@@")a' - sil exe 'n' . map_modifier . 'map ]p :' . s:py . ' ' . b:ConqueTerm_Var . '.write_expr("@@")a' - sil exe 'n' . map_modifier . 'map [p :' . s:py . ' ' . b:ConqueTerm_Var . '.write_expr("@@")a' - else - sil exe 'n' . map_modifier . 'map p' - sil exe 'n' . map_modifier . 'map P' - sil exe 'n' . map_modifier . 'map ]p' - sil exe 'n' . map_modifier . 'map [p' - endif - if has('gui_running') == 1 - if l:action == 'start' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_expr("@+")a' - sil exe 'i' . map_modifier . 'map :' . s:py . ' ' . b:ConqueTerm_Var . '.write_expr("@+")a' - else - sil exe 'i' . map_modifier . 'map ' - sil exe 'i' . map_modifier . 'map ' - endif - endif - " }}} - - " disable other normal mode keys which insert text {{{ - if l:action == 'start' - sil exe 'n' . map_modifier . 'map r :echo "Replace mode disabled in shell."' - sil exe 'n' . map_modifier . 'map R :echo "Replace mode disabled in shell."' - sil exe 'n' . map_modifier . 'map c :echo "Change mode disabled in shell."' - sil exe 'n' . map_modifier . 'map C :echo "Change mode disabled in shell."' - sil exe 'n' . map_modifier . 'map s :echo "Change mode disabled in shell."' - sil exe 'n' . map_modifier . 'map S :echo "Change mode disabled in shell."' - else - sil exe 'n' . map_modifier . 'map r' - sil exe 'n' . map_modifier . 'map R' - sil exe 'n' . map_modifier . 'map c' - sil exe 'n' . map_modifier . 'map C' - sil exe 'n' . map_modifier . 'map s' - sil exe 'n' . map_modifier . 'map S' - endif - " }}} - - " set conque as on or off {{{ - if l:action == 'start' - let b:conque_on = 1 - else - let b:conque_on = 0 - endif - " }}} - - " map command to toggle terminal key mappings {{{ - if a:action == 'start' - sil exe 'nnoremap ' . g:ConqueTerm_ToggleKey . ' :call conque_term#set_mappings("toggle")' - endif - " }}} - - " call user defined functions - if l:action == 'start' - call conque_term#call_hooks('after_keymap', conque_term#get_instance()) - endif - -endfunction " }}} - -" Initialize global mappings. Should only be called once per Vim session -function! conque_term#init() " {{{ - - if s:initialized == 1 - return - endif - - augroup ConqueTerm - - " abort any remaining running terminals when Vim exits - autocmd ConqueTerm VimLeave * call conque_term#close_all() - - " read more output when this isn't the current buffer - if g:ConqueTerm_ReadUnfocused == 1 - autocmd ConqueTerm CursorHold * call conque_term#read_all(0) - endif - - let s:initialized = 1 - -endfunction " }}} - -" read from all known conque buffers -function! conque_term#read_all(insert_mode) "{{{ - - for i in range(1, g:ConqueTerm_Idx) - try - if !g:ConqueTerm_Terminals[i].active - continue - endif - - let output = g:ConqueTerm_Terminals[i].read(1) - - if !g:ConqueTerm_Terminals[i].is_buffer && exists('*g:ConqueTerm_Terminals[i].callback') - call g:ConqueTerm_Terminals[i].callback(output) - endif - catch - " probably a deleted buffer - endtry - endfor - - " restart updatetime - if a:insert_mode - "call feedkeys("\f\e", "n") - let p = getpos('.') - if p[1] == 1 - sil exe 'call feedkeys("\\", "n")' - else - sil exe 'call feedkeys("\\", "n")' - endif - call setpos('.', p) - else - call feedkeys("f\e", "n") - endif - -endfunction "}}} - -" close all subprocesses -function! conque_term#close_all() "{{{ - - for i in range(1, g:ConqueTerm_Idx) - try - call g:ConqueTerm_Terminals[i].close() - catch - " probably a deleted buffer - endtry - endfor - -endfunction "}}} - -" gets called when user enters conque buffer. -" Useful for making temp changes to global config -function! conque_term#on_focus(...) " {{{ - - let startup = get(a:000, 0, 0) - - " Disable NeoComplCache. It has global hooks on CursorHold and CursorMoved :-/ - let s:NeoComplCache_WasEnabled = exists(':NeoComplCacheLock') - if s:NeoComplCache_WasEnabled == 2 - NeoComplCacheLock - endif - - if g:ConqueTerm_ReadUnfocused == 1 - autocmd! ConqueTerm CursorHoldI * - autocmd! ConqueTerm CursorHold * - endif - - " set poll interval to 50ms - set updatetime=50 - - " resume subprocess fast polling - if startup == 0 && exists('b:ConqueTerm_Var') - sil exe s:py . ' ' . g:ConqueTerm_Var . '.resume()' - endif - - " call user defined functions - if startup == 0 - call conque_term#call_hooks('buffer_enter', conque_term#get_instance()) - endif - - " if configured, go into insert mode - if g:ConqueTerm_InsertOnEnter == 1 - startinsert! - endif - -endfunction " }}} - -" gets called when user exits conque buffer. -" Useful for resetting changes to global config -function! conque_term#on_blur() " {{{ - " re-enable NeoComplCache if needed - if exists('s:NeoComplCache_WasEnabled') && exists(':NeoComplCacheUnlock') && s:NeoComplCache_WasEnabled == 2 - NeoComplCacheUnlock - endif - - " turn off subprocess fast polling - if exists('b:ConqueTerm_Var') - sil exe s:py . ' ' . b:ConqueTerm_Var . '.idle()' - endif - - " reset poll interval - if g:ConqueTerm_ReadUnfocused == 1 - set updatetime=1000 - autocmd ConqueTerm CursorHoldI * call conque_term#read_all(1) - autocmd ConqueTerm CursorHold * call conque_term#read_all(0) - elseif exists('s:save_updatetime') - exe 'set updatetime=' . s:save_updatetime - else - set updatetime=2000 - endif - - " call user defined functions - call conque_term#call_hooks('buffer_leave', conque_term#get_instance()) - -endfunction " }}} - -" bell event (^G) -function! conque_term#bell() " {{{ - echohl WarningMsg | echomsg "BELL!" | echohl None -endfunction " }}} - -" register function to be called at conque events -function! conque_term#register_function(event, function_name) " {{{ - - if !has_key(s:hooks, a:event) - echomsg 'No such event: ' . a:event - return - endif - - if !exists('*' . a:function_name) - echomsg 'No such function: ' . a:function_name) - return - endif - - " register the function - call add(s:hooks[a:event], function(a:function_name)) - -endfunction " }}} - -" call hooks for an event -function! conque_term#call_hooks(event, t_obj) " {{{ - - for Fu in s:hooks[a:event] - call Fu(a:t_obj) - endfor - -endfunction " }}} - -" }}} - -" ********************************************************************************************************** -" **** Windows only functions ****************************************************************************** -" ********************************************************************************************************** - -" {{{ - -" find python.exe in windows -function! conque_term#find_python_exe() " {{{ - - " first check configuration for custom value - if g:ConqueTerm_PyExe != '' && executable(g:ConqueTerm_PyExe) - return g:ConqueTerm_PyExe - endif - - let sys_paths = split($PATH, ';') - - " get exact python version - sil exe ':' . s:py . ' import sys, vim' - sil exe ':' . s:py . ' vim.command("let g:ConqueTerm_PyVersion = " + str(sys.version_info[0]) + str(sys.version_info[1]))' - - " ... and add to path list - call add(sys_paths, 'C:\Python' . g:ConqueTerm_PyVersion) - call reverse(sys_paths) - - " check if python.exe is in paths - for path in sys_paths - let cand = path . '\' . 'python.exe' - if executable(cand) - return cand - endif - endfor - - echohl WarningMsg | echomsg "Unable to find python.exe, see :help ConqueTerm_PythonExe for more information" | echohl None - - return '' - -endfunction " }}} - -" initialize concealed colors -function! conque_term#init_conceal_color() " {{{ - - highlight link ConqueCCBG Normal - - " foreground colors, low intensity - syn region ConqueCCF000 matchgroup=ConqueConceal start="\esf000;" end="\eef000;" concealends contains=ConqueCCBG - syn region ConqueCCF00c matchgroup=ConqueConceal start="\esf00c;" end="\eef00c;" concealends contains=ConqueCCBG - syn region ConqueCCF0c0 matchgroup=ConqueConceal start="\esf0c0;" end="\eef0c0;" concealends contains=ConqueCCBG - syn region ConqueCCF0cc matchgroup=ConqueConceal start="\esf0cc;" end="\eef0cc;" concealends contains=ConqueCCBG - syn region ConqueCCFc00 matchgroup=ConqueConceal start="\esfc00;" end="\eefc00;" concealends contains=ConqueCCBG - syn region ConqueCCFc0c matchgroup=ConqueConceal start="\esfc0c;" end="\eefc0c;" concealends contains=ConqueCCBG - syn region ConqueCCFcc0 matchgroup=ConqueConceal start="\esfcc0;" end="\eefcc0;" concealends contains=ConqueCCBG - syn region ConqueCCFccc matchgroup=ConqueConceal start="\esfccc;" end="\eefccc;" concealends contains=ConqueCCBG - - " foreground colors, high intensity - syn region ConqueCCF000 matchgroup=ConqueConceal start="\esf000;" end="\eef000;" concealends contains=ConqueCCBG - syn region ConqueCCF00f matchgroup=ConqueConceal start="\esf00f;" end="\eef00f;" concealends contains=ConqueCCBG - syn region ConqueCCF0f0 matchgroup=ConqueConceal start="\esf0f0;" end="\eef0f0;" concealends contains=ConqueCCBG - syn region ConqueCCF0ff matchgroup=ConqueConceal start="\esf0ff;" end="\eef0ff;" concealends contains=ConqueCCBG - syn region ConqueCCFf00 matchgroup=ConqueConceal start="\esff00;" end="\eeff00;" concealends contains=ConqueCCBG - syn region ConqueCCFf0f matchgroup=ConqueConceal start="\esff0f;" end="\eeff0f;" concealends contains=ConqueCCBG - syn region ConqueCCFff0 matchgroup=ConqueConceal start="\esfff0;" end="\eefff0;" concealends contains=ConqueCCBG - syn region ConqueCCFfff matchgroup=ConqueConceal start="\esffff;" end="\eeffff;" concealends contains=ConqueCCBG - - " background colors, low intensity - syn region ConqueCCB000 matchgroup=ConqueCCBG start="\esb000;" end="\eeb000;" concealends - syn region ConqueCCB00c matchgroup=ConqueCCBG start="\esb00c;" end="\eeb00c;" concealends - syn region ConqueCCB0c0 matchgroup=ConqueCCBG start="\esb0c0;" end="\eeb0c0;" concealends - syn region ConqueCCB0cc matchgroup=ConqueCCBG start="\esb0cc;" end="\eeb0cc;" concealends - syn region ConqueCCBc00 matchgroup=ConqueCCBG start="\esbc00;" end="\eebc00;" concealends - syn region ConqueCCBc0c matchgroup=ConqueCCBG start="\esbc0c;" end="\eebc0c;" concealends - syn region ConqueCCBcc0 matchgroup=ConqueCCBG start="\esbcc0;" end="\eebcc0;" concealends - syn region ConqueCCBccc matchgroup=ConqueCCBG start="\esbccc;" end="\eebccc;" concealends - - " background colors, high intensity - syn region ConqueCCB000 matchgroup=ConqueCCBG start="\esb000;" end="\eeb000;" concealends - syn region ConqueCCB00f matchgroup=ConqueCCBG start="\esb00f;" end="\eeb00f;" concealends - syn region ConqueCCB0f0 matchgroup=ConqueCCBG start="\esb0f0;" end="\eeb0f0;" concealends - syn region ConqueCCB0ff matchgroup=ConqueCCBG start="\esb0ff;" end="\eeb0ff;" concealends - syn region ConqueCCBf00 matchgroup=ConqueCCBG start="\esbf00;" end="\eebf00;" concealends - syn region ConqueCCBf0f matchgroup=ConqueCCBG start="\esbf0f;" end="\eebf0f;" concealends - syn region ConqueCCBff0 matchgroup=ConqueCCBG start="\esbff0;" end="\eebff0;" concealends - syn region ConqueCCBfff matchgroup=ConqueCCBG start="\esbfff;" end="\eebfff;" concealends - - - """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" - """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" - - "highlight link ConqueCCConceal Error - - " foreground colors, low intensity - highlight ConqueCCF000 guifg=#000000 - highlight ConqueCCF00c guifg=#0000cc - highlight ConqueCCF0c0 guifg=#00cc00 - highlight ConqueCCF0cc guifg=#00cccc - highlight ConqueCCFc00 guifg=#cc0000 - highlight ConqueCCFc0c guifg=#cc00cc - highlight ConqueCCFcc0 guifg=#cccc00 - highlight ConqueCCFccc guifg=#cccccc - - " foreground colors, high intensity - highlight ConqueCCF000 guifg=#000000 - highlight ConqueCCF00f guifg=#0000ff - highlight ConqueCCF0f0 guifg=#00ff00 - highlight ConqueCCF0ff guifg=#00ffff - highlight ConqueCCFf00 guifg=#ff0000 - highlight ConqueCCFf0f guifg=#ff00ff - highlight ConqueCCFff0 guifg=#ffff00 - highlight ConqueCCFfff guifg=#ffffff - - " background colors, low intensity - highlight ConqueCCB000 guibg=#000000 - highlight ConqueCCB00c guibg=#0000cc - highlight ConqueCCB0c0 guibg=#00cc00 - highlight ConqueCCB0cc guibg=#00cccc - highlight ConqueCCBc00 guibg=#cc0000 - highlight ConqueCCBc0c guibg=#cc00cc - highlight ConqueCCBcc0 guibg=#cccc00 - highlight ConqueCCBccc guibg=#cccccc - - " background colors, high intensity - highlight ConqueCCB000 guibg=#000000 - highlight ConqueCCB00f guibg=#0000ff - highlight ConqueCCB0f0 guibg=#00ff00 - highlight ConqueCCB0ff guibg=#00ffff - highlight ConqueCCBf00 guibg=#ff0000 - highlight ConqueCCBf0f guibg=#ff00ff - highlight ConqueCCBff0 guibg=#ffff00 - highlight ConqueCCBfff guibg=#ffffff - - " background colors, low intensity - highlight link ConqueCCB000 ConqueCCBG - highlight link ConqueCCB00c ConqueCCBG - highlight link ConqueCCB0c0 ConqueCCBG - highlight link ConqueCCB0cc ConqueCCBG - highlight link ConqueCCBc00 ConqueCCBG - highlight link ConqueCCBc0c ConqueCCBG - highlight link ConqueCCBcc0 ConqueCCBG - highlight link ConqueCCBccc ConqueCCBG - - " background colors, high intensity - highlight link ConqueCCB000 ConqueCCBG - highlight link ConqueCCB00f ConqueCCBG - highlight link ConqueCCB0f0 ConqueCCBG - highlight link ConqueCCB0ff ConqueCCBG - highlight link ConqueCCBf00 ConqueCCBG - highlight link ConqueCCBf0f ConqueCCBG - highlight link ConqueCCBff0 ConqueCCBG - highlight link ConqueCCBfff ConqueCCBG - -endfunction " }}} - -" }}} - -" ********************************************************************************************************** -" **** Add-on features ************************************************************************************* -" ********************************************************************************************************** - -" {{{ - -" send selected text from another buffer -function! conque_term#send_selected(type) "{{{ - - " get most recent/relevant terminal - let term = conque_term#get_instance() - - " shove visual text into @@ register - let reg_save = @@ - sil exe "normal! `<" . a:type . "`>y" - let @@ = substitute(@@, '^[\r\n]*', '', '') - let @@ = substitute(@@, '[\r\n]*$', '', '') - - " go to terminal buffer - call term.focus() - - " execute yanked text - call term.write(@@) - - " reset original values - let @@ = reg_save - - " scroll buffer left - startinsert! - normal! 0zH - -endfunction "}}} - -function! conque_term#send_file() "{{{ - - let file_lines = readfile(expand('%:p')) - if type(file_lines) == 3 && len(file_lines) > 0 - let term = conque_term#get_instance() - call term.focus() - - for line in file_lines - call term.writeln(line) - endfor - else - echomsg 'Could not read file: ' . expand('%:p') - endif - -endfunction "}}} - - -function! conque_term#exec_file() "{{{ - - let current_file = expand('%:p') - if !executable(current_file) - echomsg "Could not run " . current_file . ". Not an executable." - return - endif - exe ':ConqueTermSplit ' . current_file - -endfunction "}}} - - -" called on SessionLoadPost event -function! conque_term#resume_session() " {{{ - if g:ConqueTerm_SessionSupport == 1 - - " make sure terminals exist - if !exists('s:saved_terminals') || type(s:saved_terminals) != 4 - return - endif - - " rebuild terminals - for idx in keys(s:saved_terminals) - - " don't recreate inactive terminals - if s:saved_terminals[idx].active == 0 - continue - endif - - " check we're in the right buffer - let bufname = substitute(s:saved_terminals[idx].buffer_name, '\', '', 'g') - if bufname != bufname("%") - continue - endif - - " reopen command - call conque_term#open(s:saved_terminals[idx].command) - - return - endfor - - endif -endfunction " }}} - -" }}} - -" ********************************************************************************************************** -" **** "API" functions ************************************************************************************* -" ********************************************************************************************************** - -" See doc/conque_term.txt for full documentation {{{ - -" Write to a conque terminal buffer -function! s:term_obj.write(...) dict " {{{ - - let text = get(a:000, 0, '') - let jump_to_buffer = get(a:000, 1, 0) - - " if we're not in terminal buffer, pass flag to not position the cursor - sil exe s:py . ' ' . self.var . '.write_expr("text", False, False)' - - " move cursor to conque buffer - if jump_to_buffer - call self.focus() - endif - -endfunction " }}} - -" same as write() but adds a newline -function! s:term_obj.writeln(...) dict " {{{ - - let text = get(a:000, 0, '') - let jump_to_buffer = get(a:000, 1, 0) - - call self.write(text . "\r", jump_to_buffer) - -endfunction " }}} - -" move cursor to terminal buffer -function! s:term_obj.focus() dict " {{{ - - let save_sb = &switchbuf - sil set switchbuf=usetab - exe 'sb ' . self.buffer_name - sil exe ":set switchbuf=" . save_sb - startinsert! - -endfunction " }}} - -" read from terminal buffer and return string -function! s:term_obj.read(...) dict " {{{ - - let read_time = get(a:000, 0, 1) - let update_buffer = get(a:000, 1, self.is_buffer) - - if update_buffer - let up_py = 'True' - else - let up_py = 'False' - endif - - " figure out if we're in the buffer we're updating - if exists('b:ConqueTerm_Var') && b:ConqueTerm_Var == self.var - let in_buffer = 1 - else - let in_buffer = 0 - endif - - let output = '' - - " read! - sil exec s:py . " conque_tmp = " . self.var . ".read(timeout = " . read_time . ", set_cursor = False, return_output = True, update_buffer = " . up_py . ")" - - " ftw! - try - let pycode = "\nif conque_tmp:\n conque_tmp = re.sub('\\\\\\\\', '\\\\\\\\\\\\\\\\', conque_tmp)\n conque_tmp = re.sub('\"', '\\\\\\\\\"', conque_tmp)\n vim.command('let output = \"' + conque_tmp + '\"')\n" - sil exec s:py . pycode - catch - " d'oh - endtry - - return output - -endfunction " }}} - -" set output callback -function! s:term_obj.set_callback(callback_func) dict " {{{ - - let g:ConqueTerm_Terminals[self.idx].callback = function(a:callback_func) - -endfunction " }}} - -" close subprocess with ABORT signal -function! s:term_obj.close() dict " {{{ - - " kill process - try - sil exe s:py . ' ' . self.var . '.abort()' - catch - " probably already dead - endtry - - " delete buffer if option is set - try - if self.is_buffer - call conque_term#set_mappings('stop') - if exists('g:ConqueTerm_CloseOnEnd') && g:ConqueTerm_CloseOnEnd - sil exe 'bwipeout! ' . self.buffer_name - stopinsert! - endif - endif - catch - endtry - - " mark ourselves as inactive - let self.active = 0 - - " rebuild session options - let g:ConqueTerm_TerminalsString = string(g:ConqueTerm_Terminals) - -endfunction " }}} - -" create a new terminal object -function! conque_term#create_terminal_object(...) " {{{ - - " find conque buffer to update - let buf_num = get(a:000, 0, 0) - if buf_num > 0 - let pvar = 'ConqueTerm_' . buf_num - elseif exists('b:ConqueTerm_Var') - let pvar = b:ConqueTerm_Var - let buf_num = b:ConqueTerm_Idx - else - let pvar = g:ConqueTerm_Var - let buf_num = g:ConqueTerm_Idx - endif - - " is ther a buffer? - let is_buffer = get(a:000, 1, 1) - - " the buffer name - let bname = get(a:000, 2, '') - - " the command - let command = get(a:000, 3, '') - - " parse out the program name (not perfect) - let arg_split = split(command, '[^\\]\@<=\s') - let arg_split[0] = substitute(arg_split[0], '\\ ', ' ', 'g') - let slash_split = split(arg_split[0], '[/\\]') - let prg_name = substitute(slash_split[-1], '\(.*\)\..*', '\1', '') - - let l:t_obj = copy(s:term_obj) - let l:t_obj.is_buffer = is_buffer - let l:t_obj.idx = buf_num - let l:t_obj.buffer_name = bname - let l:t_obj.var = pvar - let l:t_obj.command = command - let l:t_obj.program_name = prg_name - - return l:t_obj - -endfunction " }}} - -" get an existing terminal instance -function! conque_term#get_instance(...) " {{{ - - " find conque buffer to update - let buf_num = get(a:000, 0, 0) - - if exists('g:ConqueTerm_Terminals[buf_num]') - - elseif exists('b:ConqueTerm_Var') - let buf_num = b:ConqueTerm_Idx - else - let buf_num = g:ConqueTerm_Idx - endif - - return g:ConqueTerm_Terminals[buf_num] - -endfunction " }}} - -" }}} - -" ********************************************************************************************************** -" **** PYTHON ********************************************************************************************** -" ********************************************************************************************************** - -function! conque_term#load_python() " {{{ - - exec s:py . "file " . s:scriptdirpy . "conque_globals.py" - exec s:py . "file " . s:scriptdirpy . "conque.py" - if s:platform == 'windows' - exec s:py . "file " . s:scriptdirpy . "conque_win32_util.py" - exec s:py . "file " . s:scriptdirpy . "conque_sole_shared_memory.py" - exec s:py . "file " . s:scriptdirpy . "conque_sole.py" - exec s:py . "file " . s:scriptdirpy . "conque_sole_wrapper.py" - else - exec s:py . "file " . s:scriptdirpy . "conque_screen.py" - exec s:py . "file " . s:scriptdirpy . "conque_subprocess.py" - endif - -endfunction " }}} - -" vim:foldmethod=marker diff --git a/vim/autoload/conque_term/conque.py b/vim/autoload/conque_term/conque.py deleted file mode 100644 index ed294fa..0000000 --- a/vim/autoload/conque_term/conque.py +++ /dev/null @@ -1,1152 +0,0 @@ -# FILE: autoload/conque_term/conque.py -# AUTHOR: Nico Raffo -# WEBSITE: http://conque.googlecode.com -# MODIFIED: 2011-09-02 -# VERSION: 2.3, for Vim 7.0 -# LICENSE: -# Conque - Vim terminal/console emulator -# Copyright (C) 2009-2011 Nico Raffo -# -# MIT License -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -""" -Vim terminal emulator. - -This class is the main interface between Vim and the terminal application. It -handles both updating the Vim buffer with new output and accepting new keyboard -input from the Vim user. - -Although this class was originally designed for a Unix terminal environment, it -has been extended by the ConqueSole class for Windows. - -Usage: - term = Conque() - term.open('/bin/bash', {'TERM': 'vt100'}) - term.write("ls -lha\r") - term.read() - term.close() -""" - -import vim -import re -import math - - -class Conque: - - # screen object - screen = None - - # subprocess object - proc = None - - # terminal dimensions and scrolling region - columns = 80 # same as $COLUMNS - lines = 24 # same as $LINES - working_columns = 80 # can be changed by CSI ? 3 l/h - working_lines = 24 # can be changed by CSI r - - # top/bottom of the scroll region - top = 1 # relative to top of screen - bottom = 24 # relative to top of screen - - # cursor position - l = 1 # current cursor line - c = 1 # current cursor column - - # autowrap mode - autowrap = True - - # absolute coordinate mode - absolute_coords = True - - # tabstop positions - tabstops = [] - - # enable colors - enable_colors = True - - # color changes - color_changes = {} - - # color history - color_history = {} - - # color highlight cache - highlight_groups = {} - - # prune terminal colors - color_pruning = True - - # don't wrap table output - unwrap_tables = True - - # wrap CUF/CUB around line breaks - wrap_cursor = False - - # do we need to move the cursor? - cursor_set = False - - # current character set, ascii or graphics - character_set = 'ascii' - - # used for auto_read actions - read_count = 0 - - # input buffer, array of ordinals - input_buffer = [] - - def open(self): - """ Start program and initialize this instance. - - Arguments: - command -- Command string to execute, e.g. '/bin/bash --login' - options -- Dictionary of environment vars to set and other options. - - """ - # get arguments - command = vim.eval('command') - options = vim.eval('options') - - # create terminal screen instance - self.screen = ConqueScreen() - - # int vars - self.columns = vim.current.window.width - self.lines = vim.current.window.height - self.working_columns = vim.current.window.width - self.working_lines = vim.current.window.height - self.bottom = vim.current.window.height - - # offset first line to make room for startup messages - if int(options['offset']) > 0: - self.l = int(options['offset']) - - # init color - self.enable_colors = options['color'] and not CONQUE_FAST_MODE - - # init tabstops - self.init_tabstops() - - # open command - self.proc = ConqueSubprocess() - self.proc.open(command, {'TERM': options['TERM'], 'CONQUE': '1', 'LINES': str(self.lines), 'COLUMNS': str(self.columns)}) - - # send window size signal, in case LINES/COLUMNS is ignored - self.update_window_size(True) - - - def write(self, input, set_cursor=True, read=True): - """ Write a unicode string to the subprocess. - - set_cursor -- Position the cursor in the current buffer when finished - read -- Check program for new output when finished - - """ - # write and read - self.proc.write(input) - - # read output immediately - if read: - self.read(1, set_cursor) - - - - def write_ord(self, input, set_cursor=True, read=True): - """ Write a single character to the subprocess, using an unicode ordinal. """ - - if CONQUE_PYTHON_VERSION == 2: - self.write(unichr(input), set_cursor, read) - else: - self.write(chr(input), set_cursor, read) - - - - def write_expr(self, expr, set_cursor=True, read=True): - """ Write the value of a Vim expression to the subprocess. """ - - if CONQUE_PYTHON_VERSION == 2: - try: - val = vim.eval(expr) - self.write(unicode(val, CONQUE_VIM_ENCODING, 'ignore'), set_cursor, read) - except: - - pass - else: - try: - # XXX - Depending on Vim to deal with encoding, sadly - self.write(vim.eval(expr), set_cursor, read) - except: - - pass - - - def write_latin1(self, input, set_cursor=True, read=True): - """ Write latin-1 string to conque. Very ugly, shood be removed. """ - # XXX - this whole method is a hack, to be removed soon - - if CONQUE_PYTHON_VERSION == 2: - try: - input_unicode = input.decode('latin-1', 'ignore') - self.write(input_unicode.encode('utf-8', 'ignore'), set_cursor, read) - except: - return - else: - self.write(input, set_cursor, read) - - - def write_buffered_ord(self, chr): - """ Add character ordinal to input buffer. In case we're not allowed to modify buffer a time of input. """ - self.input_buffer.append(chr) - - - def read(self, timeout=1, set_cursor=True, return_output=False, update_buffer=True): - """ Read new output from the subprocess and update the Vim buffer. - - Arguments: - timeout -- Milliseconds to wait before reading input - set_cursor -- Set the cursor position in the current buffer when finished - return_output -- Return new subprocess STDOUT + STDERR as a string - update_buffer -- Update the current Vim buffer with the new output - - This method goes through the following rough steps: - 1. Get new output from subprocess - 2. Split output string into control codes, escape sequences, or plain text - 3. Loop over and process each chunk, updating the Vim buffer as we go - - """ - output = '' - - # this may not actually work - try: - - # read from subprocess and strip null characters - output = self.proc.read(timeout) - - if output == '': - return - - # for bufferless terminals - if not update_buffer: - return output - - - - # strip null characters. I'm still not sure why they appear - output = output.replace(chr(0), '') - - # split input into individual escape sequences, control codes, and text output - chunks = CONQUE_SEQ_REGEX.split(output) - - - - # if there were no escape sequences, skip processing and treat entire string as plain text - if len(chunks) == 1: - self.plain_text(chunks[0]) - - # loop through and process escape sequences - else: - for s in chunks: - if s == '': - continue - - - - - # Check for control character match - if CONQUE_SEQ_REGEX_CTL.match(s[0]): - - nr = ord(s[0]) - if nr in CONQUE_CTL: - getattr(self, 'ctl_' + CONQUE_CTL[nr])() - else: - - pass - - # check for escape sequence match - elif CONQUE_SEQ_REGEX_CSI.match(s): - - if s[-1] in CONQUE_ESCAPE: - csi = self.parse_csi(s[2:]) - - getattr(self, 'csi_' + CONQUE_ESCAPE[s[-1]])(csi) - else: - - pass - - # check for title match - elif CONQUE_SEQ_REGEX_TITLE.match(s): - - self.change_title(s[2], s[4:-1]) - - # check for hash match - elif CONQUE_SEQ_REGEX_HASH.match(s): - - if s[-1] in CONQUE_ESCAPE_HASH: - getattr(self, 'hash_' + CONQUE_ESCAPE_HASH[s[-1]])() - else: - - pass - - # check for charset match - elif CONQUE_SEQ_REGEX_CHAR.match(s): - - if s[-1] in CONQUE_ESCAPE_CHARSET: - getattr(self, 'charset_' + CONQUE_ESCAPE_CHARSET[s[-1]])() - else: - - pass - - # check for other escape match - elif CONQUE_SEQ_REGEX_ESC.match(s): - - if s[-1] in CONQUE_ESCAPE_PLAIN: - getattr(self, 'esc_' + CONQUE_ESCAPE_PLAIN[s[-1]])() - else: - - pass - - # else process plain text - else: - self.plain_text(s) - - # set cusor position - if set_cursor: - self.screen.set_cursor(self.l, self.c) - - # we need to set the cursor position - self.cursor_set = False - - except: - - - pass - - if return_output: - if CONQUE_PYTHON_VERSION == 3: - return output - else: - return output.encode(CONQUE_VIM_ENCODING, 'replace') - - - def auto_read(self): - """ Poll program for more output. - - Since Vim doesn't have a reliable event system that can be triggered when new - output is available, we have to continually poll the subprocess instead. This - method is called many times a second when the terminal buffer is active, so it - needs to be very fast and efficient. - - The feedkeys portion is required to reset Vim's timer system. The timer is used - to execute this command, typically set to go off after 50 ms of inactivity. - - """ - # process buffered input if any - if len(self.input_buffer): - for chr in self.input_buffer: - self.write_ord(chr, set_cursor=False, read=False) - self.input_buffer = [] - self.read(1) - - # check subprocess status, but not every time since it's CPU expensive - if self.read_count % 32 == 0: - if not self.proc.is_alive(): - vim.command('call conque_term#get_instance().close()') - return - - if self.read_count > 512: - self.read_count = 0 - - # trim color history occasionally if desired - if self.enable_colors and self.color_pruning: - self.prune_colors() - - # ++ - self.read_count += 1 - - # read output - self.read(1) - - # reset timer - if self.c == 1: - vim.command('call feedkeys("\\", "n")') - else: - vim.command('call feedkeys("\\", "n")') - - # stop here if cursor doesn't need to be moved - if self.cursor_set: - return - - # check if window size has changed - if not CONQUE_FAST_MODE: - self.update_window_size() - - - # otherwise set cursor position - try: - self.set_cursor(self.l, self.c) - except: - - - pass - - self.cursor_set = True - - - def plain_text(self, input): - """ Write text output to Vim buffer. - - - This method writes a string of characters without any control characters or escape sequences - to the Vim buffer. In simple terms, it writes the input string to the buffer starting at the - current cursor position, wrapping the text to a new line if needed. It also triggers the - terminal coloring methods if needed. - - - """ - # translate input into graphics character set if needed - if self.character_set == 'graphics': - old_input = input - input = u('') - for i in range(0, len(old_input)): - chrd = ord(old_input[i]) - - - try: - if chrd > 255: - - input = input + old_input[i] - else: - input = input + uchr(CONQUE_GRAPHICS_SET[chrd]) - except: - - pass - - - - # get current line from Vim buffer - current_line = self.screen[self.l] - - # pad current line with spaces, if it's shorter than cursor position - if len(current_line) < self.c: - current_line = current_line + ' ' * (self.c - len(current_line)) - - # if line is wider than screen - if self.c + len(input) - 1 > self.working_columns: - - # Table formatting hack - if self.unwrap_tables and CONQUE_TABLE_OUTPUT.match(input): - self.screen[self.l] = current_line[:self.c - 1] + input + current_line[self.c + len(input) - 1:] - self.apply_color(self.c, self.c + len(input)) - self.c += len(input) - return - - - diff = self.c + len(input) - self.working_columns - 1 - - # if autowrap is enabled - if self.autowrap: - self.screen[self.l] = current_line[:self.c - 1] + input[:-1 * diff] - self.apply_color(self.c, self.working_columns) - self.ctl_nl() - self.ctl_cr() - remaining = input[-1 * diff:] - - self.plain_text(remaining) - else: - self.screen[self.l] = current_line[:self.c - 1] + input[:-1 * diff - 1] + input[-1] - self.apply_color(self.c, self.working_columns) - self.c = self.working_columns - - # no autowrap - else: - self.screen[self.l] = current_line[:self.c - 1] + input + current_line[self.c + len(input) - 1:] - self.apply_color(self.c, self.c + len(input)) - self.c += len(input) - - - - def apply_color(self, start, end, line=0): - """ Apply terminal colors to buffer for a range of characters in a single line. - - When a text attribute escape sequence is encountered during input processing, the - attributes are recorded in the dictionary self.color_changes. After those attributes - have been applied, the changes are recorded in a second dictionary self.color_history. - - - This method inspects both dictionaries to calculate any syntax highlighting - that needs to be executed to render the text attributes in the Vim buffer. - - - """ - - - # stop here if coloration is disabled - if not self.enable_colors: - return - - # allow custom line nr to be passed - if line: - buffer_line = line - else: - buffer_line = self.get_buffer_line(self.l) - - # check for previous overlapping coloration - - to_del = [] - if buffer_line in self.color_history: - for i in range(len(self.color_history[buffer_line])): - syn = self.color_history[buffer_line][i] - - if syn['start'] >= start and syn['start'] < end: - - vim.command('syn clear ' + syn['name']) - to_del.append(i) - # outside - if syn['end'] > end: - - self.exec_highlight(buffer_line, end, syn['end'], syn['highlight']) - elif syn['end'] > start and syn['end'] <= end: - - vim.command('syn clear ' + syn['name']) - to_del.append(i) - # outside - if syn['start'] < start: - - self.exec_highlight(buffer_line, syn['start'], start, syn['highlight']) - - # remove overlapped colors - if len(to_del) > 0: - to_del.reverse() - for di in to_del: - del self.color_history[buffer_line][di] - - # if there are no new colors - if len(self.color_changes) == 0: - return - - # build the color attribute string - highlight = '' - for attr in self.color_changes.keys(): - highlight = highlight + ' ' + attr + '=' + self.color_changes[attr] - - # execute the highlight - self.exec_highlight(buffer_line, start, end, highlight) - - - def exec_highlight(self, buffer_line, start, end, highlight): - """ Execute the Vim commands for a single syntax highlight """ - - syntax_name = 'ConqueHighLightAt_%d_%d_%d_%d' % (self.proc.pid, self.l, start, len(self.color_history) + 1) - syntax_options = 'contains=ALLBUT,ConqueString,MySQLString,MySQLKeyword oneline' - syntax_region = 'syntax match %s /\%%%dl\%%>%dc.\{%d}\%%<%dc/ %s' % (syntax_name, buffer_line, start - 1, end - start, end + 1, syntax_options) - - # check for cached highlight group - hgroup = 'ConqueHL_%d' % (abs(hash(highlight))) - if hgroup not in self.highlight_groups: - syntax_group = 'highlight %s %s' % (hgroup, highlight) - self.highlight_groups[hgroup] = hgroup - vim.command(syntax_group) - - # link this syntax match to existing highlight group - syntax_highlight = 'highlight link %s %s' % (syntax_name, self.highlight_groups[hgroup]) - - - - vim.command(syntax_region) - vim.command(syntax_highlight) - - # add syntax name to history - if not buffer_line in self.color_history: - self.color_history[buffer_line] = [] - - self.color_history[buffer_line].append({'name': syntax_name, 'start': start, 'end': end, 'highlight': highlight}) - - - def prune_colors(self): - """ Remove old syntax highlighting from the Vim buffer - - The kind of syntax highlighting required for terminal colors can make - Conque run slowly. The prune_colors() method will remove old highlight definitions - to keep the maximum number of highlight rules within a reasonable range. - - """ - - - buffer_line = self.get_buffer_line(self.l) - ks = list(self.color_history.keys()) - - for line in ks: - if line < buffer_line - CONQUE_MAX_SYNTAX_LINES: - for syn in self.color_history[line]: - vim.command('syn clear ' + syn['name']) - del self.color_history[line] - - - - - ############################################################################################### - # Control functions - - def ctl_nl(self): - """ Process the newline control character. """ - # if we're in a scrolling region, scroll instead of moving cursor down - if self.lines != self.working_lines and self.l == self.bottom: - del self.screen[self.top] - self.screen.insert(self.bottom, '') - elif self.l == self.bottom: - self.screen.append('') - else: - self.l += 1 - - self.color_changes = {} - - def ctl_cr(self): - """ Process the carriage return control character. """ - self.c = 1 - - self.color_changes = {} - - def ctl_bs(self): - """ Process the backspace control character. """ - if self.c > 1: - self.c += -1 - - def ctl_soh(self): - """ Process the start of heading control character. """ - pass - - def ctl_stx(self): - pass - - def ctl_bel(self): - """ Process the bell control character. """ - vim.command('call conque_term#bell()') - - def ctl_tab(self): - """ Process the tab control character. """ - # default tabstop location - ts = self.working_columns - - # check set tabstops - for i in range(self.c, len(self.tabstops)): - if self.tabstops[i]: - ts = i + 1 - break - - - - self.c = ts - - def ctl_so(self): - """ Process the shift out control character. """ - self.character_set = 'graphics' - - def ctl_si(self): - """ Process the shift in control character. """ - self.character_set = 'ascii' - - - - ############################################################################################### - # CSI functions - - def csi_font(self, csi): - """ Process the text attribute escape sequence. """ - if not self.enable_colors: - return - - # defaults to 0 - if len(csi['vals']) == 0: - csi['vals'] = [0] - - # 256 xterm color foreground - if len(csi['vals']) == 3 and csi['vals'][0] == 38 and csi['vals'][1] == 5: - self.color_changes['ctermfg'] = str(csi['vals'][2]) - self.color_changes['guifg'] = '#' + self.xterm_to_rgb(csi['vals'][2]) - - # 256 xterm color background - elif len(csi['vals']) == 3 and csi['vals'][0] == 48 and csi['vals'][1] == 5: - self.color_changes['ctermbg'] = str(csi['vals'][2]) - self.color_changes['guibg'] = '#' + self.xterm_to_rgb(csi['vals'][2]) - - # 16 colors - else: - for val in csi['vals']: - if val in CONQUE_FONT: - - # ignore starting normal colors - if CONQUE_FONT[val]['normal'] and len(self.color_changes) == 0: - - continue - # clear color changes - elif CONQUE_FONT[val]['normal']: - - self.color_changes = {} - # save these color attributes for next plain_text() call - else: - - for attr in CONQUE_FONT[val]['attributes'].keys(): - if attr in self.color_changes and (attr == 'cterm' or attr == 'gui'): - self.color_changes[attr] += ',' + CONQUE_FONT[val]['attributes'][attr] - else: - self.color_changes[attr] = CONQUE_FONT[val]['attributes'][attr] - - - def csi_clear_line(self, csi): - """ Process the line clear escape sequence. """ - - - # this escape defaults to 0 - if len(csi['vals']) == 0: - csi['val'] = 0 - - - - - # 0 means cursor right - if csi['val'] == 0: - self.screen[self.l] = self.screen[self.l][0:self.c - 1] - - # 1 means cursor left - elif csi['val'] == 1: - self.screen[self.l] = ' ' * (self.c) + self.screen[self.l][self.c:] - - # clear entire line - elif csi['val'] == 2: - self.screen[self.l] = '' - - # clear colors - if csi['val'] == 2 or (csi['val'] == 0 and self.c == 1): - buffer_line = self.get_buffer_line(self.l) - if buffer_line in self.color_history: - for syn in self.color_history[buffer_line]: - vim.command('syn clear ' + syn['name']) - - - - - - def csi_cursor_right(self, csi): - """ Process the move cursor right escape sequence. """ - # we use 1 even if escape explicitly specifies 0 - if csi['val'] == 0: - csi['val'] = 1 - - - - - if self.wrap_cursor and self.c + csi['val'] > self.working_columns: - self.l += int(math.floor((self.c + csi['val']) / self.working_columns)) - self.c = (self.c + csi['val']) % self.working_columns - return - - self.c = self.bound(self.c + csi['val'], 1, self.working_columns) - - - def csi_cursor_left(self, csi): - """ Process the move cursor left escape sequence. """ - # we use 1 even if escape explicitly specifies 0 - if csi['val'] == 0: - csi['val'] = 1 - - if self.wrap_cursor and csi['val'] >= self.c: - self.l += int(math.floor((self.c - csi['val']) / self.working_columns)) - self.c = self.working_columns - (csi['val'] - self.c) % self.working_columns - return - - self.c = self.bound(self.c - csi['val'], 1, self.working_columns) - - - def csi_cursor_to_column(self, csi): - """ Process the move cursor to column escape sequence. """ - self.c = self.bound(csi['val'], 1, self.working_columns) - - - def csi_cursor_up(self, csi): - """ Process the move cursor up escape sequence. """ - self.l = self.bound(self.l - csi['val'], self.top, self.bottom) - - self.color_changes = {} - - - def csi_cursor_down(self, csi): - """ Process the move cursor down escape sequence. """ - self.l = self.bound(self.l + csi['val'], self.top, self.bottom) - - self.color_changes = {} - - - def csi_clear_screen(self, csi): - """ Process the clear screen escape sequence. """ - # default to 0 - if len(csi['vals']) == 0: - csi['val'] = 0 - - # 2 == clear entire screen - if csi['val'] == 2: - self.l = 1 - self.c = 1 - self.screen.clear() - - # 0 == clear down - elif csi['val'] == 0: - for l in range(self.bound(self.l + 1, 1, self.lines), self.lines + 1): - self.screen[l] = '' - - # clear end of current line - self.csi_clear_line(self.parse_csi('K')) - - # 1 == clear up - elif csi['val'] == 1: - for l in range(1, self.bound(self.l, 1, self.lines + 1)): - self.screen[l] = '' - - # clear beginning of current line - self.csi_clear_line(self.parse_csi('1K')) - - # clear coloration - if csi['val'] == 2 or csi['val'] == 0: - buffer_line = self.get_buffer_line(self.l) - for line in self.color_history.keys(): - if line >= buffer_line: - for syn in self.color_history[line]: - vim.command('syn clear ' + syn['name']) - - self.color_changes = {} - - - def csi_delete_chars(self, csi): - self.screen[self.l] = self.screen[self.l][:self.c] + self.screen[self.l][self.c + csi['val']:] - - - def csi_add_spaces(self, csi): - self.screen[self.l] = self.screen[self.l][: self.c - 1] + ' ' * csi['val'] + self.screen[self.l][self.c:] - - - def csi_cursor(self, csi): - if len(csi['vals']) == 2: - new_line = csi['vals'][0] - new_col = csi['vals'][1] - else: - new_line = 1 - new_col = 1 - - if self.absolute_coords: - self.l = self.bound(new_line, 1, self.lines) - else: - self.l = self.bound(self.top + new_line - 1, self.top, self.bottom) - - self.c = self.bound(new_col, 1, self.working_columns) - if self.c > len(self.screen[self.l]): - self.screen[self.l] = self.screen[self.l] + ' ' * (self.c - len(self.screen[self.l])) - - - - def csi_set_coords(self, csi): - if len(csi['vals']) == 2: - new_start = csi['vals'][0] - new_end = csi['vals'][1] - else: - new_start = 1 - new_end = vim.current.window.height - - self.top = new_start - self.bottom = new_end - self.working_lines = new_end - new_start + 1 - - # if cursor is outside scrolling region, reset it - if self.l < self.top: - self.l = self.top - elif self.l > self.bottom: - self.l = self.bottom - - self.color_changes = {} - - - def csi_tab_clear(self, csi): - # this escape defaults to 0 - if len(csi['vals']) == 0: - csi['val'] = 0 - - - - if csi['val'] == 0: - self.tabstops[self.c - 1] = False - elif csi['val'] == 3: - for i in range(0, self.columns + 1): - self.tabstops[i] = False - - - def csi_set(self, csi): - # 132 cols - if csi['val'] == 3: - self.csi_clear_screen(self.parse_csi('2J')) - self.working_columns = 132 - - # relative_origin - elif csi['val'] == 6: - self.absolute_coords = False - - # set auto wrap - elif csi['val'] == 7: - self.autowrap = True - - - self.color_changes = {} - - - def csi_reset(self, csi): - # 80 cols - if csi['val'] == 3: - self.csi_clear_screen(self.parse_csi('2J')) - self.working_columns = 80 - - # absolute origin - elif csi['val'] == 6: - self.absolute_coords = True - - # reset auto wrap - elif csi['val'] == 7: - self.autowrap = False - - - self.color_changes = {} - - - - - ############################################################################################### - # ESC functions - - def esc_scroll_up(self): - self.ctl_nl() - - self.color_changes = {} - - - def esc_next_line(self): - self.ctl_nl() - self.c = 1 - - - def esc_set_tab(self): - - if self.c <= len(self.tabstops): - self.tabstops[self.c - 1] = True - - - def esc_scroll_down(self): - if self.l == self.top: - del self.screen[self.bottom] - self.screen.insert(self.top, '') - else: - self.l += -1 - - self.color_changes = {} - - - - - ############################################################################################### - # HASH functions - - def hash_screen_alignment_test(self): - self.csi_clear_screen(self.parse_csi('2J')) - self.working_lines = self.lines - for l in range(1, self.lines + 1): - self.screen[l] = 'E' * self.working_columns - - - - ############################################################################################### - # CHARSET functions - - def charset_us(self): - self.character_set = 'ascii' - - def charset_uk(self): - self.character_set = 'ascii' - - def charset_graphics(self): - self.character_set = 'graphics' - - - - ############################################################################################### - # Random stuff - - def set_cursor(self, line, col): - """ Set cursor position in the Vim buffer. - - Note: the line and column numbers are relative to the top left corner of the - visible screen. Not the line number in the Vim buffer. - - """ - self.screen.set_cursor(line, col) - - def change_title(self, key, val): - """ Change the Vim window title. """ - - - if key == '0' or key == '2': - - vim.command('setlocal statusline=' + re.escape(val)) - try: - vim.command('set titlestring=' + re.escape(val)) - except: - pass - - def update_window_size(self, force=False): - """ Check and save the current buffer dimensions. - - If the buffer size has changed, the update_window_size() method both updates - the Conque buffer size attributes as well as sending the new dimensions to the - subprocess pty. - - """ - # resize if needed - if force or vim.current.window.width != self.columns or vim.current.window.height != self.lines: - - # reset all window size attributes to default - self.columns = vim.current.window.width - self.lines = vim.current.window.height - self.working_columns = vim.current.window.width - self.working_lines = vim.current.window.height - self.bottom = vim.current.window.height - - # reset screen object attributes - self.l = self.screen.reset_size(self.l) - - # reset tabstops - self.init_tabstops() - - - - # signal process that screen size has changed - self.proc.window_resize(self.lines, self.columns) - - def insert_enter(self): - """ Run commands when user enters insert mode. """ - - # check window size - self.update_window_size() - - # we need to set the cursor position - self.cursor_set = False - - def init_tabstops(self): - """ Intitialize terminal tabstop positions. """ - for i in range(0, self.columns + 1): - if i % 8 == 0: - self.tabstops.append(True) - else: - self.tabstops.append(False) - - def idle(self): - """ Called when this terminal becomes idle. """ - pass - - def resume(self): - """ Called when this terminal is no longer idle. """ - pass - pass - - def close(self): - """ End the process running in the terminal. """ - self.proc.close() - - def abort(self): - """ Forcefully end the process running in the terminal. """ - self.proc.signal(1) - - - - ############################################################################################### - # Utility - - def parse_csi(self, s): - """ Parse an escape sequence into it's meaningful values. """ - - attr = {'key': s[-1], 'flag': '', 'val': 1, 'vals': []} - - if len(s) == 1: - return attr - - full = s[0:-1] - - if full[0] == '?': - full = full[1:] - attr['flag'] = '?' - - if full != '': - vals = full.split(';') - for val in vals: - - val = re.sub("\D", "", val) - - if val != '': - attr['vals'].append(int(val)) - - if len(attr['vals']) == 1: - attr['val'] = int(attr['vals'][0]) - - return attr - - - def bound(self, val, min, max): - """ TODO: This probably exists as a builtin function. """ - if val > max: - return max - - if val < min: - return min - - return val - - - def xterm_to_rgb(self, color_code): - """ Translate a terminal color number into a RGB string. """ - if color_code < 16: - ascii_colors = ['000000', 'CD0000', '00CD00', 'CDCD00', '0000EE', 'CD00CD', '00CDCD', 'E5E5E5', - '7F7F7F', 'FF0000', '00FF00', 'FFFF00', '5C5CFF', 'FF00FF', '00FFFF', 'FFFFFF'] - return ascii_colors[color_code] - - elif color_code < 232: - cc = int(color_code) - 16 - - p1 = "%02x" % (math.floor(cc / 36) * (255 / 5)) - p2 = "%02x" % (math.floor((cc % 36) / 6) * (255 / 5)) - p3 = "%02x" % (math.floor(cc % 6) * (255 / 5)) - - return p1 + p2 + p3 - else: - grey_tone = "%02x" % math.floor((255 / 24) * (color_code - 232)) - return grey_tone + grey_tone + grey_tone - - - - - def get_buffer_line(self, line): - """ Get the buffer line number corresponding to the supplied screen line number. """ - return self.screen.get_buffer_line(line) - - diff --git a/vim/autoload/conque_term/conque_globals.py b/vim/autoload/conque_term/conque_globals.py deleted file mode 100644 index f441801..0000000 --- a/vim/autoload/conque_term/conque_globals.py +++ /dev/null @@ -1,315 +0,0 @@ -# FILE: autoload/conque_term/conque_globals.py -# AUTHOR: Nico Raffo -# WEBSITE: http://conque.googlecode.com -# MODIFIED: 2011-09-02 -# VERSION: 2.3, for Vim 7.0 -# LICENSE: -# Conque - Vim terminal/console emulator -# Copyright (C) 2009-2011 Nico Raffo -# -# MIT License -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -"""Common global constants and functions for Conque.""" - -import sys -import re - - - - -# PYTHON VERSION -CONQUE_PYTHON_VERSION = sys.version_info[0] - -# Encoding - -try: - # Vim's character encoding - import vim - CONQUE_VIM_ENCODING = vim.eval('&encoding') - -except: - CONQUE_VIM_ENCODING = 'utf-8' - - -def u(str_val, str_encoding='utf-8', errors='strict'): - """ Foolhardy attempt to make unicode string syntax compatible with both python 2 and 3. """ - - if not str_val: - str_val = '' - - if CONQUE_PYTHON_VERSION == 3: - return str_val - - else: - return unicode(str_val, str_encoding, errors) - -def uchr(str): - """ Foolhardy attempt to make unicode string syntax compatible with both python 2 and 3. """ - - if CONQUE_PYTHON_VERSION == 3: - return chr(str) - - else: - return unichr(str) - - -# Logging - - - - - - - - - - - - - - - - -# Unix escape sequence settings - -CONQUE_CTL = { - 1: 'soh', # start of heading - 2: 'stx', # start of text - 7: 'bel', # bell - 8: 'bs', # backspace - 9: 'tab', # tab - 10: 'nl', # new line - 13: 'cr', # carriage return - 14: 'so', # shift out - 15: 'si' # shift in -} -# 11 : 'vt', # vertical tab -# 12 : 'ff', # form feed - -# Escape sequences -CONQUE_ESCAPE = { - 'm': 'font', - 'J': 'clear_screen', - 'K': 'clear_line', - '@': 'add_spaces', - 'A': 'cursor_up', - 'B': 'cursor_down', - 'C': 'cursor_right', - 'D': 'cursor_left', - 'G': 'cursor_to_column', - 'H': 'cursor', - 'P': 'delete_chars', - 'f': 'cursor', - 'g': 'tab_clear', - 'r': 'set_coords', - 'h': 'set', - 'l': 'reset' -} -# 'L': 'insert_lines', -# 'M': 'delete_lines', -# 'd': 'cusor_vpos', - -# Alternate escape sequences, no [ -CONQUE_ESCAPE_PLAIN = { - 'D': 'scroll_up', - 'E': 'next_line', - 'H': 'set_tab', - 'M': 'scroll_down' -} -# 'N': 'single_shift_2', -# 'O': 'single_shift_3', -# '=': 'alternate_keypad', -# '>': 'numeric_keypad', -# '7': 'save_cursor', -# '8': 'restore_cursor', - -# Character set escape sequences, with "(" -CONQUE_ESCAPE_CHARSET = { - 'A': 'uk', - 'B': 'us', - '0': 'graphics' -} - -# Uber alternate escape sequences, with # or ? -CONQUE_ESCAPE_QUESTION = { - '1h': 'new_line_mode', - '3h': '132_cols', - '4h': 'smooth_scrolling', - '5h': 'reverse_video', - '6h': 'relative_origin', - '7h': 'set_auto_wrap', - '8h': 'set_auto_repeat', - '9h': 'set_interlacing_mode', - '1l': 'set_cursor_key', - '2l': 'set_vt52', - '3l': '80_cols', - '4l': 'set_jump_scrolling', - '5l': 'normal_video', - '6l': 'absolute_origin', - '7l': 'reset_auto_wrap', - '8l': 'reset_auto_repeat', - '9l': 'reset_interlacing_mode' -} - -CONQUE_ESCAPE_HASH = { - '8': 'screen_alignment_test' -} -# '3': 'double_height_top', -# '4': 'double_height_bottom', -# '5': 'single_height_single_width', -# '6': 'single_height_double_width', - -CONQUE_GRAPHICS_SET = [ - 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, - 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, - 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, - 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, - 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, - 0x0028, 0x0029, 0x002A, 0x2192, 0x2190, 0x2191, 0x2193, 0x002F, - 0x2588, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, - 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, - 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, - 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, - 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, - 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x00A0, - 0x25C6, 0x2592, 0x2409, 0x240C, 0x240D, 0x240A, 0x00B0, 0x00B1, - 0x2591, 0x240B, 0x2518, 0x2510, 0x250C, 0x2514, 0x253C, 0xF800, - 0xF801, 0x2500, 0xF803, 0xF804, 0x251C, 0x2524, 0x2534, 0x252C, - 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00B7, 0x007F, - 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, - 0x0088, 0x0089, 0x008A, 0x008B, 0x008C, 0x008D, 0x008E, 0x008F, - 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, - 0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 0x009E, 0x009F, - 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, - 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, - 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7, - 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, - 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7, - 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, - 0x00D0, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, - 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DE, 0x00DF, - 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, - 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF, - 0x00F0, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, - 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF -] - -# Font codes -CONQUE_FONT = { - 0: {'description': 'Normal (default)', 'attributes': {'cterm': 'NONE', 'ctermfg': 'NONE', 'ctermbg': 'NONE', 'gui': 'NONE', 'guifg': 'NONE', 'guibg': 'NONE'}, 'normal': True}, - 1: {'description': 'Bold', 'attributes': {'cterm': 'BOLD', 'gui': 'BOLD'}, 'normal': False}, - 4: {'description': 'Underlined', 'attributes': {'cterm': 'UNDERLINE', 'gui': 'UNDERLINE'}, 'normal': False}, - 5: {'description': 'Blink (appears as Bold)', 'attributes': {'cterm': 'BOLD', 'gui': 'BOLD'}, 'normal': False}, - 7: {'description': 'Inverse', 'attributes': {'cterm': 'REVERSE', 'gui': 'REVERSE'}, 'normal': False}, - 8: {'description': 'Invisible (hidden)', 'attributes': {'ctermfg': '0', 'ctermbg': '0', 'guifg': '#000000', 'guibg': '#000000'}, 'normal': False}, - 22: {'description': 'Normal (neither bold nor faint)', 'attributes': {'cterm': 'NONE', 'gui': 'NONE'}, 'normal': True}, - 24: {'description': 'Not underlined', 'attributes': {'cterm': 'NONE', 'gui': 'NONE'}, 'normal': True}, - 25: {'description': 'Steady (not blinking)', 'attributes': {'cterm': 'NONE', 'gui': 'NONE'}, 'normal': True}, - 27: {'description': 'Positive (not inverse)', 'attributes': {'cterm': 'NONE', 'gui': 'NONE'}, 'normal': True}, - 28: {'description': 'Visible (not hidden)', 'attributes': {'ctermfg': 'NONE', 'ctermbg': 'NONE', 'guifg': 'NONE', 'guibg': 'NONE'}, 'normal': True}, - 30: {'description': 'Set foreground color to Black', 'attributes': {'ctermfg': '16', 'guifg': '#000000'}, 'normal': False}, - 31: {'description': 'Set foreground color to Red', 'attributes': {'ctermfg': '1', 'guifg': '#ff0000'}, 'normal': False}, - 32: {'description': 'Set foreground color to Green', 'attributes': {'ctermfg': '2', 'guifg': '#00ff00'}, 'normal': False}, - 33: {'description': 'Set foreground color to Yellow', 'attributes': {'ctermfg': '3', 'guifg': '#ffff00'}, 'normal': False}, - 35: {'description': 'Set foreground color to Magenta', 'attributes': {'ctermfg': '5', 'guifg': '#990099'}, 'normal': False}, - 36: {'description': 'Set foreground color to Cyan', 'attributes': {'ctermfg': '6', 'guifg': '#009999'}, 'normal': False}, - 37: {'description': 'Set foreground color to White', 'attributes': {'ctermfg': '7', 'guifg': '#ffffff'}, 'normal': False}, - 39: {'description': 'Set foreground color to default (original)', 'attributes': {'ctermfg': 'NONE', 'guifg': 'NONE'}, 'normal': True}, - 40: {'description': 'Set background color to Black', 'attributes': {'ctermbg': '16', 'guibg': '#000000'}, 'normal': False}, - 41: {'description': 'Set background color to Red', 'attributes': {'ctermbg': '1', 'guibg': '#ff0000'}, 'normal': False}, - 42: {'description': 'Set background color to Green', 'attributes': {'ctermbg': '2', 'guibg': '#00ff00'}, 'normal': False}, - 43: {'description': 'Set background color to Yellow', 'attributes': {'ctermbg': '3', 'guibg': '#ffff00'}, 'normal': False}, - 45: {'description': 'Set background color to Magenta', 'attributes': {'ctermbg': '5', 'guibg': '#990099'}, 'normal': False}, - 46: {'description': 'Set background color to Cyan', 'attributes': {'ctermbg': '6', 'guibg': '#009999'}, 'normal': False}, - 47: {'description': 'Set background color to White', 'attributes': {'ctermbg': '7', 'guibg': '#ffffff'}, 'normal': False}, - 49: {'description': 'Set background color to default (original).', 'attributes': {'ctermbg': 'NONE', 'guibg': 'NONE'}, 'normal': True}, - 90: {'description': 'Set foreground color to Black', 'attributes': {'ctermfg': '8', 'guifg': '#000000'}, 'normal': False}, - 91: {'description': 'Set foreground color to Red', 'attributes': {'ctermfg': '9', 'guifg': '#ff0000'}, 'normal': False}, - 92: {'description': 'Set foreground color to Green', 'attributes': {'ctermfg': '10', 'guifg': '#00ff00'}, 'normal': False}, - 93: {'description': 'Set foreground color to Yellow', 'attributes': {'ctermfg': '11', 'guifg': '#ffff00'}, 'normal': False}, - 95: {'description': 'Set foreground color to Magenta', 'attributes': {'ctermfg': '13', 'guifg': '#990099'}, 'normal': False}, - 96: {'description': 'Set foreground color to Cyan', 'attributes': {'ctermfg': '14', 'guifg': '#009999'}, 'normal': False}, - 97: {'description': 'Set foreground color to White', 'attributes': {'ctermfg': '15', 'guifg': '#ffffff'}, 'normal': False}, - 100: {'description': 'Set background color to Black', 'attributes': {'ctermbg': '8', 'guibg': '#000000'}, 'normal': False}, - 101: {'description': 'Set background color to Red', 'attributes': {'ctermbg': '9', 'guibg': '#ff0000'}, 'normal': False}, - 102: {'description': 'Set background color to Green', 'attributes': {'ctermbg': '10', 'guibg': '#00ff00'}, 'normal': False}, - 103: {'description': 'Set background color to Yellow', 'attributes': {'ctermbg': '11', 'guibg': '#ffff00'}, 'normal': False}, - 105: {'description': 'Set background color to Magenta', 'attributes': {'ctermbg': '13', 'guibg': '#990099'}, 'normal': False}, - 106: {'description': 'Set background color to Cyan', 'attributes': {'ctermbg': '14', 'guibg': '#009999'}, 'normal': False}, - 107: {'description': 'Set background color to White', 'attributes': {'ctermbg': '15', 'guibg': '#ffffff'}, 'normal': False} -} - - -# regular expression matching (almost) all control sequences -CONQUE_SEQ_REGEX = re.compile("(\x1b\[?\??#?[0-9;]*[a-zA-Z0-9@=>]|\x1b\][0-9];.*?\x07|[\x01-\x0f]|\x1b\([AB0])") -CONQUE_SEQ_REGEX_CTL = re.compile("^[\x01-\x0f]$") -CONQUE_SEQ_REGEX_CSI = re.compile("^\x1b\[") -CONQUE_SEQ_REGEX_TITLE = re.compile("^\x1b\]") -CONQUE_SEQ_REGEX_HASH = re.compile("^\x1b#") -CONQUE_SEQ_REGEX_ESC = re.compile("^\x1b.$") -CONQUE_SEQ_REGEX_CHAR = re.compile("^\x1b[()]") - -# match table output -CONQUE_TABLE_OUTPUT = re.compile("^\s*\|\s.*\s\|\s*$|^\s*\+[=+-]+\+\s*$") - -# basic terminal colors -CONQUE_COLOR_SEQUENCE = ( - '000', '009', '090', '099', '900', '909', '990', '999', - '000', '00f', '0f0', '0ff', 'f00', 'f0f', 'ff0', 'fff' -) - - -# Windows subprocess constants - -# shared memory size -CONQUE_SOLE_BUFFER_LENGTH = 1000 -CONQUE_SOLE_INPUT_SIZE = 1000 -CONQUE_SOLE_STATS_SIZE = 1000 -CONQUE_SOLE_COMMANDS_SIZE = 255 -CONQUE_SOLE_RESCROLL_SIZE = 255 -CONQUE_SOLE_RESIZE_SIZE = 255 - -# interval of screen redraw -# larger number means less frequent -CONQUE_SOLE_SCREEN_REDRAW = 50 - -# interval of full buffer redraw -# larger number means less frequent -CONQUE_SOLE_BUFFER_REDRAW = 500 - -# interval of full output bucket replacement -# larger number means less frequent, 1 = every time -CONQUE_SOLE_MEM_REDRAW = 1000 - -# maximum number of lines with terminal colors -# ignored if g:ConqueTerm_Color = 2 -CONQUE_MAX_SYNTAX_LINES = 200 - -# windows input splitting on special keys -CONQUE_WIN32_REGEX_VK = re.compile("(\x1b\[[0-9;]+VK)") - -# windows attribute string splitting -CONQUE_WIN32_REGEX_ATTR = re.compile("((.)\\2*)", re.DOTALL) - -# special key attributes -CONQUE_VK_ATTR_CTRL_PRESSED = u('1024') - - diff --git a/vim/autoload/conque_term/conque_screen.py b/vim/autoload/conque_term/conque_screen.py deleted file mode 100644 index 3557e11..0000000 --- a/vim/autoload/conque_term/conque_screen.py +++ /dev/null @@ -1,233 +0,0 @@ -# FILE: autoload/conque_term/conque_screen.py -# AUTHOR: Nico Raffo -# WEBSITE: http://conque.googlecode.com -# MODIFIED: 2011-09-02 -# VERSION: 2.3, for Vim 7.0 -# LICENSE: -# Conque - Vim terminal/console emulator -# Copyright (C) 2009-2011 Nico Raffo -# -# MIT License -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -""" -ConqueScreen is an extention of the vim.current.buffer object - -Unix terminal escape sequences usually reference line numbers relative to the -top of the visible screen. However the visible portion of the Vim buffer -representing the terminal probably doesn't start at the first line of the -buffer. - -The ConqueScreen class allows access to the Vim buffer with screen-relative -line numbering. And handles a few other related tasks, such as setting the -correct cursor position. - - E.g.: - s = ConqueScreen() - ... - s[5] = 'Set 5th line in terminal to this line' - s.append('Add new line to terminal') - s[5] = 'Since previous append() command scrolled the terminal down, this is a different line than first cb[5] call' - -""" - -import vim - - -class ConqueScreen(object): - - # the buffer - buffer = None - - # screen and scrolling regions - screen_top = 1 - - # screen width - screen_width = 80 - screen_height = 80 - - # char encoding for vim buffer - screen_encoding = 'utf-8' - - - def __init__(self): - """ Initialize screen size and character encoding. """ - - self.buffer = vim.current.buffer - - # initialize screen size - self.screen_top = 1 - self.screen_width = vim.current.window.width - self.screen_height = vim.current.window.height - - # save screen character encoding type - self.screen_encoding = vim.eval('&fileencoding') - - - def __len__(self): - """ Define the len() function for ConqueScreen objects. """ - return len(self.buffer) - - - def __getitem__(self, key): - """ Define value access for ConqueScreen objects. """ - buffer_line = self.get_real_idx(key) - - # if line is past buffer end, add lines to buffer - if buffer_line >= len(self.buffer): - for i in range(len(self.buffer), buffer_line + 1): - self.append(' ') - - return u(self.buffer[buffer_line], 'utf-8') - - - def __setitem__(self, key, value): - """ Define value assignments for ConqueScreen objects. """ - buffer_line = self.get_real_idx(key) - - if CONQUE_PYTHON_VERSION == 2: - val = value.encode(self.screen_encoding) - else: - # XXX / Vim's python3 interface doesn't accept bytes object - val = str(value) - - # if line is past end of screen, append - if buffer_line == len(self.buffer): - self.buffer.append(val) - else: - self.buffer[buffer_line] = val - - - def __delitem__(self, key): - """ Define value deletion for ConqueScreen objects. """ - del self.buffer[self.screen_top + key - 2] - - - def append(self, value): - """ Define value appending for ConqueScreen objects. """ - - if len(self.buffer) > self.screen_top + self.screen_height - 1: - self.buffer[len(self.buffer) - 1] = value - else: - self.buffer.append(value) - - if len(self.buffer) > self.screen_top + self.screen_height - 1: - self.screen_top += 1 - - if vim.current.buffer.number == self.buffer.number: - vim.command('normal! G') - - - def insert(self, line, value): - """ Define value insertion for ConqueScreen objects. """ - - l = self.screen_top + line - 2 - try: - self.buffer.append(value, l) - except: - self.buffer[l:l] = [value] - - - def get_top(self): - """ Get the Vim line number representing the top of the visible terminal. """ - return self.screen_top - - - def get_real_idx(self, line): - """ Get the zero index Vim line number corresponding to the provided screen line. """ - return (self.screen_top + line - 2) - - - def get_buffer_line(self, line): - """ Get the Vim line number corresponding to the provided screen line. """ - return (self.screen_top + line - 1) - - - def set_screen_width(self, width): - """ Set the screen width. """ - self.screen_width = width - - - def clear(self): - """ Clear the screen. Does not clear the buffer, just scrolls down past all text. """ - - self.screen_width = width - self.buffer.append(' ') - vim.command('normal! Gzt') - self.screen_top = len(self.buffer) - - - def set_cursor(self, line, column): - """ Set cursor position. """ - - # figure out line - buffer_line = self.screen_top + line - 1 - if buffer_line > len(self.buffer): - for l in range(len(self.buffer) - 1, buffer_line): - self.buffer.append('') - - # figure out column - real_column = column - if len(self.buffer[buffer_line - 1]) < real_column: - self.buffer[buffer_line - 1] = self.buffer[buffer_line - 1] + ' ' * (real_column - len(self.buffer[buffer_line - 1])) - - if not CONQUE_FAST_MODE: - # set cursor at byte index of real_column'th character - vim.command('call cursor(' + str(buffer_line) + ', byteidx(getline(' + str(buffer_line) + '), ' + str(real_column) + '))') - - else: - # old version - # python version is occasionally grumpy - try: - vim.current.window.cursor = (buffer_line, real_column - 1) - except: - vim.command('call cursor(' + str(buffer_line) + ', ' + str(real_column) + ')') - - - def reset_size(self, line): - """ Change screen size """ - - - - - - # save cursor line number - buffer_line = self.screen_top + line - - # reset screen size - self.screen_width = vim.current.window.width - self.screen_height = vim.current.window.height - self.screen_top = len(self.buffer) - vim.current.window.height + 1 - if self.screen_top < 1: - self.screen_top = 1 - - - # align bottom of buffer to bottom of screen - vim.command('normal! ' + str(self.screen_height) + 'kG') - - # return new relative line number - return (buffer_line - self.screen_top) - - - def align(self): - """ align bottom of buffer to bottom of screen """ - vim.command('normal! ' + str(self.screen_height) + 'kG') - - diff --git a/vim/autoload/conque_term/conque_sole.py b/vim/autoload/conque_term/conque_sole.py deleted file mode 100644 index 329988b..0000000 --- a/vim/autoload/conque_term/conque_sole.py +++ /dev/null @@ -1,458 +0,0 @@ -# FILE: autoload/conque_term/conque_sole.py -# AUTHOR: Nico Raffo -# WEBSITE: http://conque.googlecode.com -# MODIFIED: 2011-09-02 -# VERSION: 2.3, for Vim 7.0 -# LICENSE: -# Conque - Vim terminal/console emulator -# Copyright (C) 2009-2011 Nico Raffo -# -# MIT License -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -""" -Windows Console Emulator - -This is the main interface to the Windows emulator. It reads new output from the background console -and updates the Vim buffer. -""" - -import vim - - -class ConqueSole(Conque): - - window_top = None - window_bottom = None - - color_cache = {} - attribute_cache = {} - color_mode = None - color_conceals = {} - - buffer = None - encoding = None - - # counters for periodic rendering - buffer_redraw_ct = 1 - screen_redraw_ct = 1 - - # line offset, shifts output down - offset = 0 - - - def open(self): - """ Start command and initialize this instance - - Arguments: - command - Command string, e.g. "Powershell.exe" - options - Dictionary of config options - python_exe - Path to the python.exe executable. Usually C:\PythonXX\python.exe - communicator_py - Path to subprocess controller script in user's vimfiles directory - - """ - # get arguments - command = vim.eval('command') - options = vim.eval('options') - python_exe = vim.eval('py_exe') - communicator_py = vim.eval('py_vim') - - # init size - self.columns = vim.current.window.width - self.lines = vim.current.window.height - self.window_top = 0 - self.window_bottom = vim.current.window.height - 1 - - # color mode - self.color_mode = vim.eval('g:ConqueTerm_ColorMode') - - # line offset - self.offset = int(options['offset']) - - # init color - self.enable_colors = options['color'] and not CONQUE_FAST_MODE - - # open command - self.proc = ConqueSoleWrapper() - self.proc.open(command, self.lines, self.columns, python_exe, communicator_py, options) - - self.buffer = vim.current.buffer - self.screen_encoding = vim.eval('&fileencoding') - - - def read(self, timeout=1, set_cursor=True, return_output=False, update_buffer=True): - """ Read from console and update Vim buffer. """ - - try: - stats = self.proc.get_stats() - - if not stats: - return - - # disable screen and buffer redraws in fast mode - if not CONQUE_FAST_MODE: - self.buffer_redraw_ct += 1 - self.screen_redraw_ct += 1 - - update_top = 0 - update_bottom = 0 - lines = [] - - # full buffer redraw, our favorite! - #if self.buffer_redraw_ct == CONQUE_SOLE_BUFFER_REDRAW: - # self.buffer_redraw_ct = 0 - # update_top = 0 - # update_bottom = stats['top_offset'] + self.lines - # (lines, attributes) = self.proc.read(update_top, update_bottom) - # if return_output: - # output = self.get_new_output(lines, update_top, stats) - # if update_buffer: - # for i in range(update_top, update_bottom + 1): - # if CONQUE_FAST_MODE: - # self.plain_text(i, lines[i], None, stats) - # else: - # self.plain_text(i, lines[i], attributes[i], stats) - - # full screen redraw - if stats['cursor_y'] + 1 != self.l or stats['top_offset'] != self.window_top or self.screen_redraw_ct >= CONQUE_SOLE_SCREEN_REDRAW: - - self.screen_redraw_ct = 0 - update_top = self.window_top - update_bottom = max([stats['top_offset'] + self.lines + 1, stats['cursor_y']]) - (lines, attributes) = self.proc.read(update_top, update_bottom - update_top + 1) - if return_output: - output = self.get_new_output(lines, update_top, stats) - if update_buffer: - for i in range(update_top, update_bottom + 1): - if CONQUE_FAST_MODE: - self.plain_text(i, lines[i - update_top], None, stats) - else: - self.plain_text(i, lines[i - update_top], attributes[i - update_top], stats) - - - # single line redraw - else: - update_top = stats['cursor_y'] - (lines, attributes) = self.proc.read(update_top, 1) - if return_output: - output = self.get_new_output(lines, update_top, stats) - if update_buffer: - if lines[0].rstrip() != u(self.buffer[update_top].rstrip()): - if CONQUE_FAST_MODE: - self.plain_text(update_top, lines[0], None, stats) - else: - self.plain_text(update_top, lines[0], attributes[0], stats) - - - # reset current position - self.window_top = stats['top_offset'] - self.l = stats['cursor_y'] + 1 - self.c = stats['cursor_x'] + 1 - - # reposition cursor if this seems plausible - if set_cursor: - self.set_cursor(self.l, self.c) - - if return_output: - return output - - except: - - pass - - - def get_new_output(self, lines, update_top, stats): - """ Calculate the "new" output from this read. Fake but useful """ - - if not (stats['cursor_y'] + 1 > self.l or (stats['cursor_y'] + 1 == self.l and stats['cursor_x'] + 1 > self.c)): - return "" - - - - - - - try: - num_to_return = stats['cursor_y'] - self.l + 2 - - lines = lines[self.l - update_top - 1:] - - - new_output = [] - - # first line - new_output.append(lines[0][self.c - 1:].rstrip()) - - # the rest - for i in range(1, num_to_return): - new_output.append(lines[i].rstrip()) - - except: - - pass - - - - return "\n".join(new_output) - - - def plain_text(self, line_nr, text, attributes, stats): - """ Write plain text to Vim buffer. """ - - - - - - # handle line offset - line_nr += self.offset - - self.l = line_nr + 1 - - # remove trailing whitespace - text = text.rstrip() - - # if we're using concealed text for color, then s- is weird - if self.color_mode == 'conceal': - - text = self.add_conceal_color(text, attributes, stats, line_nr) - - - # deal with character encoding - if CONQUE_PYTHON_VERSION == 2: - val = text.encode(self.screen_encoding) - else: - # XXX / Vim's python3 interface doesn't accept bytes object - val = str(text) - - # update vim buffer - if len(self.buffer) <= line_nr: - self.buffer.append(val) - else: - self.buffer[line_nr] = val - - if self.enable_colors and not self.color_mode == 'conceal' and line_nr > self.l - CONQUE_MAX_SYNTAX_LINES: - relevant = attributes[0:len(text)] - if line_nr not in self.attribute_cache or self.attribute_cache[line_nr] != relevant: - self.do_color(attributes=relevant, stats=stats) - self.attribute_cache[line_nr] = relevant - - - def add_conceal_color(self, text, attributes, stats, line_nr): - """ Add 'conceal' color strings to output text """ - - # stop here if coloration is disabled - if not self.enable_colors: - return text - - # if no colors for this line, clear everything out - if len(attributes) == 0 or attributes == u(chr(stats['default_attribute'])) * len(attributes): - return text - - new_text = '' - self.color_conceals[line_nr] = [] - - attribute_chunks = CONQUE_WIN32_REGEX_ATTR.findall(attributes) - offset = 0 - ends = [] - for attr in attribute_chunks: - attr_num = ord(attr[1]) - ends = [] - if attr_num != stats['default_attribute']: - - color = self.translate_color(attr_num) - - new_text += chr(27) + 'sf' + color['fg_code'] + ';' - ends.append(chr(27) + 'ef' + color['fg_code'] + ';') - self.color_conceals[line_nr].append(offset) - - if attr_num > 15: - new_text += chr(27) + 'sb' + color['bg_code'] + ';' - ends.append(chr(27) + 'eb' + color['bg_code'] + ';') - self.color_conceals[line_nr].append(offset) - - new_text += text[offset:offset + len(attr[0])] - - # close color regions - ends.reverse() - for i in range(0, len(ends)): - self.color_conceals[line_nr].append(len(new_text)) - new_text += ends[i] - - offset += len(attr[0]) - - return new_text - - - def do_color(self, start=0, end=0, attributes='', stats=None): - """ Convert Windows console attributes into Vim syntax highlighting """ - - # if no colors for this line, clear everything out - if len(attributes) == 0 or attributes == u(chr(stats['default_attribute'])) * len(attributes): - self.color_changes = {} - self.apply_color(1, len(attributes), self.l) - return - - attribute_chunks = CONQUE_WIN32_REGEX_ATTR.findall(attributes) - offset = 0 - for attr in attribute_chunks: - attr_num = ord(attr[1]) - if attr_num != stats['default_attribute']: - self.color_changes = self.translate_color(attr_num) - self.apply_color(offset + 1, offset + len(attr[0]) + 1, self.l) - offset += len(attr[0]) - - - def translate_color(self, attr): - """ Convert Windows console attributes into RGB colors """ - - # check for cached color - if attr in self.color_cache: - return self.color_cache[attr] - - - - - - - # convert attribute integer to bit string - bit_str = bin(attr) - bit_str = bit_str.replace('0b', '') - - # slice foreground and background portions of bit string - fg = bit_str[-4:].rjust(4, '0') - bg = bit_str[-8:-4].rjust(4, '0') - - # ok, first create foreground #rbg - red = int(fg[1]) * 204 + int(fg[0]) * int(fg[1]) * 51 - green = int(fg[2]) * 204 + int(fg[0]) * int(fg[2]) * 51 - blue = int(fg[3]) * 204 + int(fg[0]) * int(fg[3]) * 51 - fg_str = "#%02x%02x%02x" % (red, green, blue) - fg_code = "%02x%02x%02x" % (red, green, blue) - fg_code = fg_code[0] + fg_code[2] + fg_code[4] - - # ok, first create foreground #rbg - red = int(bg[1]) * 204 + int(bg[0]) * int(bg[1]) * 51 - green = int(bg[2]) * 204 + int(bg[0]) * int(bg[2]) * 51 - blue = int(bg[3]) * 204 + int(bg[0]) * int(bg[3]) * 51 - bg_str = "#%02x%02x%02x" % (red, green, blue) - bg_code = "%02x%02x%02x" % (red, green, blue) - bg_code = bg_code[0] + bg_code[2] + bg_code[4] - - # build value for color_changes - - color = {'guifg': fg_str, 'guibg': bg_str} - - if self.color_mode == 'conceal': - color['fg_code'] = fg_code - color['bg_code'] = bg_code - - self.color_cache[attr] = color - - return color - - - def write_vk(self, vk_code): - """ write virtual key code to shared memory using proprietary escape seq """ - - self.proc.write_vk(vk_code) - - - def update_window_size(self): - """ Resize underlying console if Vim buffer size has changed """ - - if vim.current.window.width != self.columns or vim.current.window.height != self.lines: - - - - # reset all window size attributes to default - self.columns = vim.current.window.width - self.lines = vim.current.window.height - self.working_columns = vim.current.window.width - self.working_lines = vim.current.window.height - self.bottom = vim.current.window.height - - self.proc.window_resize(vim.current.window.height, vim.current.window.width) - - - def set_cursor(self, line, column): - """ Update cursor position in Vim buffer """ - - - - # handle offset - line += self.offset - - # shift cursor position to handle concealed text - if self.enable_colors and self.color_mode == 'conceal': - if line - 1 in self.color_conceals: - for c in self.color_conceals[line - 1]: - if c < column: - column += 7 - else: - break - - - - # figure out line - buffer_line = line - if buffer_line > len(self.buffer): - for l in range(len(self.buffer) - 1, buffer_line): - self.buffer.append('') - - # figure out column - real_column = column - if len(self.buffer[buffer_line - 1]) < real_column: - self.buffer[buffer_line - 1] = self.buffer[buffer_line - 1] + ' ' * (real_column - len(self.buffer[buffer_line - 1])) - - # python version is occasionally grumpy - try: - vim.current.window.cursor = (buffer_line, real_column - 1) - except: - vim.command('call cursor(' + str(buffer_line) + ', ' + str(real_column) + ')') - - - def idle(self): - """ go into idle mode """ - - self.proc.idle() - - - def resume(self): - """ resume from idle mode """ - - self.proc.resume() - - - def close(self): - """ end console subprocess """ - self.proc.close() - - - def abort(self): - """ end subprocess forcefully """ - self.proc.close() - - - def get_buffer_line(self, line): - """ get buffer line """ - return line - - -# vim:foldmethod=marker diff --git a/vim/autoload/conque_term/conque_sole_communicator.py b/vim/autoload/conque_term/conque_sole_communicator.py deleted file mode 100644 index 39f1bd8..0000000 --- a/vim/autoload/conque_term/conque_sole_communicator.py +++ /dev/null @@ -1,183 +0,0 @@ -# FILE: autoload/conque_term/conque_sole_communicator.py -# AUTHOR: Nico Raffo -# WEBSITE: http://conque.googlecode.com -# MODIFIED: 2011-09-02 -# VERSION: 2.3, for Vim 7.0 -# LICENSE: -# Conque - Vim terminal/console emulator -# Copyright (C) 2009-2011 Nico Raffo -# -# MIT License -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -""" - -ConqueSoleCommunicator - -This script will create a new Windows console and start the requested program -inside of it. This process is launched independently from the parent Vim -program, so it has no access to the vim module. - -The main loop in this script reads data from the console and syncs it onto -blocks of memory shared with the Vim process. In this way the Vim process -and this script can communicate with each other. - -""" - -import time -import sys - -from conque_globals import * -from conque_win32_util import * -from conque_sole_subprocess import * -from conque_sole_shared_memory import * - -############################################################## -# only run if this file was run directly - -if __name__ == '__main__': - - # attempt to catch ALL exceptions to fend of zombies - try: - - # simple arg validation - - if len(sys.argv) < 5: - - exit() - - # maximum time this thing reads. 0 means no limit. Only for testing. - max_loops = 0 - - # read interval, in seconds - sleep_time = 0.01 - - # idle read interval, in seconds - idle_sleep_time = 0.10 - - # are we idled? - is_idle = False - - # mem key - mem_key = sys.argv[1] - - # console width - console_width = int(sys.argv[2]) - - # console height - console_height = int(sys.argv[3]) - - # code page - code_page = int(sys.argv[4]) - - # code page - fast_mode = int(sys.argv[5]) - - # the actual subprocess to run - cmd_line = " ".join(sys.argv[6:]) - - - # width and height - options = {'LINES': console_height, 'COLUMNS': console_width, 'CODE_PAGE': code_page, 'FAST_MODE': fast_mode} - - - - # set initial idle status - shm_command = ConqueSoleSharedMemory(CONQUE_SOLE_COMMANDS_SIZE, 'command', mem_key, serialize=True) - shm_command.create('write') - - cmd = shm_command.read() - if cmd: - - if cmd['cmd'] == 'idle': - is_idle = True - shm_command.clear() - - - ############################################################## - # Create the subprocess - - proc = ConqueSoleSubprocess() - res = proc.open(cmd_line, mem_key, options) - - if not res: - - exit() - - ############################################################## - # main loop! - - loops = 0 - - while True: - - # check for idle/resume - if is_idle or loops % 25 == 0: - - # check process health - if not proc.is_alive(): - - proc.close() - break - - # check for change in buffer focus - cmd = shm_command.read() - if cmd: - - if cmd['cmd'] == 'idle': - is_idle = True - shm_command.clear() - - elif cmd['cmd'] == 'resume': - is_idle = False - shm_command.clear() - - - # sleep between loops if moderation is requested - if sleep_time > 0: - if is_idle: - time.sleep(idle_sleep_time) - else: - time.sleep(sleep_time) - - # write, read, etc - proc.write() - proc.read() - - # increment loops, and exit if max has been reached - loops += 1 - if max_loops and loops >= max_loops: - - break - - ############################################################## - # all done! - - - - proc.close() - - # if an exception was thrown, croak - except: - - proc.close() - - -# vim:foldmethod=marker diff --git a/vim/autoload/conque_term/conque_sole_shared_memory.py b/vim/autoload/conque_term/conque_sole_shared_memory.py deleted file mode 100644 index fa44ab3..0000000 --- a/vim/autoload/conque_term/conque_sole_shared_memory.py +++ /dev/null @@ -1,210 +0,0 @@ -# FILE: autoload/conque_term/conque_sole_shared_memory.py -# AUTHOR: Nico Raffo -# WEBSITE: http://conque.googlecode.com -# MODIFIED: 2011-09-02 -# VERSION: 2.3, for Vim 7.0 -# LICENSE: -# Conque - Vim terminal/console emulator -# Copyright (C) 2009-2011 Nico Raffo -# -# MIT License -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -""" -Wrapper class for shared memory between Windows python processes - -Adds a small amount of functionality to the standard mmap module. - -""" - -import mmap -import sys - -# PYTHON VERSION -CONQUE_PYTHON_VERSION = sys.version_info[0] - -if CONQUE_PYTHON_VERSION == 2: - import cPickle as pickle -else: - import pickle - - -class ConqueSoleSharedMemory(): - - # is the data being stored not fixed length - fixed_length = False - - # maximum number of bytes per character, for fixed width blocks - char_width = 1 - - # fill memory with this character when clearing and fixed_length is true - FILL_CHAR = None - - # serialize and unserialize data automatically - serialize = False - - # size of shared memory, in bytes / chars - mem_size = None - - # size of shared memory, in bytes / chars - mem_type = None - - # unique key, so multiple console instances are possible - mem_key = None - - # mmap instance - shm = None - - # character encoding, dammit - encoding = 'utf-8' - - # pickle terminator - TERMINATOR = None - - - def __init__(self, mem_size, mem_type, mem_key, fixed_length=False, fill_char=' ', serialize=False, encoding='utf-8'): - """ Initialize new shared memory block instance - - Arguments: - mem_size -- Memory size in characters, depends on encoding argument to calcuate byte size - mem_type -- Label to identify what will be stored - mem_key -- Unique, probably random key to identify this block - fixed_length -- If set to true, assume the data stored will always fill the memory size - fill_char -- Initialize memory block with this character, only really helpful with fixed_length blocks - serialize -- Automatically serialize data passed to write. Allows storing non-byte data - encoding -- Character encoding to use when storing character data - - """ - self.mem_size = mem_size - self.mem_type = mem_type - self.mem_key = mem_key - self.fixed_length = fixed_length - self.fill_char = fill_char - self.serialize = serialize - self.encoding = encoding - self.TERMINATOR = str(chr(0)).encode(self.encoding) - - if CONQUE_PYTHON_VERSION == 3: - self.FILL_CHAR = fill_char - else: - self.FILL_CHAR = unicode(fill_char) - - if fixed_length and encoding == 'utf-8': - self.char_width = 4 - - - def create(self, access='write'): - """ Create a new block of shared memory using the mmap module. """ - - if access == 'write': - mmap_access = mmap.ACCESS_WRITE - else: - mmap_access = mmap.ACCESS_READ - - name = "conque_%s_%s" % (self.mem_type, self.mem_key) - - self.shm = mmap.mmap(0, self.mem_size * self.char_width, name, mmap_access) - - if not self.shm: - return False - else: - return True - - - def read(self, chars=1, start=0): - """ Read data from shared memory. - - If this is a fixed length block, read 'chars' characters from memory. - Otherwise read up until the TERMINATOR character (null byte). - If this memory is serialized, unserialize it automatically. - - """ - # go to start position - self.shm.seek(start * self.char_width) - - if self.fixed_length: - chars = chars * self.char_width - else: - chars = self.shm.find(self.TERMINATOR) - - if chars == 0: - return '' - - shm_str = self.shm.read(chars) - - # return unpickled byte object - if self.serialize: - return pickle.loads(shm_str) - - # decode byes in python 3 - if CONQUE_PYTHON_VERSION == 3: - return str(shm_str, self.encoding) - - # encoding - if self.encoding != 'ascii': - shm_str = unicode(shm_str, self.encoding) - - return shm_str - - - def write(self, text, start=0): - """ Write data to memory. - - If memory is fixed length, simply write the 'text' characters at 'start' position. - Otherwise write 'text' characters and append a null character. - If memory is serializable, do so first. - - """ - # simple scenario, let pickle create bytes - if self.serialize: - if CONQUE_PYTHON_VERSION == 3: - tb = pickle.dumps(text, 0) - else: - tb = pickle.dumps(text, 0).encode(self.encoding) - - else: - tb = text.encode(self.encoding, 'replace') - - # write to memory - self.shm.seek(start * self.char_width) - - if self.fixed_length: - self.shm.write(tb) - else: - self.shm.write(tb + self.TERMINATOR) - - - def clear(self, start=0): - """ Clear memory block using self.fill_char. """ - - self.shm.seek(start) - - if self.fixed_length: - self.shm.write(str(self.fill_char * self.mem_size * self.char_width).encode(self.encoding)) - else: - self.shm.write(self.TERMINATOR) - - - def close(self): - """ Close/destroy memory block. """ - - self.shm.close() - - diff --git a/vim/autoload/conque_term/conque_sole_subprocess.py b/vim/autoload/conque_term/conque_sole_subprocess.py deleted file mode 100644 index 3ba7509..0000000 --- a/vim/autoload/conque_term/conque_sole_subprocess.py +++ /dev/null @@ -1,762 +0,0 @@ -# FILE: autoload/conque_term/conque_sole_subprocess.py -# AUTHOR: Nico Raffo -# WEBSITE: http://conque.googlecode.com -# MODIFIED: 2011-09-02 -# VERSION: 2.3, for Vim 7.0 -# LICENSE: -# Conque - Vim terminal/console emulator -# Copyright (C) 2009-2011 Nico Raffo -# -# MIT License -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -""" ConqueSoleSubprocess - -Creates a new subprocess with it's own (hidden) console window. - -Mirrors console window text onto a block of shared memory (mmap), along with -text attribute data. Also handles translation of text input into the format -Windows console expects. - -Sample Usage: - - sh = ConqueSoleSubprocess() - sh.open("cmd.exe", "unique_str") - - shm_in = ConqueSoleSharedMemory(mem_key = "unique_str", mem_type = "input", ...) - shm_out = ConqueSoleSharedMemory(mem_key = "unique_str", mem_type = "output", ...) - - output = shm_out.read(...) - shm_in.write("dir\r") - output = shm_out.read(...) - -""" - -import time -import re -import os -import ctypes - -from conque_globals import * -from conque_win32_util import * -from conque_sole_shared_memory import * - - -class ConqueSoleSubprocess(): - - # subprocess handle and pid - handle = None - pid = None - - # input / output handles - stdin = None - stdout = None - - # size of console window - window_width = 160 - window_height = 40 - - # max lines for the console buffer - buffer_width = 160 - buffer_height = 100 - - # keep track of the buffer number at the top of the window - top = 0 - line_offset = 0 - - # buffer height is CONQUE_SOLE_BUFFER_LENGTH * output_blocks - output_blocks = 1 - - # cursor position - cursor_line = 0 - cursor_col = 0 - - # console data, array of lines - data = [] - - # console attribute data, array of array of int - attributes = [] - attribute_cache = {} - - # default attribute - default_attribute = 7 - - # shared memory objects - shm_input = None - shm_output = None - shm_attributes = None - shm_stats = None - shm_command = None - shm_rescroll = None - shm_resize = None - - # are we still a valid process? - is_alive = True - - # running in fast mode - fast_mode = 0 - - # used for periodic execution of screen and memory redrawing - screen_redraw_ct = 0 - mem_redraw_ct = 0 - - - def open(self, cmd, mem_key, options={}): - """ Create subproccess running in hidden console window. """ - - - - self.reset = True - - try: - # if we're already attached to a console, then unattach - try: - ctypes.windll.kernel32.FreeConsole() - except: - pass - - # set buffer height - self.buffer_height = CONQUE_SOLE_BUFFER_LENGTH - - if 'LINES' in options and 'COLUMNS' in options: - self.window_width = options['COLUMNS'] - self.window_height = options['LINES'] - self.buffer_width = options['COLUMNS'] - - # fast mode - self.fast_mode = options['FAST_MODE'] - - # console window options - si = STARTUPINFO() - - # hide window - si.dwFlags |= STARTF_USESHOWWINDOW - si.wShowWindow = SW_HIDE - #si.wShowWindow = SW_MINIMIZE - - # process options - flags = NORMAL_PRIORITY_CLASS | CREATE_NEW_PROCESS_GROUP | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_CONSOLE - - # created process info - pi = PROCESS_INFORMATION() - - - - # create the process! - res = ctypes.windll.kernel32.CreateProcessW(None, u(cmd), None, None, 0, flags, None, u('.'), ctypes.byref(si), ctypes.byref(pi)) - - - - - - # process info - self.pid = pi.dwProcessId - self.handle = pi.hProcess - - - - - # attach ourselves to the new console - # console is not immediately available - for i in range(10): - time.sleep(0.25) - try: - - res = ctypes.windll.kernel32.AttachConsole(self.pid) - - - - - - - break - except: - - pass - - # get input / output handles - self.stdout = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) - self.stdin = ctypes.windll.kernel32.GetStdHandle(STD_INPUT_HANDLE) - - # set buffer size - size = COORD(self.buffer_width, self.buffer_height) - res = ctypes.windll.kernel32.SetConsoleScreenBufferSize(self.stdout, size) - - - - - - - - # prev set size call needs to process - time.sleep(0.2) - - # set window size - self.set_window_size(self.window_width, self.window_height) - - # set utf-8 code page - if 'CODE_PAGE' in options and options['CODE_PAGE'] > 0: - if ctypes.windll.kernel32.IsValidCodePage(ctypes.c_uint(options['CODE_PAGE'])): - - ctypes.windll.kernel32.SetConsoleCP(ctypes.c_uint(options['CODE_PAGE'])) - ctypes.windll.kernel32.SetConsoleOutputCP(ctypes.c_uint(options['CODE_PAGE'])) - - # init shared memory - self.init_shared_memory(mem_key) - - # init read buffers - self.tc = ctypes.create_unicode_buffer(self.buffer_width) - self.ac = ctypes.create_unicode_buffer(self.buffer_width) - - return True - - except: - - return False - - - def init_shared_memory(self, mem_key): - """ Create shared memory objects. """ - - self.shm_input = ConqueSoleSharedMemory(CONQUE_SOLE_INPUT_SIZE, 'input', mem_key) - self.shm_input.create('write') - self.shm_input.clear() - - self.shm_output = ConqueSoleSharedMemory(self.buffer_height * self.buffer_width, 'output', mem_key, True) - self.shm_output.create('write') - self.shm_output.clear() - - if not self.fast_mode: - buf_info = self.get_buffer_info() - self.shm_attributes = ConqueSoleSharedMemory(self.buffer_height * self.buffer_width, 'attributes', mem_key, True, chr(buf_info.wAttributes), encoding='latin-1') - self.shm_attributes.create('write') - self.shm_attributes.clear() - - self.shm_stats = ConqueSoleSharedMemory(CONQUE_SOLE_STATS_SIZE, 'stats', mem_key, serialize=True) - self.shm_stats.create('write') - self.shm_stats.clear() - - self.shm_command = ConqueSoleSharedMemory(CONQUE_SOLE_COMMANDS_SIZE, 'command', mem_key, serialize=True) - self.shm_command.create('write') - self.shm_command.clear() - - self.shm_resize = ConqueSoleSharedMemory(CONQUE_SOLE_RESIZE_SIZE, 'resize', mem_key, serialize=True) - self.shm_resize.create('write') - self.shm_resize.clear() - - self.shm_rescroll = ConqueSoleSharedMemory(CONQUE_SOLE_RESCROLL_SIZE, 'rescroll', mem_key, serialize=True) - self.shm_rescroll.create('write') - self.shm_rescroll.clear() - - return True - - - def check_commands(self): - """ Check for and process commands from Vim. """ - - cmd = self.shm_command.read() - - if cmd: - - # shut it all down - if cmd['cmd'] == 'close': - - # clear command - self.shm_command.clear() - - self.close() - return - - cmd = self.shm_resize.read() - - if cmd: - - # clear command - self.shm_resize.clear() - - # resize console - if cmd['cmd'] == 'resize': - - - - # only change buffer width if it's larger - if cmd['data']['width'] > self.buffer_width: - self.buffer_width = cmd['data']['width'] - - # always change console width and height - self.window_width = cmd['data']['width'] - self.window_height = cmd['data']['height'] - - # reset the console - buf_info = self.get_buffer_info() - self.reset_console(buf_info, add_block=False) - - - def read(self): - """ Read from windows console and update shared memory blocks. """ - - # no point really - if self.screen_redraw_ct == 0 and not self.is_alive(): - stats = {'top_offset': 0, 'default_attribute': 0, 'cursor_x': 0, 'cursor_y': self.cursor_line, 'is_alive': 0} - - self.shm_stats.write(stats) - return - - # check for commands - self.check_commands() - - # get cursor position - buf_info = self.get_buffer_info() - curs_line = buf_info.dwCursorPosition.Y - curs_col = buf_info.dwCursorPosition.X - - # set update range - if curs_line != self.cursor_line or self.top != buf_info.srWindow.Top or self.screen_redraw_ct == CONQUE_SOLE_SCREEN_REDRAW: - self.screen_redraw_ct = 0 - - read_start = self.top - read_end = max([buf_info.srWindow.Bottom + 1, curs_line + 1]) - else: - - read_start = curs_line - read_end = curs_line + 1 - - - - - # vars used in for loop - coord = COORD(0, 0) - chars_read = ctypes.c_int(0) - - # read new data - for i in range(read_start, read_end): - - coord.Y = i - - res = ctypes.windll.kernel32.ReadConsoleOutputCharacterW(self.stdout, ctypes.byref(self.tc), self.buffer_width, coord, ctypes.byref(chars_read)) - if not self.fast_mode: - ctypes.windll.kernel32.ReadConsoleOutputAttribute(self.stdout, ctypes.byref(self.ac), self.buffer_width, coord, ctypes.byref(chars_read)) - - t = self.tc.value - if not self.fast_mode: - a = self.ac.value - - # add data - if i >= len(self.data): - for j in range(len(self.data), i + 1): - self.data.append('') - if not self.fast_mode: - self.attributes.append('') - - self.data[i] = t - if not self.fast_mode: - self.attributes[i] = a - - - - - #for i in range(0, len(t)): - - - - - # write new output to shared memory - try: - if self.mem_redraw_ct == CONQUE_SOLE_MEM_REDRAW: - self.mem_redraw_ct = 0 - - for i in range(0, len(self.data)): - self.shm_output.write(text=self.data[i], start=self.buffer_width * i) - if not self.fast_mode: - self.shm_attributes.write(text=self.attributes[i], start=self.buffer_width * i) - else: - - for i in range(read_start, read_end): - self.shm_output.write(text=self.data[i], start=self.buffer_width * i) - if not self.fast_mode: - self.shm_attributes.write(text=self.attributes[i], start=self.buffer_width * i) - #self.shm_output.write(text=''.join(self.data[read_start:read_end]), start=read_start * self.buffer_width) - #self.shm_attributes.write(text=''.join(self.attributes[read_start:read_end]), start=read_start * self.buffer_width) - - # write cursor position to shared memory - stats = {'top_offset': buf_info.srWindow.Top, 'default_attribute': buf_info.wAttributes, 'cursor_x': curs_col, 'cursor_y': curs_line, 'is_alive': 1} - self.shm_stats.write(stats) - - # adjust screen position - self.top = buf_info.srWindow.Top - self.cursor_line = curs_line - - # check for reset - if curs_line > buf_info.dwSize.Y - 200: - self.reset_console(buf_info) - - except: - - - - - pass - - # increment redraw counters - self.screen_redraw_ct += 1 - self.mem_redraw_ct += 1 - - return None - - - def reset_console(self, buf_info, add_block=True): - """ Extend the height of the current console if the cursor postion gets within 200 lines of the current size. """ - - # sometimes we just want to change the buffer width, - # in which case no need to add another block - if add_block: - self.output_blocks += 1 - - # close down old memory - self.shm_output.close() - self.shm_output = None - - if not self.fast_mode: - self.shm_attributes.close() - self.shm_attributes = None - - # new shared memory key - mem_key = 'mk' + str(time.time()) - - # reallocate memory - self.shm_output = ConqueSoleSharedMemory(self.buffer_height * self.buffer_width * self.output_blocks, 'output', mem_key, True) - self.shm_output.create('write') - self.shm_output.clear() - - # backfill data - if len(self.data[0]) < self.buffer_width: - for i in range(0, len(self.data)): - self.data[i] = self.data[i] + ' ' * (self.buffer_width - len(self.data[i])) - self.shm_output.write(''.join(self.data)) - - if not self.fast_mode: - self.shm_attributes = ConqueSoleSharedMemory(self.buffer_height * self.buffer_width * self.output_blocks, 'attributes', mem_key, True, chr(buf_info.wAttributes), encoding='latin-1') - self.shm_attributes.create('write') - self.shm_attributes.clear() - - # backfill attributes - if len(self.attributes[0]) < self.buffer_width: - for i in range(0, len(self.attributes)): - self.attributes[i] = self.attributes[i] + chr(buf_info.wAttributes) * (self.buffer_width - len(self.attributes[i])) - if not self.fast_mode: - self.shm_attributes.write(''.join(self.attributes)) - - # notify wrapper of new output block - self.shm_rescroll.write({'cmd': 'new_output', 'data': {'blocks': self.output_blocks, 'mem_key': mem_key}}) - - # set buffer size - size = COORD(X=self.buffer_width, Y=self.buffer_height * self.output_blocks) - - res = ctypes.windll.kernel32.SetConsoleScreenBufferSize(self.stdout, size) - - - - - - - # prev set size call needs to process - time.sleep(0.2) - - # set window size - self.set_window_size(self.window_width, self.window_height) - - # init read buffers - self.tc = ctypes.create_unicode_buffer(self.buffer_width) - self.ac = ctypes.create_unicode_buffer(self.buffer_width) - - - - def write(self): - """ Write text to console. - - This function just parses out special sequences for special key events - and passes on the text to the plain or virtual key functions. - - """ - # get input from shared mem - text = self.shm_input.read() - - # nothing to do here - if text == u(''): - return - - - - # clear input queue - self.shm_input.clear() - - # split on VK codes - chunks = CONQUE_WIN32_REGEX_VK.split(text) - - # if len() is one then no vks - if len(chunks) == 1: - self.write_plain(text) - return - - - - # loop over chunks and delegate - for t in chunks: - - if t == '': - continue - - if CONQUE_WIN32_REGEX_VK.match(t): - - self.write_vk(t[2:-2]) - else: - self.write_plain(t) - - - def write_plain(self, text): - """ Write simple text to subprocess. """ - - li = INPUT_RECORD * len(text) - list_input = li() - - for i in range(0, len(text)): - - # create keyboard input - ke = KEY_EVENT_RECORD() - ke.bKeyDown = ctypes.c_byte(1) - ke.wRepeatCount = ctypes.c_short(1) - - cnum = ord(text[i]) - - ke.wVirtualKeyCode = ctypes.windll.user32.VkKeyScanW(cnum) - ke.wVirtualScanCode = ctypes.c_short(ctypes.windll.user32.MapVirtualKeyW(int(cnum), 0)) - - if cnum > 31: - ke.uChar.UnicodeChar = uchr(cnum) - elif cnum == 3: - ctypes.windll.kernel32.GenerateConsoleCtrlEvent(0, self.pid) - ke.uChar.UnicodeChar = uchr(cnum) - ke.wVirtualKeyCode = ctypes.windll.user32.VkKeyScanW(cnum + 96) - ke.dwControlKeyState |= LEFT_CTRL_PRESSED - else: - ke.uChar.UnicodeChar = uchr(cnum) - if cnum in CONQUE_WINDOWS_VK_INV: - ke.wVirtualKeyCode = cnum - else: - ke.wVirtualKeyCode = ctypes.windll.user32.VkKeyScanW(cnum + 96) - ke.dwControlKeyState |= LEFT_CTRL_PRESSED - - - - - kc = INPUT_RECORD(KEY_EVENT) - kc.Event.KeyEvent = ke - list_input[i] = kc - - - - # write input array - events_written = ctypes.c_int() - res = ctypes.windll.kernel32.WriteConsoleInputW(self.stdin, list_input, len(text), ctypes.byref(events_written)) - - - - - - - - - def write_vk(self, vk_code): - """ Write special characters to console subprocess. """ - - - - code = None - ctrl_pressed = False - - # this could be made more generic when more attributes - # other than ctrl_pressed are available - vk_attributes = vk_code.split(';') - - for attr in vk_attributes: - if attr == CONQUE_VK_ATTR_CTRL_PRESSED: - ctrl_pressed = True - else: - code = attr - - li = INPUT_RECORD * 1 - - # create keyboard input - ke = KEY_EVENT_RECORD() - ke.uChar.UnicodeChar = uchr(0) - ke.wVirtualKeyCode = ctypes.c_short(int(code)) - ke.wVirtualScanCode = ctypes.c_short(ctypes.windll.user32.MapVirtualKeyW(int(code), 0)) - ke.bKeyDown = ctypes.c_byte(1) - ke.wRepeatCount = ctypes.c_short(1) - - # set enhanced key mode for arrow keys - if code in CONQUE_WINDOWS_VK_ENHANCED: - - ke.dwControlKeyState |= ENHANCED_KEY - - if ctrl_pressed: - ke.dwControlKeyState |= LEFT_CTRL_PRESSED - - kc = INPUT_RECORD(KEY_EVENT) - kc.Event.KeyEvent = ke - list_input = li(kc) - - # write input array - events_written = ctypes.c_int() - res = ctypes.windll.kernel32.WriteConsoleInputW(self.stdin, list_input, 1, ctypes.byref(events_written)) - - - - - - - - def close(self): - """ Close all running subproccesses """ - - # record status - self.is_alive = False - try: - stats = {'top_offset': 0, 'default_attribute': 0, 'cursor_x': 0, 'cursor_y': self.cursor_line, 'is_alive': 0} - self.shm_stats.write(stats) - except: - pass - - pid_list = (ctypes.c_int * 10)() - num = ctypes.windll.kernel32.GetConsoleProcessList(pid_list, 10) - - - - current_pid = os.getpid() - - - - - - # kill subprocess pids - for pid in pid_list[0:num]: - if not pid: - break - - # kill current pid last - if pid == current_pid: - continue - try: - self.close_pid(pid) - except: - - pass - - # kill this process - try: - self.close_pid(current_pid) - except: - - pass - - - def close_pid(self, pid): - """ Terminate a single process. """ - - - handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, 0, pid) - ctypes.windll.kernel32.TerminateProcess(handle, -1) - ctypes.windll.kernel32.CloseHandle(handle) - - - def is_alive(self): - """ Check process health. """ - - status = ctypes.windll.kernel32.WaitForSingleObject(self.handle, 1) - - if status == 0: - - self.is_alive = False - - return self.is_alive - - - def get_screen_text(self): - """ Return screen data as string. """ - - return "\n".join(self.data) - - - def set_window_size(self, width, height): - """ Change Windows console size. """ - - - - # get current window size object - window_size = SMALL_RECT(0, 0, 0, 0) - - # buffer info has maximum window size data - buf_info = self.get_buffer_info() - - - # set top left corner - window_size.Top = 0 - window_size.Left = 0 - - # set bottom right corner - if buf_info.dwMaximumWindowSize.X < width: - - window_size.Right = buf_info.dwMaximumWindowSize.X - 1 - else: - window_size.Right = width - 1 - - if buf_info.dwMaximumWindowSize.Y < height: - - window_size.Bottom = buf_info.dwMaximumWindowSize.Y - 1 - else: - window_size.Bottom = height - 1 - - - - # set the window size! - res = ctypes.windll.kernel32.SetConsoleWindowInfo(self.stdout, ctypes.c_bool(True), ctypes.byref(window_size)) - - - - - - - # reread buffer info to get final console max lines - buf_info = self.get_buffer_info() - - self.window_width = buf_info.srWindow.Right + 1 - self.window_height = buf_info.srWindow.Bottom + 1 - - - def get_buffer_info(self): - """ Retrieve commonly-used buffer information. """ - - buf_info = CONSOLE_SCREEN_BUFFER_INFO() - ctypes.windll.kernel32.GetConsoleScreenBufferInfo(self.stdout, ctypes.byref(buf_info)) - - return buf_info - - - diff --git a/vim/autoload/conque_term/conque_sole_wrapper.py b/vim/autoload/conque_term/conque_sole_wrapper.py deleted file mode 100644 index 1c333f9..0000000 --- a/vim/autoload/conque_term/conque_sole_wrapper.py +++ /dev/null @@ -1,278 +0,0 @@ -# FILE: autoload/conque_term/conque_sole_wrapper.py -# AUTHOR: Nico Raffo -# WEBSITE: http://conque.googlecode.com -# MODIFIED: 2011-09-02 -# VERSION: 2.3, for Vim 7.0 -# LICENSE: -# Conque - Vim terminal/console emulator -# Copyright (C) 2009-2011 Nico Raffo -# -# MIT License -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -""" - -ConqueSoleSubprocessWrapper - -Subprocess wrapper to deal with Windows insanity. Launches console based python, -which in turn launches originally requested command. Communicates with cosole -python through shared memory objects. - -""" - -import ctypes -import time - - -class ConqueSoleWrapper(): - - # unique key used for shared memory block names - shm_key = '' - - # process info - handle = None - pid = None - - # queue input in this bucket - bucket = None - - # console size - lines = 24 - columns = 80 - - # shared memory objects - shm_input = None - shm_output = None - shm_attributes = None - shm_stats = None - shm_command = None - shm_rescroll = None - shm_resize = None - - # console python process - proc = None - - - def open(self, cmd, lines, columns, python_exe='python.exe', communicator_py='conque_sole_communicator.py', options={}): - """ Launch python.exe subprocess which will in turn launch the user's program. - - Arguments: - cmd -- The user's command to run. E.g. "Powershell.exe" or "C:\Python27\Scripts\ipython.bat" - lines, columns -- The size of the console, also the size of the Vim buffer - python.exe -- The path to the python executable, typically C:\PythonXX\python.exe - communicator_py -- The path to the subprocess controller script in the user's vimfiles directory - options -- optional configuration - - """ - self.lines = lines - self.columns = columns - self.bucket = u('') - - # create a shm key - self.shm_key = 'mk' + str(time.time()) - - # python command - cmd_line = '%s "%s" %s %d %d %d %d %s' % (python_exe, communicator_py, self.shm_key, int(self.columns), int(self.lines), int(options['CODE_PAGE']), int(CONQUE_FAST_MODE), cmd) - - - # console window attributes - flags = NORMAL_PRIORITY_CLASS | DETACHED_PROCESS | CREATE_UNICODE_ENVIRONMENT - si = STARTUPINFO() - pi = PROCESS_INFORMATION() - - # start the stupid process already - try: - res = ctypes.windll.kernel32.CreateProcessW(None, u(cmd_line), None, None, 0, flags, None, u('.'), ctypes.byref(si), ctypes.byref(pi)) - except: - - raise - - # handle - self.pid = pi.dwProcessId - - - - # init shared memory objects - self.init_shared_memory(self.shm_key) - - - def read(self, start_line, num_lines, timeout=0): - """ Read a range of console lines from shared memory. - - Returns a pair of lists containing the console text and console text attributes. - - """ - # emulate timeout by sleeping timeout time - if timeout > 0: - read_timeout = float(timeout) / 1000 - - time.sleep(read_timeout) - - output = [] - attributes = [] - - # get output - for i in range(start_line, start_line + num_lines + 1): - output.append(self.shm_output.read(self.columns, i * self.columns)) - if not CONQUE_FAST_MODE: - attributes.append(self.shm_attributes.read(self.columns, i * self.columns)) - - return (output, attributes) - - - def get_stats(self): - """ Return a dictionary with current console cursor and scrolling information. """ - - try: - rescroll = self.shm_rescroll.read() - if rescroll != '' and rescroll != None: - - - - self.shm_rescroll.clear() - - # close down old memory - self.shm_output.close() - self.shm_output = None - - if not CONQUE_FAST_MODE: - self.shm_attributes.close() - self.shm_attributes = None - - # reallocate memory - - self.shm_output = ConqueSoleSharedMemory(CONQUE_SOLE_BUFFER_LENGTH * self.columns * rescroll['data']['blocks'], 'output', rescroll['data']['mem_key'], True) - self.shm_output.create('read') - - if not CONQUE_FAST_MODE: - self.shm_attributes = ConqueSoleSharedMemory(CONQUE_SOLE_BUFFER_LENGTH * self.columns * rescroll['data']['blocks'], 'attributes', rescroll['data']['mem_key'], True, encoding='latin-1') - self.shm_attributes.create('read') - - stats_str = self.shm_stats.read() - if stats_str != '': - self.stats = stats_str - else: - return False - except: - - return False - - return self.stats - - - def is_alive(self): - """ Get process status. """ - - if not self.shm_stats: - return True - - stats_str = self.shm_stats.read() - if stats_str: - return (stats_str['is_alive']) - else: - return True - - - def write(self, text): - """ Write input to shared memory. """ - - self.bucket += text - - istr = self.shm_input.read() - - if istr == '': - - self.shm_input.write(self.bucket[:500]) - self.bucket = self.bucket[500:] - - - def write_vk(self, vk_code): - """ Write virtual key code to shared memory using proprietary escape sequences. """ - - seq = u("\x1b[") + u(str(vk_code)) + u("VK") - self.write(seq) - - - def idle(self): - """ Write idle command to shared memory block, so subprocess controller can hibernate. """ - - - self.shm_command.write({'cmd': 'idle', 'data': {}}) - - - def resume(self): - """ Write resume command to shared memory block, so subprocess controller can wake up. """ - - self.shm_command.write({'cmd': 'resume', 'data': {}}) - - - def close(self): - """ Shut it all down. """ - - self.shm_command.write({'cmd': 'close', 'data': {}}) - time.sleep(0.2) - - - def window_resize(self, lines, columns): - """ Resize console window. """ - - self.lines = lines - - # we don't shrink buffer width - if columns > self.columns: - self.columns = columns - - self.shm_resize.write({'cmd': 'resize', 'data': {'width': columns, 'height': lines}}) - - - def init_shared_memory(self, mem_key): - """ Create shared memory objects. """ - - self.shm_input = ConqueSoleSharedMemory(CONQUE_SOLE_INPUT_SIZE, 'input', mem_key) - self.shm_input.create('write') - self.shm_input.clear() - - self.shm_output = ConqueSoleSharedMemory(CONQUE_SOLE_BUFFER_LENGTH * self.columns, 'output', mem_key, True) - self.shm_output.create('write') - - if not CONQUE_FAST_MODE: - self.shm_attributes = ConqueSoleSharedMemory(CONQUE_SOLE_BUFFER_LENGTH * self.columns, 'attributes', mem_key, True, encoding='latin-1') - self.shm_attributes.create('write') - - self.shm_stats = ConqueSoleSharedMemory(CONQUE_SOLE_STATS_SIZE, 'stats', mem_key, serialize=True) - self.shm_stats.create('write') - self.shm_stats.clear() - - self.shm_command = ConqueSoleSharedMemory(CONQUE_SOLE_COMMANDS_SIZE, 'command', mem_key, serialize=True) - self.shm_command.create('write') - self.shm_command.clear() - - self.shm_resize = ConqueSoleSharedMemory(CONQUE_SOLE_RESIZE_SIZE, 'resize', mem_key, serialize=True) - self.shm_resize.create('write') - self.shm_resize.clear() - - self.shm_rescroll = ConqueSoleSharedMemory(CONQUE_SOLE_RESCROLL_SIZE, 'rescroll', mem_key, serialize=True) - self.shm_rescroll.create('write') - self.shm_rescroll.clear() - - return True - - -# vim:foldmethod=marker diff --git a/vim/autoload/conque_term/conque_subprocess.py b/vim/autoload/conque_term/conque_subprocess.py deleted file mode 100644 index b44c331..0000000 --- a/vim/autoload/conque_term/conque_subprocess.py +++ /dev/null @@ -1,198 +0,0 @@ -# FILE: autoload/conque_term/conque_subprocess.py -# AUTHOR: Nico Raffo -# WEBSITE: http://conque.googlecode.com -# MODIFIED: 2011-09-02 -# VERSION: 2.3, for Vim 7.0 -# LICENSE: -# Conque - Vim terminal/console emulator -# Copyright (C) 2009-2011 Nico Raffo -# -# MIT License -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -""" -ConqueSubprocess - -Create and interact with a subprocess through a pty. - -Usage: - - p = ConqueSubprocess() - p.open('bash', {'TERM':'vt100'}) - output = p.read() - p.write('cd ~/vim' + "\r") - p.write('ls -lha' + "\r") - output += p.read(timeout = 500) - p.close() -""" - -import os -import signal -import pty -import tty -import select -import fcntl -import termios -import struct -import shlex - - -class ConqueSubprocess: - - # process id - pid = 0 - - # stdout+stderr file descriptor - fd = None - - - def open(self, command, env={}): - """ Create subprocess using forkpty() """ - - # parse command - command_arr = shlex.split(command) - executable = command_arr[0] - args = command_arr - - # try to fork a new pty - try: - self.pid, self.fd = pty.fork() - - except: - - return False - - # child proc, replace with command after altering terminal attributes - if self.pid == 0: - - # set requested environment variables - for k in env.keys(): - os.environ[k] = env[k] - - # set tty attributes - try: - attrs = tty.tcgetattr(1) - attrs[0] = attrs[0] ^ tty.IGNBRK - attrs[0] = attrs[0] | tty.BRKINT | tty.IXANY | tty.IMAXBEL - attrs[2] = attrs[2] | tty.HUPCL - attrs[3] = attrs[3] | tty.ICANON | tty.ECHO | tty.ISIG | tty.ECHOKE - attrs[6][tty.VMIN] = 1 - attrs[6][tty.VTIME] = 0 - tty.tcsetattr(1, tty.TCSANOW, attrs) - except: - - pass - - # replace this process with the subprocess - os.execvp(executable, args) - - # else master, do nothing - else: - pass - - - def read(self, timeout=1): - """ Read from subprocess and return new output """ - - output = '' - read_timeout = float(timeout) / 1000 - read_ct = 0 - - try: - # read from fd until no more output - while 1: - s_read, s_write, s_error = select.select([self.fd], [], [], read_timeout) - - lines = '' - for s_fd in s_read: - try: - # increase read buffer so huge reads don't slow down - if read_ct < 10: - lines = os.read(self.fd, 32) - elif read_ct < 50: - lines = os.read(self.fd, 512) - else: - lines = os.read(self.fd, 2048) - read_ct += 1 - except: - pass - output = output + lines.decode('utf-8') - - if lines == '' or read_ct > 100: - break - except: - - pass - - return output - - - def write(self, input): - """ Write new input to subprocess """ - - try: - if CONQUE_PYTHON_VERSION == 2: - os.write(self.fd, input.encode('utf-8', 'ignore')) - else: - os.write(self.fd, bytes(input, 'utf-8')) - except: - - pass - - - def signal(self, signum): - """ signal process """ - - try: - os.kill(self.pid, signum) - except: - pass - - - def close(self): - """ close process with sigterm signal """ - - self.signal(15) - - - def is_alive(self): - """ get process status """ - - p_status = True - try: - if os.waitpid(self.pid, os.WNOHANG)[0]: - p_status = False - except: - p_status = False - - return p_status - - - def window_resize(self, lines, columns): - """ update window size in kernel, then send SIGWINCH to fg process """ - - try: - fcntl.ioctl(self.fd, termios.TIOCSWINSZ, struct.pack("HHHH", lines, columns, 0, 0)) - os.kill(self.pid, signal.SIGWINCH) - except: - pass - - -# vim:foldmethod=marker diff --git a/vim/autoload/conque_term/conque_win32_util.py b/vim/autoload/conque_term/conque_win32_util.py deleted file mode 100644 index aad0d12..0000000 --- a/vim/autoload/conque_term/conque_win32_util.py +++ /dev/null @@ -1,448 +0,0 @@ -# FILE: autoload/conque_term/conque_win32_util.py -# AUTHOR: Nico Raffo -# WEBSITE: http://conque.googlecode.com -# MODIFIED: 2011-09-02 -# VERSION: 2.3, for Vim 7.0 -# LICENSE: -# Conque - Vim terminal/console emulator -# Copyright (C) 2009-2011 Nico Raffo -# -# MIT License -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -""" Python constants and structures used for ctypes interaction. """ - -from ctypes import * - -# Constants - -# create process flag constants - -CREATE_BREAKAWAY_FROM_JOB = 0x01000000 -CREATE_DEFAULT_ERROR_MODE = 0x04000000 -CREATE_NEW_CONSOLE = 0x00000010 -CREATE_NEW_PROCESS_GROUP = 0x00000200 -CREATE_NO_WINDOW = 0x08000000 -CREATE_PROTECTED_PROCESS = 0x00040000 -CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000 -CREATE_SEPARATE_WOW_VDM = 0x00000800 -CREATE_SHARED_WOW_VDM = 0x00001000 -CREATE_SUSPENDED = 0x00000004 -CREATE_UNICODE_ENVIRONMENT = 0x00000400 - - -DETACHED_PROCESS = 0x00000008 -EXTENDED_STARTUPINFO_PRESENT = 0x00080000 -INHERIT_PARENT_AFFINITY = 0x00010000 - - -# process priority constants - -ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000 -BELOW_NORMAL_PRIORITY_CLASS = 0x00004000 -HIGH_PRIORITY_CLASS = 0x00000080 -IDLE_PRIORITY_CLASS = 0x00000040 -NORMAL_PRIORITY_CLASS = 0x00000020 -REALTIME_PRIORITY_CLASS = 0x00000100 - - -# startup info constants - -STARTF_FORCEONFEEDBACK = 0x00000040 -STARTF_FORCEOFFFEEDBACK = 0x00000080 -STARTF_PREVENTPINNING = 0x00002000 -STARTF_RUNFULLSCREEN = 0x00000020 -STARTF_TITLEISAPPID = 0x00001000 -STARTF_TITLEISLINKNAME = 0x00000800 -STARTF_USECOUNTCHARS = 0x00000008 -STARTF_USEFILLATTRIBUTE = 0x00000010 -STARTF_USEHOTKEY = 0x00000200 -STARTF_USEPOSITION = 0x00000004 -STARTF_USESHOWWINDOW = 0x00000001 -STARTF_USESIZE = 0x00000002 -STARTF_USESTDHANDLES = 0x00000100 - - -# show window constants - -SW_FORCEMINIMIZE = 11 -SW_HIDE = 0 -SW_MAXIMIZE = 3 -SW_MINIMIZE = 6 -SW_RESTORE = 9 -SW_SHOW = 5 -SW_SHOWDEFAULT = 10 -SW_SHOWMAXIMIZED = 3 -SW_SHOWMINIMIZED = 2 -SW_SHOWMINNOACTIVE = 7 -SW_SHOWNA = 8 -SW_SHOWNOACTIVATE = 4 -SW_SHOWNORMAL = 1 - - -# input event types - -FOCUS_EVENT = 0x0010 -KEY_EVENT = 0x0001 -MENU_EVENT = 0x0008 -MOUSE_EVENT = 0x0002 -WINDOW_BUFFER_SIZE_EVENT = 0x0004 - - -# key event modifiers - -CAPSLOCK_ON = 0x0080 -ENHANCED_KEY = 0x0100 -LEFT_ALT_PRESSED = 0x0002 -LEFT_CTRL_PRESSED = 0x0008 -NUMLOCK_ON = 0x0020 -RIGHT_ALT_PRESSED = 0x0001 -RIGHT_CTRL_PRESSED = 0x0004 -SCROLLLOCK_ON = 0x0040 -SHIFT_PRESSED = 0x0010 - - -# process access - -PROCESS_CREATE_PROCESS = 0x0080 -PROCESS_CREATE_THREAD = 0x0002 -PROCESS_DUP_HANDLE = 0x0040 -PROCESS_QUERY_INFORMATION = 0x0400 -PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 -PROCESS_SET_INFORMATION = 0x0200 -PROCESS_SET_QUOTA = 0x0100 -PROCESS_SUSPEND_RESUME = 0x0800 -PROCESS_TERMINATE = 0x0001 -PROCESS_VM_OPERATION = 0x0008 -PROCESS_VM_READ = 0x0010 -PROCESS_VM_WRITE = 0x0020 - - -# input / output handles - -STD_INPUT_HANDLE = c_ulong(-10) -STD_OUTPUT_HANDLE = c_ulong(-11) -STD_ERROR_HANDLE = c_ulong(-12) - - -CONQUE_WINDOWS_VK = { - 'VK_LBUTTON': 0x0001, - 'VK_RBUTTON': 0x0002, - 'VK_CANCEL': 0x0003, - 'VK_BACK': 0x0008, - 'VK_TAB': 0x0009, - 'VK_CLEAR': 0x000C, - 'VK_RETURN': 0x0D, - 'VK_SHIFT': 0x10, - 'VK_CONTROL': 0x11, - 'VK_MENU': 0x12, - 'VK_PAUSE': 0x0013, - 'VK_CAPITAL': 0x0014, - 'VK_ESCAPE': 0x001B, - 'VK_SPACE': 0x0020, - 'VK_PRIOR': 0x0021, - 'VK_NEXT': 0x0022, - 'VK_END': 0x0023, - 'VK_HOME': 0x0024, - 'VK_LEFT': 0x0025, - 'VK_UP': 0x0026, - 'VK_RIGHT': 0x0027, - 'VK_DOWN': 0x0028, - 'VK_SELECT': 0x0029, - 'VK_PRINT': 0x002A, - 'VK_EXECUTE': 0x002B, - 'VK_SNAPSHOT': 0x002C, - 'VK_INSERT': 0x002D, - 'VK_DELETE': 0x002E, - 'VK_HELP': 0x002F, - 'VK_0': 0x0030, - 'VK_1': 0x0031, - 'VK_2': 0x0032, - 'VK_3': 0x0033, - 'VK_4': 0x0034, - 'VK_5': 0x0035, - 'VK_6': 0x0036, - 'VK_7': 0x0037, - 'VK_8': 0x0038, - 'VK_9': 0x0039, - 'VK_A': 0x0041, - 'VK_B': 0x0042, - 'VK_C': 0x0043, - 'VK_D': 0x0044, - 'VK_E': 0x0045, - 'VK_F': 0x0046, - 'VK_G': 0x0047, - 'VK_H': 0x0048, - 'VK_I': 0x0049, - 'VK_J': 0x004A, - 'VK_K': 0x004B, - 'VK_L': 0x004C, - 'VK_M': 0x004D, - 'VK_N': 0x004E, - 'VK_O': 0x004F, - 'VK_P': 0x0050, - 'VK_Q': 0x0051, - 'VK_R': 0x0052, - 'VK_S': 0x0053, - 'VK_T': 0x0054, - 'VK_U': 0x0055, - 'VK_V': 0x0056, - 'VK_W': 0x0057, - 'VK_X': 0x0058, - 'VK_Y': 0x0059, - 'VK_Z': 0x005A, - 'VK_LWIN': 0x005B, - 'VK_RWIN': 0x005C, - 'VK_APPS': 0x005D, - 'VK_SLEEP': 0x005F, - 'VK_NUMPAD0': 0x0060, - 'VK_NUMPAD1': 0x0061, - 'VK_NUMPAD2': 0x0062, - 'VK_NUMPAD3': 0x0063, - 'VK_NUMPAD4': 0x0064, - 'VK_NUMPAD5': 0x0065, - 'VK_NUMPAD6': 0x0066, - 'VK_NUMPAD7': 0x0067, - 'VK_NUMPAD8': 0x0068, - 'VK_MULTIPLY': 0x006A, - 'VK_ADD': 0x006B, - 'VK_SEPARATOR': 0x006C, - 'VK_SUBTRACT': 0x006D, - 'VK_DECIMAL': 0x006E, - 'VK_DIVIDE': 0x006F, - 'VK_F1': 0x0070, - 'VK_F2': 0x0071, - 'VK_F3': 0x0072, - 'VK_F4': 0x0073, - 'VK_F5': 0x0074, - 'VK_F6': 0x0075, - 'VK_F7': 0x0076, - 'VK_F8': 0x0077, - 'VK_F9': 0x0078, - 'VK_F10': 0x0079, - 'VK_F11': 0x007A, - 'VK_F12': 0x007B, - 'VK_F13': 0x007C, - 'VK_F14': 0x007D, - 'VK_F15': 0x007E, - 'VK_F16': 0x007F, - 'VK_F17': 0x0080, - 'VK_F18': 0x0081, - 'VK_F19': 0x0082, - 'VK_F20': 0x0083, - 'VK_F21': 0x0084, - 'VK_F22': 0x0085, - 'VK_F23': 0x0086, - 'VK_F24': 0x0087, - 'VK_NUMLOCK': 0x0090, - 'VK_SCROLL': 0x0091, - 'VK_LSHIFT': 0x00A0, - 'VK_RSHIFT': 0x00A1, - 'VK_LCONTROL': 0x00A2, - 'VK_RCONTROL': 0x00A3, - 'VK_LMENU': 0x00A4, - 'VK_RMENU': 0x00A5 -} - -CONQUE_WINDOWS_VK_INV = dict([v, k] for k, v in CONQUE_WINDOWS_VK.items()) - -CONQUE_WINDOWS_VK_ENHANCED = { - str(int(CONQUE_WINDOWS_VK['VK_UP'])): 1, - str(int(CONQUE_WINDOWS_VK['VK_DOWN'])): 1, - str(int(CONQUE_WINDOWS_VK['VK_LEFT'])): 1, - str(int(CONQUE_WINDOWS_VK['VK_RIGHT'])): 1, - str(int(CONQUE_WINDOWS_VK['VK_HOME'])): 1, - str(int(CONQUE_WINDOWS_VK['VK_END'])): 1 -} - - -# structures used for CreateProcess - -# Odd types - -LPBYTE = POINTER(c_ubyte) -LPTSTR = POINTER(c_char) - - -class STARTUPINFO(Structure): - _fields_ = [("cb", c_ulong), - ("lpReserved", LPTSTR), - ("lpDesktop", LPTSTR), - ("lpTitle", LPTSTR), - ("dwX", c_ulong), - ("dwY", c_ulong), - ("dwXSize", c_ulong), - ("dwYSize", c_ulong), - ("dwXCountChars", c_ulong), - ("dwYCountChars", c_ulong), - ("dwFillAttribute", c_ulong), - ("dwFlags", c_ulong), - ("wShowWindow", c_short), - ("cbReserved2", c_short), - ("lpReserved2", LPBYTE), - ("hStdInput", c_void_p), - ("hStdOutput", c_void_p), - ("hStdError", c_void_p),] - - def to_str(self): - return '' - - -class PROCESS_INFORMATION(Structure): - _fields_ = [("hProcess", c_void_p), - ("hThread", c_void_p), - ("dwProcessId", c_ulong), - ("dwThreadId", c_ulong),] - - def to_str(self): - return '' - - -class MEMORY_BASIC_INFORMATION(Structure): - _fields_ = [("BaseAddress", c_void_p), - ("AllocationBase", c_void_p), - ("AllocationProtect", c_ulong), - ("RegionSize", c_ulong), - ("State", c_ulong), - ("Protect", c_ulong), - ("Type", c_ulong),] - - def to_str(self): - return '' - - -class SECURITY_ATTRIBUTES(Structure): - _fields_ = [("Length", c_ulong), - ("SecDescriptor", c_void_p), - ("InheritHandle", c_bool)] - - def to_str(self): - return '' - - -class COORD(Structure): - _fields_ = [("X", c_short), - ("Y", c_short)] - - def to_str(self): - return '' - - -class SMALL_RECT(Structure): - _fields_ = [("Left", c_short), - ("Top", c_short), - ("Right", c_short), - ("Bottom", c_short)] - - def to_str(self): - return '' - - -class CONSOLE_SCREEN_BUFFER_INFO(Structure): - _fields_ = [("dwSize", COORD), - ("dwCursorPosition", COORD), - ("wAttributes", c_short), - ("srWindow", SMALL_RECT), - ("dwMaximumWindowSize", COORD)] - - def to_str(self): - return '' - - -class CHAR_UNION(Union): - _fields_ = [("UnicodeChar", c_wchar), - ("AsciiChar", c_char)] - - def to_str(self): - return '' - - -class CHAR_INFO(Structure): - _fields_ = [("Char", CHAR_UNION), - ("Attributes", c_short)] - - def to_str(self): - return '' - - -class KEY_EVENT_RECORD(Structure): - _fields_ = [("bKeyDown", c_byte), - ("pad2", c_byte), - ('pad1', c_short), - ("wRepeatCount", c_short), - ("wVirtualKeyCode", c_short), - ("wVirtualScanCode", c_short), - ("uChar", CHAR_UNION), - ("dwControlKeyState", c_int)] - - def to_str(self): - return '' - - -class MOUSE_EVENT_RECORD(Structure): - _fields_ = [("dwMousePosition", COORD), - ("dwButtonState", c_int), - ("dwControlKeyState", c_int), - ("dwEventFlags", c_int)] - - def to_str(self): - return '' - - -class WINDOW_BUFFER_SIZE_RECORD(Structure): - _fields_ = [("dwSize", COORD)] - - def to_str(self): - return '' - - -class MENU_EVENT_RECORD(Structure): - _fields_ = [("dwCommandId", c_uint)] - - def to_str(self): - return '' - - -class FOCUS_EVENT_RECORD(Structure): - _fields_ = [("bSetFocus", c_byte)] - - def to_str(self): - return '' - - -class INPUT_UNION(Union): - _fields_ = [("KeyEvent", KEY_EVENT_RECORD), - ("MouseEvent", MOUSE_EVENT_RECORD), - ("WindowBufferSizeEvent", WINDOW_BUFFER_SIZE_RECORD), - ("MenuEvent", MENU_EVENT_RECORD), - ("FocusEvent", FOCUS_EVENT_RECORD)] - - def to_str(self): - return '' - - -class INPUT_RECORD(Structure): - _fields_ = [("EventType", c_short), - ("Event", INPUT_UNION)] - - def to_str(self): - return '' - - diff --git a/vim/bundle/rson-vim-conque b/vim/bundle/rson-vim-conque new file mode 160000 index 0000000..da35739 --- /dev/null +++ b/vim/bundle/rson-vim-conque @@ -0,0 +1 @@ +Subproject commit da35739921a258ecce991040f9b1537897a8ff57 diff --git a/vim/plugin/NERD_commenter.vim b/vim/plugin/NERD_commenter.vim deleted file mode 100644 index 18a348f..0000000 --- a/vim/plugin/NERD_commenter.vim +++ /dev/null @@ -1,3132 +0,0 @@ -" ============================================================================ -" File: NERD_commenter.vim -" Description: vim global plugin that provides easy code commenting -" Maintainer: Martin Grenfell -" Version: 2.2.2 -" Last Change: 30th March, 2008 -" License: This program is free software. It comes without any warranty, -" to the extent permitted by applicable law. You can redistribute -" it and/or modify it under the terms of the Do What The Fuck You -" Want To Public License, Version 2, as published by Sam Hocevar. -" See http://sam.zoy.org/wtfpl/COPYING for more details. -" -" ============================================================================ - -" Section: script init stuff {{{1 -if exists("loaded_nerd_comments") - finish -endif -if v:version < 700 - echoerr "NERDCommenter: this plugin requires vim >= 7. DOWNLOAD IT! You'll thank me later!" - finish -endif -let loaded_nerd_comments = 1 - -" Function: s:InitVariable() function {{{2 -" This function is used to initialise a given variable to a given value. The -" variable is only initialised if it does not exist prior -" -" Args: -" -var: the name of the var to be initialised -" -value: the value to initialise var to -" -" Returns: -" 1 if the var is set, 0 otherwise -function s:InitVariable(var, value) - if !exists(a:var) - exec 'let ' . a:var . ' = ' . "'" . a:value . "'" - return 1 - endif - return 0 -endfunction - -" Section: space string init{{{2 -" When putting spaces after the left delim and before the right we use -" s:spaceStr for the space char. This way we can make it add anything after -" the left and before the right by modifying this variable -let s:spaceStr = ' ' -let s:lenSpaceStr = strlen(s:spaceStr) - -" Section: variable init calls {{{2 -call s:InitVariable("g:NERDAllowAnyVisualDelims", 1) -call s:InitVariable("g:NERDBlockComIgnoreEmpty", 0) -call s:InitVariable("g:NERDCommentWholeLinesInVMode", 0) -call s:InitVariable("g:NERDCompactSexyComs", 0) -call s:InitVariable("g:NERDCreateDefaultMappings", 1) -call s:InitVariable("g:NERDDefaultNesting", 1) -call s:InitVariable("g:NERDMenuMode", 3) -call s:InitVariable("g:NERDLPlace", "[>") -call s:InitVariable("g:NERDUsePlaceHolders", 1) -call s:InitVariable("g:NERDRemoveAltComs", 1) -call s:InitVariable("g:NERDRemoveExtraSpaces", 1) -call s:InitVariable("g:NERDRPlace", "<]") -call s:InitVariable("g:NERDSpaceDelims", 0) -call s:InitVariable("g:NERDDelimiterRequests", 1) - - - -let s:NERDFileNameEscape="[]#*$%'\" ?`!&();<>\\" - -" Section: Comment mapping functions, autocommands and commands {{{1 -" ============================================================================ -" Section: Comment enabler autocommands {{{2 -" ============================================================================ - -augroup commentEnablers - - "if the user enters a buffer or reads a buffer then we gotta set up - "the comment delimiters for that new filetype - autocmd BufEnter,BufRead * :call s:SetUpForNewFiletype(&filetype, 0) - - "if the filetype of a buffer changes, force the script to reset the - "delims for the buffer - autocmd Filetype * :call s:SetUpForNewFiletype(&filetype, 1) -augroup END - - -" Function: s:SetUpForNewFiletype(filetype) function {{{2 -" This function is responsible for setting up buffer scoped variables for the -" given filetype. -" -" These variables include the comment delimiters for the given filetype and calls -" MapDelimiters or MapDelimitersWithAlternative passing in these delimiters. -" -" Args: -" -filetype: the filetype to set delimiters for -" -forceReset: 1 if the delimiters should be reset if they have already be -" set for this buffer. -" -function s:SetUpForNewFiletype(filetype, forceReset) - "if we have already set the delimiters for this buffer then dont go thru - "it again - if !a:forceReset && exists("b:NERDLeft") && b:NERDLeft != '' - return - endif - - let b:NERDSexyComMarker = '' - - "check the filetype against all known filetypes to see if we have - "hardcoded the comment delimiters to use - if a:filetype ==? "" - call s:MapDelimiters('', '') - elseif a:filetype ==? "aap" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "abc" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "acedb" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "actionscript" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "ada" - call s:MapDelimitersWithAlternative('--','', '-- ', '') - elseif a:filetype ==? "ahdl" - call s:MapDelimiters('--', '') - elseif a:filetype ==? "ahk" - call s:MapDelimitersWithAlternative(';', '', '/*', '*/') - elseif a:filetype ==? "amiga" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "aml" - call s:MapDelimiters('/*', '') - elseif a:filetype ==? "ampl" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "apache" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "apachestyle" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "asciidoc" - call s:MapDelimiters('//', '') - elseif a:filetype ==? "applescript" - call s:MapDelimitersWithAlternative('--', '', '(*', '*)') - elseif a:filetype ==? "asm68k" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "asm" - call s:MapDelimitersWithAlternative(';', '', '#', '') - elseif a:filetype ==? "asn" - call s:MapDelimiters('--', '') - elseif a:filetype ==? "aspvbs" - call s:MapDelimiters('''', '') - elseif a:filetype ==? "asterisk" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "asy" - call s:MapDelimiters('//', '') - elseif a:filetype ==? "atlas" - call s:MapDelimiters('C','$') - elseif a:filetype ==? "autohotkey" - call s:MapDelimiters(';','') - elseif a:filetype ==? "autoit" - call s:MapDelimiters(';','') - elseif a:filetype ==? "ave" - call s:MapDelimiters("'",'') - elseif a:filetype ==? "awk" - call s:MapDelimiters('#','') - elseif a:filetype ==? "basic" - call s:MapDelimitersWithAlternative("'",'', 'REM ', '') - elseif a:filetype ==? "bbx" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "bc" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "bib" - call s:MapDelimiters('%','') - elseif a:filetype ==? "bindzone" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "bst" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "btm" - call s:MapDelimiters('::', '') - elseif a:filetype ==? "caos" - call s:MapDelimiters('*', '') - elseif a:filetype ==? "calibre" - call s:MapDelimiters('//','') - elseif a:filetype ==? "catalog" - call s:MapDelimiters('--','--') - elseif a:filetype ==? "c" - call s:MapDelimitersWithAlternative('/*','*/', '//', '') - elseif a:filetype ==? "cfg" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "cg" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "ch" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "cl" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "clean" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "clipper" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "clojure" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "cmake" - call s:MapDelimiters('#','') - elseif a:filetype ==? "conkyrc" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "cpp" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "crontab" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "cs" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "csp" - call s:MapDelimiters('--', '') - elseif a:filetype ==? "cterm" - call s:MapDelimiters('*', '') - elseif a:filetype ==? "cucumber" - call s:MapDelimiters('#','') - elseif a:filetype ==? "cvs" - call s:MapDelimiters('CVS:','') - elseif a:filetype ==? "d" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "dcl" - call s:MapDelimiters('$!', '') - elseif a:filetype ==? "dakota" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "debcontrol" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "debsources" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "def" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "desktop" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "dhcpd" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "diff" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "django" - call s:MapDelimitersWithAlternative('', '{#', '#}') - elseif a:filetype ==? "docbk" - call s:MapDelimiters('') - elseif a:filetype ==? "dns" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "dosbatch" - call s:MapDelimitersWithAlternative('REM ','', '::', '') - elseif a:filetype ==? "dosini" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "dot" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "dracula" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "dsl" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "dtml" - call s:MapDelimiters('','') - elseif a:filetype ==? "dylan" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? 'ebuild' - call s:MapDelimiters('#', '') - elseif a:filetype ==? "ecd" - call s:MapDelimiters('#', '') - elseif a:filetype ==? 'eclass' - call s:MapDelimiters('#', '') - elseif a:filetype ==? "eiffel" - call s:MapDelimiters('--', '') - elseif a:filetype ==? "elf" - call s:MapDelimiters("'", '') - elseif a:filetype ==? "elmfilt" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "erlang" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "eruby" - call s:MapDelimitersWithAlternative('<%#', '%>', '') - elseif a:filetype ==? "expect" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "exports" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "factor" - call s:MapDelimitersWithAlternative('! ', '', '!# ', '') - elseif a:filetype ==? "fgl" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "focexec" - call s:MapDelimiters('-*', '') - elseif a:filetype ==? "form" - call s:MapDelimiters('*', '') - elseif a:filetype ==? "foxpro" - call s:MapDelimiters('*', '') - elseif a:filetype ==? "fstab" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "fvwm" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "fx" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "gams" - call s:MapDelimiters('*', '') - elseif a:filetype ==? "gdb" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "gdmo" - call s:MapDelimiters('--', '') - elseif a:filetype ==? "geek" - call s:MapDelimiters('GEEK_COMMENT:', '') - elseif a:filetype ==? "genshi" - call s:MapDelimitersWithAlternative('', '{#', '#}') - elseif a:filetype ==? "gentoo-conf-d" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "gentoo-env-d" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "gentoo-init-d" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "gentoo-make-conf" - call s:MapDelimiters('#', '') - elseif a:filetype ==? 'gentoo-package-keywords' - call s:MapDelimiters('#', '') - elseif a:filetype ==? 'gentoo-package-mask' - call s:MapDelimiters('#', '') - elseif a:filetype ==? 'gentoo-package-use' - call s:MapDelimiters('#', '') - elseif a:filetype ==? 'gitcommit' - call s:MapDelimiters('#', '') - elseif a:filetype ==? 'gitconfig' - call s:MapDelimiters(';', '') - elseif a:filetype ==? 'gitrebase' - call s:MapDelimiters('#', '') - elseif a:filetype ==? "gnuplot" - call s:MapDelimiters('#','') - elseif a:filetype ==? "groovy" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "gtkrc" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "haskell" - call s:MapDelimitersWithAlternative('{-','-}', '--', '') - elseif a:filetype ==? "hb" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "h" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "haml" - call s:MapDelimitersWithAlternative('-#', '', '/', '') - elseif a:filetype ==? "hercules" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "hog" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "hostsaccess" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "htmlcheetah" - call s:MapDelimiters('##','') - elseif a:filetype ==? "htmldjango" - call s:MapDelimitersWithAlternative('', '{#', '#}') - elseif a:filetype ==? "htmlos" - call s:MapDelimiters('#','/#') - elseif a:filetype ==? "ia64" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "icon" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "idlang" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "idl" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "inform" - call s:MapDelimiters('!', '') - elseif a:filetype ==? "inittab" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "ishd" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "iss" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "ist" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "java" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "javacc" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "javascript" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype == "javascript.jquery" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "jess" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "jgraph" - call s:MapDelimiters('(*','*)') - elseif a:filetype ==? "jproperties" - call s:MapDelimiters('#','') - elseif a:filetype ==? "jsp" - call s:MapDelimiters('<%--', '--%>') - elseif a:filetype ==? "kix" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "kscript" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "lace" - call s:MapDelimiters('--', '') - elseif a:filetype ==? "ldif" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "lilo" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "lilypond" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "liquid" - call s:MapDelimiters('{%', '%}') - elseif a:filetype ==? "lisp" - call s:MapDelimitersWithAlternative(';','', '#|', '|#') - elseif a:filetype ==? "llvm" - call s:MapDelimiters(';','') - elseif a:filetype ==? "lotos" - call s:MapDelimiters('(*','*)') - elseif a:filetype ==? "lout" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "lprolog" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "lscript" - call s:MapDelimiters("'", '') - elseif a:filetype ==? "lss" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "lua" - call s:MapDelimitersWithAlternative('--','', '--[[', ']]') - elseif a:filetype ==? "lynx" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "lytex" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "mail" - call s:MapDelimiters('> ','') - elseif a:filetype ==? "mako" - call s:MapDelimiters('##', '') - elseif a:filetype ==? "man" - call s:MapDelimiters('."', '') - elseif a:filetype ==? "map" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "maple" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "markdown" - call s:MapDelimiters('') - elseif a:filetype ==? "masm" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "mason" - call s:MapDelimiters('<% #', '%>') - elseif a:filetype ==? "master" - call s:MapDelimiters('$', '') - elseif a:filetype ==? "matlab" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "mel" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "mib" - call s:MapDelimiters('--', '') - elseif a:filetype ==? "mkd" - call s:MapDelimiters('>', '') - elseif a:filetype ==? "mma" - call s:MapDelimiters('(*','*)') - elseif a:filetype ==? "model" - call s:MapDelimiters('$','$') - elseif a:filetype =~ "moduala." - call s:MapDelimiters('(*','*)') - elseif a:filetype ==? "modula2" - call s:MapDelimiters('(*','*)') - elseif a:filetype ==? "modula3" - call s:MapDelimiters('(*','*)') - elseif a:filetype ==? "monk" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "mush" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "named" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "nasm" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "nastran" - call s:MapDelimiters('$', '') - elseif a:filetype ==? "natural" - call s:MapDelimiters('/*', '') - elseif a:filetype ==? "ncf" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "newlisp" - call s:MapDelimiters(';','') - elseif a:filetype ==? "nroff" - call s:MapDelimiters('\"', '') - elseif a:filetype ==? "nsis" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "ntp" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "objc" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "objcpp" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "objj" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "ocaml" - call s:MapDelimiters('(*','*)') - elseif a:filetype ==? "occam" - call s:MapDelimiters('--','') - elseif a:filetype ==? "omlet" - call s:MapDelimiters('(*','*)') - elseif a:filetype ==? "omnimark" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "openroad" - call s:MapDelimiters('//', '') - elseif a:filetype ==? "opl" - call s:MapDelimiters("REM", "") - elseif a:filetype ==? "ora" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "ox" - call s:MapDelimiters('//', '') - elseif a:filetype ==? "pascal" - call s:MapDelimitersWithAlternative('{','}', '(*', '*)') - elseif a:filetype ==? "patran" - call s:MapDelimitersWithAlternative('$','','/*', '*/') - elseif a:filetype ==? "pcap" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "pccts" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "pdf" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "pfmain" - call s:MapDelimiters('//', '') - elseif a:filetype ==? "php" - call s:MapDelimitersWithAlternative('//','','/*', '*/') - elseif a:filetype ==? "pic" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "pike" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "pilrc" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "pine" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "plm" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "plsql" - call s:MapDelimitersWithAlternative('--', '', '/*', '*/') - elseif a:filetype ==? "po" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "postscr" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "pov" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "povini" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "ppd" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "ppwiz" - call s:MapDelimiters(';;', '') - elseif a:filetype ==? "processing" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "prolog" - call s:MapDelimitersWithAlternative('%','','/*','*/') - elseif a:filetype ==? "ps1" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "psf" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "ptcap" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "radiance" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "ratpoison" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "r" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "rc" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "rebol" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "registry" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "remind" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "resolv" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "rgb" - call s:MapDelimiters('!', '') - elseif a:filetype ==? "rib" - call s:MapDelimiters('#','') - elseif a:filetype ==? "robots" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "sa" - call s:MapDelimiters('--','') - elseif a:filetype ==? "samba" - call s:MapDelimitersWithAlternative(';','', '#', '') - elseif a:filetype ==? "sass" - call s:MapDelimitersWithAlternative('//','', '/*', '') - elseif a:filetype ==? "sather" - call s:MapDelimiters('--', '') - elseif a:filetype ==? "scala" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "scilab" - call s:MapDelimiters('//', '') - elseif a:filetype ==? "scsh" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "sed" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "sgmldecl" - call s:MapDelimiters('--','--') - elseif a:filetype ==? "sgmllnx" - call s:MapDelimiters('') - elseif a:filetype ==? "sicad" - call s:MapDelimiters('*', '') - elseif a:filetype ==? "simula" - call s:MapDelimitersWithAlternative('%', '', '--', '') - elseif a:filetype ==? "sinda" - call s:MapDelimiters('$', '') - elseif a:filetype ==? "skill" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "slang" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "slice" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "slrnrc" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "sm" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "smarty" - call s:MapDelimiters('{*', '*}') - elseif a:filetype ==? "smil" - call s:MapDelimiters('') - elseif a:filetype ==? "smith" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "sml" - call s:MapDelimiters('(*','*)') - elseif a:filetype ==? "snnsnet" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "snnspat" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "snnsres" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "snobol4" - call s:MapDelimiters('*', '') - elseif a:filetype ==? "spec" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "specman" - call s:MapDelimiters('//', '') - elseif a:filetype ==? "spectre" - call s:MapDelimitersWithAlternative('//', '', '*', '') - elseif a:filetype ==? "spice" - call s:MapDelimiters('$', '') - elseif a:filetype ==? "sql" - call s:MapDelimiters('--', '') - elseif a:filetype ==? "sqlforms" - call s:MapDelimiters('--', '') - elseif a:filetype ==? "sqlj" - call s:MapDelimiters('--', '') - elseif a:filetype ==? "sqr" - call s:MapDelimiters('!', '') - elseif a:filetype ==? "squid" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "st" - call s:MapDelimiters('"','') - elseif a:filetype ==? "stp" - call s:MapDelimiters('--', '') - elseif a:filetype ==? "systemverilog" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "tads" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "tags" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "tak" - call s:MapDelimiters('$', '') - elseif a:filetype ==? "tasm" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "tcl" - call s:MapDelimiters('#','') - elseif a:filetype ==? "texinfo" - call s:MapDelimiters("@c ", "") - elseif a:filetype ==? "texmf" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "tf" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "tidy" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "tli" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "trasys" - call s:MapDelimiters("$", "") - elseif a:filetype ==? "tsalt" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "tsscl" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "tssgm" - call s:MapDelimiters("comment = '","'") - elseif a:filetype ==? "txt2tags" - call s:MapDelimiters('%','') - elseif a:filetype ==? "uc" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "uil" - call s:MapDelimiters('!', '') - elseif a:filetype ==? "vb" - call s:MapDelimiters("'","") - elseif a:filetype ==? "velocity" - call s:MapDelimitersWithAlternative("##","", '#*', '*#') - elseif a:filetype ==? "vera" - call s:MapDelimitersWithAlternative('/*','*/','//','') - elseif a:filetype ==? "verilog" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "verilog_systemverilog" - call s:MapDelimitersWithAlternative('//','', '/*','*/') - elseif a:filetype ==? "vgrindefs" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "vhdl" - call s:MapDelimiters('--', '') - elseif a:filetype ==? "vimperator" - call s:MapDelimiters('"','') - elseif a:filetype ==? "virata" - call s:MapDelimiters('%', '') - elseif a:filetype ==? "vrml" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "vsejcl" - call s:MapDelimiters('/*', '') - elseif a:filetype ==? "webmacro" - call s:MapDelimiters('##', '') - elseif a:filetype ==? "wget" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "Wikipedia" - call s:MapDelimiters('') - elseif a:filetype ==? "winbatch" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "wml" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "wvdial" - call s:MapDelimiters(';', '') - elseif a:filetype ==? "xdefaults" - call s:MapDelimiters('!', '') - elseif a:filetype ==? "xkb" - call s:MapDelimiters('//', '') - elseif a:filetype ==? "xmath" - call s:MapDelimiters('#', '') - elseif a:filetype ==? "xpm2" - call s:MapDelimiters('!', '') - elseif a:filetype ==? "xquery" - call s:MapDelimiters('(:',':)') - elseif a:filetype ==? "z8a" - call s:MapDelimiters(';', '') - - else - - "extract the delims from &commentstring - let left= substitute(&commentstring, '\([^ \t]*\)\s*%s.*', '\1', '') - let right= substitute(&commentstring, '.*%s\s*\(.*\)', '\1', 'g') - call s:MapDelimiters(left,right) - - endif -endfunction - -" Function: s:MapDelimiters(left, right) function {{{2 -" This function is a wrapper for s:MapDelimiters(left, right, leftAlt, rightAlt, useAlt) and is called when there -" is no alternative comment delimiters for the current filetype -" -" Args: -" -left: the left comment delimiter -" -right: the right comment delimiter -function s:MapDelimiters(left, right) - call s:MapDelimitersWithAlternative(a:left, a:right, "", "") -endfunction - -" Function: s:MapDelimitersWithAlternative(left, right, leftAlt, rightAlt) function {{{2 -" this function sets up the comment delimiter buffer variables -" -" Args: -" -left: the string defining the comment start delimiter -" -right: the string defining the comment end delimiter -" -leftAlt: the string for the alternative comment style defining the comment start delimiter -" -rightAlt: the string for the alternative comment style defining the comment end delimiter -function s:MapDelimitersWithAlternative(left, right, leftAlt, rightAlt) - if !exists('g:NERD_' . &filetype . '_alt_style') - let b:NERDLeft = a:left - let b:NERDRight = a:right - let b:NERDLeftAlt = a:leftAlt - let b:NERDRightAlt = a:rightAlt - else - let b:NERDLeft = a:leftAlt - let b:NERDRight = a:rightAlt - let b:NERDLeftAlt = a:left - let b:NERDRightAlt = a:right - endif -endfunction - -" Function: s:SwitchToAlternativeDelimiters(printMsgs) function {{{2 -" This function is used to swap the delimiters that are being used to the -" alternative delimiters for that filetype. For example, if a c++ file is -" being edited and // comments are being used, after this function is called -" /**/ comments will be used. -" -" Args: -" -printMsgs: if this is 1 then a message is echoed to the user telling them -" if this function changed the delimiters or not -function s:SwitchToAlternativeDelimiters(printMsgs) - "if both of the alternative delimiters are empty then there is no - "alternative comment style so bail out - if b:NERDLeftAlt == "" && b:NERDRightAlt == "" - if a:printMsgs - call s:NerdEcho("Cannot use alternative delimiters, none are specified", 0) - endif - return 0 - endif - - "save the current delimiters - let tempLeft = b:NERDLeft - let tempRight = b:NERDRight - - "swap current delimiters for alternative - let b:NERDLeft = b:NERDLeftAlt - let b:NERDRight = b:NERDRightAlt - - "set the previously current delimiters to be the new alternative ones - let b:NERDLeftAlt = tempLeft - let b:NERDRightAlt = tempRight - - "tell the user what comment delimiters they are now using - if a:printMsgs - let leftNoEsc = b:NERDLeft - let rightNoEsc = b:NERDRight - call s:NerdEcho("Now using " . leftNoEsc . " " . rightNoEsc . " to delimit comments", 1) - endif - - return 1 -endfunction - -" Section: Comment delimiter add/removal functions {{{1 -" ============================================================================ -" Function: s:AppendCommentToLine(){{{2 -" This function appends comment delimiters at the EOL and places the cursor in -" position to start typing the comment -function s:AppendCommentToLine() - let left = s:GetLeft(0,1,0) - let right = s:GetRight(0,1,0) - - " get the len of the right delim - let lenRight = strlen(right) - - let isLineEmpty = strlen(getline(".")) == 0 - let insOrApp = (isLineEmpty==1 ? 'i' : 'A') - - "stick the delimiters down at the end of the line. We have to format the - "comment with spaces as appropriate - execute ":normal! " . insOrApp . (isLineEmpty ? '' : ' ') . left . right . " " - - " if there is a right delimiter then we gotta move the cursor left - " by the len of the right delimiter so we insert between the delimiters - if lenRight > 0 - let leftMoveAmount = lenRight - execute ":normal! " . leftMoveAmount . "h" - endif - startinsert -endfunction - -" Function: s:CommentBlock(top, bottom, lSide, rSide, forceNested ) {{{2 -" This function is used to comment out a region of code. This region is -" specified as a bounding box by arguments to the function. -" -" Args: -" -top: the line number for the top line of code in the region -" -bottom: the line number for the bottom line of code in the region -" -lSide: the column number for the left most column in the region -" -rSide: the column number for the right most column in the region -" -forceNested: a flag indicating whether comments should be nested -function s:CommentBlock(top, bottom, lSide, rSide, forceNested ) - " we need to create local copies of these arguments so we can modify them - let top = a:top - let bottom = a:bottom - let lSide = a:lSide - let rSide = a:rSide - - "if the top or bottom line starts with tabs we have to adjust the left and - "right boundaries so that they are set as though the tabs were spaces - let topline = getline(top) - let bottomline = getline(bottom) - if s:HasLeadingTabs(topline, bottomline) - - "find out how many tabs are in the top line and adjust the left - "boundary accordingly - let numTabs = s:NumberOfLeadingTabs(topline) - if lSide < numTabs - let lSide = &ts * lSide - else - let lSide = (lSide - numTabs) + (&ts * numTabs) - endif - - "find out how many tabs are in the bottom line and adjust the right - "boundary accordingly - let numTabs = s:NumberOfLeadingTabs(bottomline) - let rSide = (rSide - numTabs) + (&ts * numTabs) - endif - - "we must check that bottom IS actually below top, if it is not then we - "swap top and bottom. Similarly for left and right. - if bottom < top - let temp = top - let top = bottom - let bottom = top - endif - if rSide < lSide - let temp = lSide - let lSide = rSide - let rSide = temp - endif - - "if the current delimiters arent multipart then we will switch to the - "alternative delims (if THEY are) as the comment will be better and more - "accurate with multipart delims - let switchedDelims = 0 - if !s:Multipart() && g:NERDAllowAnyVisualDelims && s:AltMultipart() - let switchedDelims = 1 - call s:SwitchToAlternativeDelimiters(0) - endif - - "start the commenting from the top and keep commenting till we reach the - "bottom - let currentLine=top - while currentLine <= bottom - - "check if we are allowed to comment this line - if s:CanCommentLine(a:forceNested, currentLine) - - "convert the leading tabs into spaces - let theLine = getline(currentLine) - let lineHasLeadTabs = s:HasLeadingTabs(theLine) - if lineHasLeadTabs - let theLine = s:ConvertLeadingTabsToSpaces(theLine) - endif - - "dont comment lines that begin after the right boundary of the - "block unless the user has specified to do so - if theLine !~ '^ \{' . rSide . '\}' || !g:NERDBlockComIgnoreEmpty - - "attempt to place the cursor in on the left of the boundary box, - "then check if we were successful, if not then we cant comment this - "line - call setline(currentLine, theLine) - if s:CanPlaceCursor(currentLine, lSide) - - let leftSpaced = s:GetLeft(0,1,0) - let rightSpaced = s:GetRight(0,1,0) - - "stick the left delimiter down - let theLine = strpart(theLine, 0, lSide-1) . leftSpaced . strpart(theLine, lSide-1) - - if s:Multipart() - "stick the right delimiter down - let theLine = strpart(theLine, 0, rSide+strlen(leftSpaced)) . rightSpaced . strpart(theLine, rSide+strlen(leftSpaced)) - - let firstLeftDelim = s:FindDelimiterIndex(b:NERDLeft, theLine) - let lastRightDelim = s:LastIndexOfDelim(b:NERDRight, theLine) - - if firstLeftDelim != -1 && lastRightDelim != -1 - let searchStr = strpart(theLine, 0, lastRightDelim) - let searchStr = strpart(searchStr, firstLeftDelim+strlen(b:NERDLeft)) - - "replace the outter most delims in searchStr with - "place-holders - let theLineWithPlaceHolders = s:ReplaceDelims(b:NERDLeft, b:NERDRight, g:NERDLPlace, g:NERDRPlace, searchStr) - - "add the right delimiter onto the line - let theLine = strpart(theLine, 0, firstLeftDelim+strlen(b:NERDLeft)) . theLineWithPlaceHolders . strpart(theLine, lastRightDelim) - endif - endif - endif - endif - - "restore tabs if needed - if lineHasLeadTabs - let theLine = s:ConvertLeadingSpacesToTabs(theLine) - endif - - call setline(currentLine, theLine) - endif - - let currentLine = currentLine + 1 - endwhile - - "if we switched delims then we gotta go back to what they were before - if switchedDelims == 1 - call s:SwitchToAlternativeDelimiters(0) - endif -endfunction - -" Function: s:CommentLines(forceNested, alignLeft, alignRight, firstLine, lastLine) {{{2 -" This function comments a range of lines. -" -" Args: -" -forceNested: a flag indicating whether the called is requesting the comment -" to be nested if need be -" -align: should be "left" or "both" or "none" -" -firstLine/lastLine: the top and bottom lines to comment -function s:CommentLines(forceNested, align, firstLine, lastLine) - " we need to get the left and right indexes of the leftmost char in the - " block of of lines and the right most char so that we can do alignment of - " the delimiters if the user has specified - let leftAlignIndx = s:LeftMostIndx(a:forceNested, 0, a:firstLine, a:lastLine) - let rightAlignIndx = s:RightMostIndx(a:forceNested, 0, a:firstLine, a:lastLine) - - " gotta add the length of the left delimiter onto the rightAlignIndx cos - " we'll be adding a left delim to the line - let rightAlignIndx = rightAlignIndx + strlen(s:GetLeft(0,1,0)) - - " now we actually comment the lines. Do it line by line - let currentLine = a:firstLine - while currentLine <= a:lastLine - - " get the next line, check commentability and convert spaces to tabs - let theLine = getline(currentLine) - let lineHasLeadingTabs = s:HasLeadingTabs(theLine) - let theLine = s:ConvertLeadingTabsToSpaces(theLine) - if s:CanCommentLine(a:forceNested, currentLine) - "if the user has specified forceNesting then we check to see if we - "need to switch delimiters for place-holders - if a:forceNested && g:NERDUsePlaceHolders - let theLine = s:SwapOutterMultiPartDelimsForPlaceHolders(theLine) - endif - - " find out if the line is commented using normal delims and/or - " alternate ones - let isCommented = s:IsCommented(b:NERDLeft, b:NERDRight, theLine) || s:IsCommented(b:NERDLeftAlt, b:NERDRightAlt, theLine) - - " check if we can comment this line - if !isCommented || g:NERDUsePlaceHolders || s:Multipart() - if a:align == "left" || a:align == "both" - let theLine = s:AddLeftDelimAligned(s:GetLeft(0,1,0), theLine, leftAlignIndx) - else - let theLine = s:AddLeftDelim(s:GetLeft(0,1,0), theLine) - endif - if a:align == "both" - let theLine = s:AddRightDelimAligned(s:GetRight(0,1,0), theLine, rightAlignIndx) - else - let theLine = s:AddRightDelim(s:GetRight(0,1,0), theLine) - endif - endif - endif - - " restore leading tabs if appropriate - if lineHasLeadingTabs - let theLine = s:ConvertLeadingSpacesToTabs(theLine) - endif - - " we are done with this line - call setline(currentLine, theLine) - let currentLine = currentLine + 1 - endwhile - -endfunction - -" Function: s:CommentLinesMinimal(firstLine, lastLine) {{{2 -" This function comments a range of lines in a minimal style. I -" -" Args: -" -firstLine/lastLine: the top and bottom lines to comment -function s:CommentLinesMinimal(firstLine, lastLine) - "check that minimal comments can be done on this filetype - if !s:HasMultipartDelims() - throw 'NERDCommenter.Delimiters exception: Minimal comments can only be used for filetypes that have multipart delimiters' - endif - - "if we need to use place holders for the comment, make sure they are - "enabled for this filetype - if !g:NERDUsePlaceHolders && s:DoesBlockHaveMultipartDelim(a:firstLine, a:lastLine) - throw 'NERDCommenter.Settings exception: Placeoholders are required but disabled.' - endif - - "get the left and right delims to smack on - let left = s:GetSexyComLeft(g:NERDSpaceDelims,0) - let right = s:GetSexyComRight(g:NERDSpaceDelims,0) - - "make sure all multipart delims on the lines are replaced with - "placeholders to prevent illegal syntax - let currentLine = a:firstLine - while(currentLine <= a:lastLine) - let theLine = getline(currentLine) - let theLine = s:ReplaceDelims(left, right, g:NERDLPlace, g:NERDRPlace, theLine) - call setline(currentLine, theLine) - let currentLine = currentLine + 1 - endwhile - - "add the delim to the top line - let theLine = getline(a:firstLine) - let lineHasLeadingTabs = s:HasLeadingTabs(theLine) - let theLine = s:ConvertLeadingTabsToSpaces(theLine) - let theLine = s:AddLeftDelim(left, theLine) - if lineHasLeadingTabs - let theLine = s:ConvertLeadingSpacesToTabs(theLine) - endif - call setline(a:firstLine, theLine) - - "add the delim to the bottom line - let theLine = getline(a:lastLine) - let lineHasLeadingTabs = s:HasLeadingTabs(theLine) - let theLine = s:ConvertLeadingTabsToSpaces(theLine) - let theLine = s:AddRightDelim(right, theLine) - if lineHasLeadingTabs - let theLine = s:ConvertLeadingSpacesToTabs(theLine) - endif - call setline(a:lastLine, theLine) -endfunction - -" Function: s:CommentLinesSexy(topline, bottomline) function {{{2 -" This function is used to comment lines in the 'Sexy' style. eg in c: -" /* -" * This is a sexy comment -" */ -" Args: -" -topline: the line num of the top line in the sexy comment -" -bottomline: the line num of the bottom line in the sexy comment -function s:CommentLinesSexy(topline, bottomline) - let left = s:GetSexyComLeft(0, 0) - let right = s:GetSexyComRight(0, 0) - - "check if we can do a sexy comment with the available delimiters - if left == -1 || right == -1 - throw 'NERDCommenter.Delimiters exception: cannot perform sexy comments with available delimiters.' - endif - - "make sure the lines arent already commented sexually - if !s:CanSexyCommentLines(a:topline, a:bottomline) - throw 'NERDCommenter.Nesting exception: cannot nest sexy comments' - endif - - - let sexyComMarker = s:GetSexyComMarker(0,0) - let sexyComMarkerSpaced = s:GetSexyComMarker(1,0) - - - " we jam the comment as far to the right as possible - let leftAlignIndx = s:LeftMostIndx(1, 1, a:topline, a:bottomline) - - "check if we should use the compact style i.e that the left/right - "delimiters should appear on the first and last lines of the code and not - "on separate lines above/below the first/last lines of code - if g:NERDCompactSexyComs - let spaceString = (g:NERDSpaceDelims ? s:spaceStr : '') - - "comment the top line - let theLine = getline(a:topline) - let lineHasTabs = s:HasLeadingTabs(theLine) - if lineHasTabs - let theLine = s:ConvertLeadingTabsToSpaces(theLine) - endif - let theLine = s:SwapOutterMultiPartDelimsForPlaceHolders(theLine) - let theLine = s:AddLeftDelimAligned(left . spaceString, theLine, leftAlignIndx) - if lineHasTabs - let theLine = s:ConvertLeadingSpacesToTabs(theLine) - endif - call setline(a:topline, theLine) - - "comment the bottom line - if a:bottomline != a:topline - let theLine = getline(a:bottomline) - let lineHasTabs = s:HasLeadingTabs(theLine) - if lineHasTabs - let theLine = s:ConvertLeadingTabsToSpaces(theLine) - endif - let theLine = s:SwapOutterMultiPartDelimsForPlaceHolders(theLine) - endif - let theLine = s:AddRightDelim(spaceString . right, theLine) - if lineHasTabs - let theLine = s:ConvertLeadingSpacesToTabs(theLine) - endif - call setline(a:bottomline, theLine) - else - - " add the left delimiter one line above the lines that are to be commented - call cursor(a:topline, 1) - execute 'normal! O' - call setline(a:topline, repeat(' ', leftAlignIndx) . left ) - - " add the right delimiter after bottom line (we have to add 1 cos we moved - " the lines down when we added the left delim - call cursor(a:bottomline+1, 1) - execute 'normal! o' - call setline(a:bottomline+2, repeat(' ', leftAlignIndx) . repeat(' ', strlen(left)-strlen(sexyComMarker)) . right ) - - endif - - " go thru each line adding the sexyComMarker marker to the start of each - " line in the appropriate place to align them with the comment delims - let currentLine = a:topline+1 - while currentLine <= a:bottomline + !g:NERDCompactSexyComs - " get the line and convert the tabs to spaces - let theLine = getline(currentLine) - let lineHasTabs = s:HasLeadingTabs(theLine) - if lineHasTabs - let theLine = s:ConvertLeadingTabsToSpaces(theLine) - endif - - let theLine = s:SwapOutterMultiPartDelimsForPlaceHolders(theLine) - - " add the sexyComMarker - let theLine = repeat(' ', leftAlignIndx) . repeat(' ', strlen(left)-strlen(sexyComMarker)) . sexyComMarkerSpaced . strpart(theLine, leftAlignIndx) - - if lineHasTabs - let theLine = s:ConvertLeadingSpacesToTabs(theLine) - endif - - - " set the line and move onto the next one - call setline(currentLine, theLine) - let currentLine = currentLine + 1 - endwhile - -endfunction - -" Function: s:CommentLinesToggle(forceNested, firstLine, lastLine) {{{2 -" Applies "toggle" commenting to the given range of lines -" -" Args: -" -forceNested: a flag indicating whether the called is requesting the comment -" to be nested if need be -" -firstLine/lastLine: the top and bottom lines to comment -function s:CommentLinesToggle(forceNested, firstLine, lastLine) - let currentLine = a:firstLine - while currentLine <= a:lastLine - - " get the next line, check commentability and convert spaces to tabs - let theLine = getline(currentLine) - let lineHasLeadingTabs = s:HasLeadingTabs(theLine) - let theLine = s:ConvertLeadingTabsToSpaces(theLine) - if s:CanToggleCommentLine(a:forceNested, currentLine) - - "if the user has specified forceNesting then we check to see if we - "need to switch delimiters for place-holders - if g:NERDUsePlaceHolders - let theLine = s:SwapOutterMultiPartDelimsForPlaceHolders(theLine) - endif - - let theLine = s:AddLeftDelim(s:GetLeft(0, 1, 0), theLine) - let theLine = s:AddRightDelim(s:GetRight(0, 1, 0), theLine) - endif - - " restore leading tabs if appropriate - if lineHasLeadingTabs - let theLine = s:ConvertLeadingSpacesToTabs(theLine) - endif - - " we are done with this line - call setline(currentLine, theLine) - let currentLine = currentLine + 1 - endwhile - -endfunction - -" Function: s:CommentRegion(topline, topCol, bottomLine, bottomCol) function {{{2 -" This function comments chunks of text selected in visual mode. -" It will comment exactly the text that they have selected. -" Args: -" -topLine: the line num of the top line in the sexy comment -" -topCol: top left col for this comment -" -bottomline: the line num of the bottom line in the sexy comment -" -bottomCol: the bottom right col for this comment -" -forceNested: whether the caller wants comments to be nested if the -" line(s) are already commented -function s:CommentRegion(topLine, topCol, bottomLine, bottomCol, forceNested) - - "switch delims (if we can) if the current set isnt multipart - let switchedDelims = 0 - if !s:Multipart() && s:AltMultipart() && !g:NERDAllowAnyVisualDelims - let switchedDelims = 1 - call s:SwitchToAlternativeDelimiters(0) - endif - - "if there is only one line in the comment then just do it - if a:topLine == a:bottomLine - call s:CommentBlock(a:topLine, a:bottomLine, a:topCol, a:bottomCol, a:forceNested) - - "there are multiple lines in the comment - else - "comment the top line - call s:CommentBlock(a:topLine, a:topLine, a:topCol, strlen(getline(a:topLine)), a:forceNested) - - "comment out all the lines in the middle of the comment - let topOfRange = a:topLine+1 - let bottomOfRange = a:bottomLine-1 - if topOfRange <= bottomOfRange - call s:CommentLines(a:forceNested, "none", topOfRange, bottomOfRange) - endif - - "comment the bottom line - let bottom = getline(a:bottomLine) - let numLeadingSpacesTabs = strlen(substitute(bottom, '^\([ \t]*\).*$', '\1', '')) - call s:CommentBlock(a:bottomLine, a:bottomLine, numLeadingSpacesTabs+1, a:bottomCol, a:forceNested) - - endif - - "stick the cursor back on the char it was on before the comment - call cursor(a:topLine, a:topCol + strlen(b:NERDLeft) + g:NERDSpaceDelims) - - "if we switched delims then we gotta go back to what they were before - if switchedDelims == 1 - call s:SwitchToAlternativeDelimiters(0) - endif - -endfunction - -" Function: s:InvertComment(firstLine, lastLine) function {{{2 -" Inverts the comments on the lines between and including the given line -" numbers i.e all commented lines are uncommented and vice versa -" Args: -" -firstLine: the top of the range of lines to be inverted -" -lastLine: the bottom of the range of lines to be inverted -function s:InvertComment(firstLine, lastLine) - - " go thru all lines in the given range - let currentLine = a:firstLine - while currentLine <= a:lastLine - let theLine = getline(currentLine) - - let sexyComBounds = s:FindBoundingLinesOfSexyCom(currentLine) - - " if the line is commented normally, uncomment it - if s:IsCommentedFromStartOfLine(b:NERDLeft, theLine) || s:IsCommentedFromStartOfLine(b:NERDLeftAlt, theLine) - call s:UncommentLines(currentLine, currentLine) - let currentLine = currentLine + 1 - - " check if the line is commented sexually - elseif !empty(sexyComBounds) - let numLinesBeforeSexyComRemoved = s:NumLinesInBuf() - call s:UncommentLinesSexy(sexyComBounds[0], sexyComBounds[1]) - - "move to the line after last line of the sexy comment - let numLinesAfterSexyComRemoved = s:NumLinesInBuf() - let currentLine = bottomBound - (numLinesBeforeSexyComRemoved - numLinesAfterSexyComRemoved) + 1 - - " the line isnt commented - else - call s:CommentLinesToggle(1, currentLine, currentLine) - let currentLine = currentLine + 1 - endif - - endwhile -endfunction - -" Function: NERDComment(isVisual, type) function {{{2 -" This function is a Wrapper for the main commenting functions -" -" Args: -" -isVisual: a flag indicating whether the comment is requested in visual -" mode or not -" -type: the type of commenting requested. Can be 'sexy', 'invert', -" 'minimal', 'toggle', 'alignLeft', 'alignBoth', 'norm', -" 'nested', 'toEOL', 'append', 'insert', 'uncomment', 'yank' -function! NERDComment(isVisual, type) range - " we want case sensitivity when commenting - let oldIgnoreCase = &ignorecase - set noignorecase - - if a:isVisual - let firstLine = line("'<") - let lastLine = line("'>") - let firstCol = col("'<") - let lastCol = col("'>") - (&selection == 'exclusive' ? 1 : 0) - else - let firstLine = a:firstline - let lastLine = a:lastline - endif - - let countWasGiven = (a:isVisual == 0 && firstLine != lastLine) - - let forceNested = (a:type == 'nested' || g:NERDDefaultNesting) - - if a:type == 'norm' || a:type == 'nested' - if a:isVisual && visualmode() == "" - call s:CommentBlock(firstLine, lastLine, firstCol, lastCol, forceNested) - elseif a:isVisual && visualmode() == "v" && (g:NERDCommentWholeLinesInVMode==0 || (g:NERDCommentWholeLinesInVMode==2 && s:HasMultipartDelims())) - call s:CommentRegion(firstLine, firstCol, lastLine, lastCol, forceNested) - else - call s:CommentLines(forceNested, "none", firstLine, lastLine) - endif - - elseif a:type == 'alignLeft' || a:type == 'alignBoth' - let align = "none" - if a:type == "alignLeft" - let align = "left" - elseif a:type == "alignBoth" - let align = "both" - endif - call s:CommentLines(forceNested, align, firstLine, lastLine) - - elseif a:type == 'invert' - call s:InvertComment(firstLine, lastLine) - - elseif a:type == 'sexy' - try - call s:CommentLinesSexy(firstLine, lastLine) - catch /NERDCommenter.Delimiters/ - call s:CommentLines(forceNested, "none", firstLine, lastLine) - catch /NERDCommenter.Nesting/ - call s:NerdEcho("Sexy comment aborted. Nested sexy cannot be nested", 0) - endtry - - elseif a:type == 'toggle' - let theLine = getline(firstLine) - - if s:IsInSexyComment(firstLine) || s:IsCommentedFromStartOfLine(b:NERDLeft, theLine) || s:IsCommentedFromStartOfLine(b:NERDLeftAlt, theLine) - call s:UncommentLines(firstLine, lastLine) - else - call s:CommentLinesToggle(forceNested, firstLine, lastLine) - endif - - elseif a:type == 'minimal' - try - call s:CommentLinesMinimal(firstLine, lastLine) - catch /NERDCommenter.Delimiters/ - call s:NerdEcho("Minimal comments can only be used for filetypes that have multipart delimiters.", 0) - catch /NERDCommenter.Settings/ - call s:NerdEcho("Place holders are required but disabled.", 0) - endtry - - elseif a:type == 'toEOL' - call s:SaveScreenState() - call s:CommentBlock(firstLine, firstLine, col("."), col("$")-1, 1) - call s:RestoreScreenState() - - elseif a:type == 'append' - call s:AppendCommentToLine() - - elseif a:type == 'insert' - call s:PlaceDelimitersAndInsBetween() - - elseif a:type == 'uncomment' - call s:UncommentLines(firstLine, lastLine) - - elseif a:type == 'yank' - if a:isVisual - normal! gvy - elseif countWasGiven - execute firstLine .','. lastLine .'yank' - else - normal! yy - endif - execute firstLine .','. lastLine .'call NERDComment('. a:isVisual .', "norm")' - endif - - let &ignorecase = oldIgnoreCase -endfunction - -" Function: s:PlaceDelimitersAndInsBetween() function {{{2 -" This is function is called to place comment delimiters down and place the -" cursor between them -function s:PlaceDelimitersAndInsBetween() - " get the left and right delimiters without any escape chars in them - let left = s:GetLeft(0, 1, 0) - let right = s:GetRight(0, 1, 0) - - let theLine = getline(".") - let lineHasLeadTabs = s:HasLeadingTabs(theLine) || (theLine =~ '^ *$' && !&expandtab) - - "convert tabs to spaces and adjust the cursors column to take this into - "account - let untabbedCol = s:UntabbedCol(theLine, col(".")) - call setline(line("."), s:ConvertLeadingTabsToSpaces(theLine)) - call cursor(line("."), untabbedCol) - - " get the len of the right delim - let lenRight = strlen(right) - - let isDelimOnEOL = col(".") >= strlen(getline(".")) - - " if the cursor is in the first col then we gotta insert rather than - " append the comment delimiters here - let insOrApp = (col(".")==1 ? 'i' : 'a') - - " place the delimiters down. We do it differently depending on whether - " there is a left AND right delimiter - if lenRight > 0 - execute ":normal! " . insOrApp . left . right - execute ":normal! " . lenRight . "h" - else - execute ":normal! " . insOrApp . left - - " if we are tacking the delim on the EOL then we gotta add a space - " after it cos when we go out of insert mode the cursor will move back - " one and the user wont be in position to type the comment. - if isDelimOnEOL - execute 'normal! a ' - endif - endif - normal! l - - "if needed convert spaces back to tabs and adjust the cursors col - "accordingly - if lineHasLeadTabs - let tabbedCol = s:TabbedCol(getline("."), col(".")) - call setline(line("."), s:ConvertLeadingSpacesToTabs(getline("."))) - call cursor(line("."), tabbedCol) - endif - - startinsert -endfunction - -" Function: s:RemoveDelimiters(left, right, line) {{{2 -" this function is called to remove the first left comment delimiter and the -" last right delimiter of the given line. -" -" The args left and right must be strings. If there is no right delimiter (as -" is the case for e.g vim file comments) them the arg right should be "" -" -" Args: -" -left: the left comment delimiter -" -right: the right comment delimiter -" -line: the line to remove the delimiters from -function s:RemoveDelimiters(left, right, line) - - let l:left = a:left - let l:right = a:right - let lenLeft = strlen(left) - let lenRight = strlen(right) - - let delimsSpaced = (g:NERDSpaceDelims || g:NERDRemoveExtraSpaces) - - let line = a:line - - "look for the left delimiter, if we find it, remove it. - let leftIndx = s:FindDelimiterIndex(a:left, line) - if leftIndx != -1 - let line = strpart(line, 0, leftIndx) . strpart(line, leftIndx+lenLeft) - - "if the user has specified that there is a space after the left delim - "then check for the space and remove it if it is there - if delimsSpaced && strpart(line, leftIndx, s:lenSpaceStr) == s:spaceStr - let line = strpart(line, 0, leftIndx) . strpart(line, leftIndx+s:lenSpaceStr) - endif - endif - - "look for the right delimiter, if we find it, remove it - let rightIndx = s:FindDelimiterIndex(a:right, line) - if rightIndx != -1 - let line = strpart(line, 0, rightIndx) . strpart(line, rightIndx+lenRight) - - "if the user has specified that there is a space before the right delim - "then check for the space and remove it if it is there - if delimsSpaced && strpart(line, rightIndx-s:lenSpaceStr, s:lenSpaceStr) == s:spaceStr && s:Multipart() - let line = strpart(line, 0, rightIndx-s:lenSpaceStr) . strpart(line, rightIndx) - endif - endif - - return line -endfunction - -" Function: s:UncommentLines(topLine, bottomLine) {{{2 -" This function uncomments the given lines -" -" Args: -" topLine: the top line of the visual selection to uncomment -" bottomLine: the bottom line of the visual selection to uncomment -function s:UncommentLines(topLine, bottomLine) - "make local copies of a:firstline and a:lastline and, if need be, swap - "them around if the top line is below the bottom - let l:firstline = a:topLine - let l:lastline = a:bottomLine - if firstline > lastline - let firstline = lastline - let lastline = a:topLine - endif - - "go thru each line uncommenting each line removing sexy comments - let currentLine = firstline - while currentLine <= lastline - - "check the current line to see if it is part of a sexy comment - let sexyComBounds = s:FindBoundingLinesOfSexyCom(currentLine) - if !empty(sexyComBounds) - - "we need to store the num lines in the buf before the comment is - "removed so we know how many lines were removed when the sexy com - "was removed - let numLinesBeforeSexyComRemoved = s:NumLinesInBuf() - - call s:UncommentLinesSexy(sexyComBounds[0], sexyComBounds[1]) - - "move to the line after last line of the sexy comment - let numLinesAfterSexyComRemoved = s:NumLinesInBuf() - let numLinesRemoved = numLinesBeforeSexyComRemoved - numLinesAfterSexyComRemoved - let currentLine = sexyComBounds[1] - numLinesRemoved + 1 - let lastline = lastline - numLinesRemoved - - "no sexy com was detected so uncomment the line as normal - else - call s:UncommentLinesNormal(currentLine, currentLine) - let currentLine = currentLine + 1 - endif - endwhile - -endfunction - -" Function: s:UncommentLinesSexy(topline, bottomline) {{{2 -" This function removes all the comment characters associated with the sexy -" comment spanning the given lines -" Args: -" -topline/bottomline: the top/bottom lines of the sexy comment -function s:UncommentLinesSexy(topline, bottomline) - let left = s:GetSexyComLeft(0,1) - let right = s:GetSexyComRight(0,1) - - - "check if it is even possible for sexy comments to exist with the - "available delimiters - if left == -1 || right == -1 - throw 'NERDCommenter.Delimiters exception: cannot uncomment sexy comments with available delimiters.' - endif - - let leftUnEsc = s:GetSexyComLeft(0,0) - let rightUnEsc = s:GetSexyComRight(0,0) - - let sexyComMarker = s:GetSexyComMarker(0, 1) - let sexyComMarkerUnEsc = s:GetSexyComMarker(0, 0) - - "the markerOffset is how far right we need to move the sexyComMarker to - "line it up with the end of the left delim - let markerOffset = strlen(leftUnEsc)-strlen(sexyComMarkerUnEsc) - - " go thru the intermediate lines of the sexy comment and remove the - " sexy comment markers (eg the '*'s on the start of line in a c sexy - " comment) - let currentLine = a:topline+1 - while currentLine < a:bottomline - let theLine = getline(currentLine) - - " remove the sexy comment marker from the line. We also remove the - " space after it if there is one and if appropriate options are set - let sexyComMarkerIndx = stridx(theLine, sexyComMarkerUnEsc) - if strpart(theLine, sexyComMarkerIndx+strlen(sexyComMarkerUnEsc), s:lenSpaceStr) == s:spaceStr && g:NERDSpaceDelims - let theLine = strpart(theLine, 0, sexyComMarkerIndx - markerOffset) . strpart(theLine, sexyComMarkerIndx+strlen(sexyComMarkerUnEsc)+s:lenSpaceStr) - else - let theLine = strpart(theLine, 0, sexyComMarkerIndx - markerOffset) . strpart(theLine, sexyComMarkerIndx+strlen(sexyComMarkerUnEsc)) - endif - - let theLine = s:SwapOutterPlaceHoldersForMultiPartDelims(theLine) - - let theLine = s:ConvertLeadingWhiteSpace(theLine) - - " move onto the next line - call setline(currentLine, theLine) - let currentLine = currentLine + 1 - endwhile - - " gotta make a copy of a:bottomline cos we modify the position of the - " last line it if we remove the topline - let bottomline = a:bottomline - - " get the first line so we can remove the left delim from it - let theLine = getline(a:topline) - - " if the first line contains only the left delim then just delete it - if theLine =~ '^[ \t]*' . left . '[ \t]*$' && !g:NERDCompactSexyComs - call cursor(a:topline, 1) - normal! dd - let bottomline = bottomline - 1 - - " topline contains more than just the left delim - else - - " remove the delim. If there is a space after it - " then remove this too if appropriate - let delimIndx = stridx(theLine, leftUnEsc) - if strpart(theLine, delimIndx+strlen(leftUnEsc), s:lenSpaceStr) == s:spaceStr && g:NERDSpaceDelims - let theLine = strpart(theLine, 0, delimIndx) . strpart(theLine, delimIndx+strlen(leftUnEsc)+s:lenSpaceStr) - else - let theLine = strpart(theLine, 0, delimIndx) . strpart(theLine, delimIndx+strlen(leftUnEsc)) - endif - let theLine = s:SwapOutterPlaceHoldersForMultiPartDelims(theLine) - call setline(a:topline, theLine) - endif - - " get the last line so we can remove the right delim - let theLine = getline(bottomline) - - " if the bottomline contains only the right delim then just delete it - if theLine =~ '^[ \t]*' . right . '[ \t]*$' - call cursor(bottomline, 1) - normal! dd - - " the last line contains more than the right delim - else - " remove the right delim. If there is a space after it and - " if the appropriate options are set then remove this too. - let delimIndx = s:LastIndexOfDelim(rightUnEsc, theLine) - if strpart(theLine, delimIndx+strlen(leftUnEsc), s:lenSpaceStr) == s:spaceStr && g:NERDSpaceDelims - let theLine = strpart(theLine, 0, delimIndx) . strpart(theLine, delimIndx+strlen(rightUnEsc)+s:lenSpaceStr) - else - let theLine = strpart(theLine, 0, delimIndx) . strpart(theLine, delimIndx+strlen(rightUnEsc)) - endif - - " if the last line also starts with a sexy comment marker then we - " remove this as well - if theLine =~ '^[ \t]*' . sexyComMarker - - " remove the sexyComMarker. If there is a space after it then - " remove that too - let sexyComMarkerIndx = stridx(theLine, sexyComMarkerUnEsc) - if strpart(theLine, sexyComMarkerIndx+strlen(sexyComMarkerUnEsc), s:lenSpaceStr) == s:spaceStr && g:NERDSpaceDelims - let theLine = strpart(theLine, 0, sexyComMarkerIndx - markerOffset ) . strpart(theLine, sexyComMarkerIndx+strlen(sexyComMarkerUnEsc)+s:lenSpaceStr) - else - let theLine = strpart(theLine, 0, sexyComMarkerIndx - markerOffset ) . strpart(theLine, sexyComMarkerIndx+strlen(sexyComMarkerUnEsc)) - endif - endif - - let theLine = s:SwapOutterPlaceHoldersForMultiPartDelims(theLine) - call setline(bottomline, theLine) - endif -endfunction - -" Function: s:UncommentLineNormal(line) {{{2 -" uncomments the given line and returns the result -" Args: -" -line: the line to uncomment -function s:UncommentLineNormal(line) - let line = a:line - - "get the comment status on the line so we know how it is commented - let lineCommentStatus = s:IsCommentedOuttermost(b:NERDLeft, b:NERDRight, b:NERDLeftAlt, b:NERDRightAlt, line) - - "it is commented with b:NERDLeft and b:NERDRight so remove these delims - if lineCommentStatus == 1 - let line = s:RemoveDelimiters(b:NERDLeft, b:NERDRight, line) - - "it is commented with b:NERDLeftAlt and b:NERDRightAlt so remove these delims - elseif lineCommentStatus == 2 && g:NERDRemoveAltComs - let line = s:RemoveDelimiters(b:NERDLeftAlt, b:NERDRightAlt, line) - - "it is not properly commented with any delims so we check if it has - "any random left or right delims on it and remove the outtermost ones - else - "get the positions of all delim types on the line - let indxLeft = s:FindDelimiterIndex(b:NERDLeft, line) - let indxLeftAlt = s:FindDelimiterIndex(b:NERDLeftAlt, line) - let indxRight = s:FindDelimiterIndex(b:NERDRight, line) - let indxRightAlt = s:FindDelimiterIndex(b:NERDRightAlt, line) - - "remove the outter most left comment delim - if indxLeft != -1 && (indxLeft < indxLeftAlt || indxLeftAlt == -1) - let line = s:RemoveDelimiters(b:NERDLeft, '', line) - elseif indxLeftAlt != -1 - let line = s:RemoveDelimiters(b:NERDLeftAlt, '', line) - endif - - "remove the outter most right comment delim - if indxRight != -1 && (indxRight < indxRightAlt || indxRightAlt == -1) - let line = s:RemoveDelimiters('', b:NERDRight, line) - elseif indxRightAlt != -1 - let line = s:RemoveDelimiters('', b:NERDRightAlt, line) - endif - endif - - - let indxLeft = s:FindDelimiterIndex(b:NERDLeft, line) - let indxLeftAlt = s:FindDelimiterIndex(b:NERDLeftAlt, line) - let indxLeftPlace = s:FindDelimiterIndex(g:NERDLPlace, line) - - let indxRightPlace = s:FindDelimiterIndex(g:NERDRPlace, line) - let indxRightAlt = s:FindDelimiterIndex(b:NERDRightAlt, line) - let indxRightPlace = s:FindDelimiterIndex(g:NERDRPlace, line) - - let right = b:NERDRight - let left = b:NERDLeft - if !s:Multipart() - let right = b:NERDRightAlt - let left = b:NERDLeftAlt - endif - - - "if there are place-holders on the line then we check to see if they are - "the outtermost delimiters on the line. If so then we replace them with - "real delimiters - if indxLeftPlace != -1 - if (indxLeftPlace < indxLeft || indxLeft==-1) && (indxLeftPlace < indxLeftAlt || indxLeftAlt==-1) - let line = s:ReplaceDelims(g:NERDLPlace, g:NERDRPlace, left, right, line) - endif - elseif indxRightPlace != -1 - if (indxRightPlace < indxLeft || indxLeft==-1) && (indxLeftPlace < indxLeftAlt || indxLeftAlt==-1) - let line = s:ReplaceDelims(g:NERDLPlace, g:NERDRPlace, left, right, line) - endif - - endif - - let line = s:ConvertLeadingWhiteSpace(line) - - return line -endfunction - -" Function: s:UncommentLinesNormal(topline, bottomline) {{{2 -" This function is called to uncomment lines that arent a sexy comment -" Args: -" -topline/bottomline: the top/bottom line numbers of the comment -function s:UncommentLinesNormal(topline, bottomline) - let currentLine = a:topline - while currentLine <= a:bottomline - let line = getline(currentLine) - call setline(currentLine, s:UncommentLineNormal(line)) - let currentLine = currentLine + 1 - endwhile -endfunction - - -" Section: Other helper functions {{{1 -" ============================================================================ - -" Function: s:AddLeftDelim(delim, theLine) {{{2 -" Args: -function s:AddLeftDelim(delim, theLine) - return substitute(a:theLine, '^\([ \t]*\)', '\1' . a:delim, '') -endfunction - -" Function: s:AddLeftDelimAligned(delim, theLine) {{{2 -" Args: -function s:AddLeftDelimAligned(delim, theLine, alignIndx) - - "if the line is not long enough then bung some extra spaces on the front - "so we can align the delim properly - let theLine = a:theLine - if strlen(theLine) < a:alignIndx - let theLine = repeat(' ', a:alignIndx - strlen(theLine)) - endif - - return strpart(theLine, 0, a:alignIndx) . a:delim . strpart(theLine, a:alignIndx) -endfunction - -" Function: s:AddRightDelim(delim, theLine) {{{2 -" Args: -function s:AddRightDelim(delim, theLine) - if a:delim == '' - return a:theLine - else - return substitute(a:theLine, '$', a:delim, '') - endif -endfunction - -" Function: s:AddRightDelimAligned(delim, theLine, alignIndx) {{{2 -" Args: -function s:AddRightDelimAligned(delim, theLine, alignIndx) - if a:delim == "" - return a:theLine - else - - " when we align the right delim we are just adding spaces - " so we get a string containing the needed spaces (it - " could be empty) - let extraSpaces = '' - let extraSpaces = repeat(' ', a:alignIndx-strlen(a:theLine)) - - " add the right delim - return substitute(a:theLine, '$', extraSpaces . a:delim, '') - endif -endfunction - -" Function: s:AltMultipart() {{{2 -" returns 1 if the alternative delims are multipart -function s:AltMultipart() - return b:NERDRightAlt != '' -endfunction - -" Function: s:CanCommentLine(forceNested, line) {{{2 -"This function is used to determine whether the given line can be commented. -"It returns 1 if it can be and 0 otherwise -" -" Args: -" -forceNested: a flag indicating whether the caller wants comments to be nested -" if the current line is already commented -" -lineNum: the line num of the line to check for commentability -function s:CanCommentLine(forceNested, lineNum) - let theLine = getline(a:lineNum) - - " make sure we don't comment lines that are just spaces or tabs or empty. - if theLine =~ "^[ \t]*$" - return 0 - endif - - "if the line is part of a sexy comment then just flag it... - if s:IsInSexyComment(a:lineNum) - return 0 - endif - - let isCommented = s:IsCommentedNormOrSexy(a:lineNum) - - "if the line isnt commented return true - if !isCommented - return 1 - endif - - "if the line is commented but nesting is allowed then return true - if a:forceNested && (!s:Multipart() || g:NERDUsePlaceHolders) - return 1 - endif - - return 0 -endfunction - -" Function: s:CanPlaceCursor(line, col) {{{2 -" returns 1 if the cursor can be placed exactly in the given position -function s:CanPlaceCursor(line, col) - let c = col(".") - let l = line(".") - call cursor(a:line, a:col) - let success = (line(".") == a:line && col(".") == a:col) - call cursor(l,c) - return success -endfunction - -" Function: s:CanSexyCommentLines(topline, bottomline) {{{2 -" Return: 1 if the given lines can be commented sexually, 0 otherwise -function s:CanSexyCommentLines(topline, bottomline) - " see if the selected regions have any sexy comments - let currentLine = a:topline - while(currentLine <= a:bottomline) - if s:IsInSexyComment(currentLine) - return 0 - endif - let currentLine = currentLine + 1 - endwhile - return 1 -endfunction -" Function: s:CanToggleCommentLine(forceNested, line) {{{2 -"This function is used to determine whether the given line can be toggle commented. -"It returns 1 if it can be and 0 otherwise -" -" Args: -" -lineNum: the line num of the line to check for commentability -function s:CanToggleCommentLine(forceNested, lineNum) - let theLine = getline(a:lineNum) - if (s:IsCommentedFromStartOfLine(b:NERDLeft, theLine) || s:IsCommentedFromStartOfLine(b:NERDLeftAlt, theLine)) && !a:forceNested - return 0 - endif - - " make sure we don't comment lines that are just spaces or tabs or empty. - if theLine =~ "^[ \t]*$" - return 0 - endif - - "if the line is part of a sexy comment then just flag it... - if s:IsInSexyComment(a:lineNum) - return 0 - endif - - return 1 -endfunction - -" Function: s:ConvertLeadingSpacesToTabs(line) {{{2 -" This function takes a line and converts all leading tabs on that line into -" spaces -" -" Args: -" -line: the line whose leading tabs will be converted -function s:ConvertLeadingSpacesToTabs(line) - let toReturn = a:line - while toReturn =~ '^\t*' . s:TabSpace() . '\(.*\)$' - let toReturn = substitute(toReturn, '^\(\t*\)' . s:TabSpace() . '\(.*\)$' , '\1\t\2' , "") - endwhile - - return toReturn -endfunction - - -" Function: s:ConvertLeadingTabsToSpaces(line) {{{2 -" This function takes a line and converts all leading spaces on that line into -" tabs -" -" Args: -" -line: the line whose leading spaces will be converted -function s:ConvertLeadingTabsToSpaces(line) - let toReturn = a:line - while toReturn =~ '^\( *\)\t' - let toReturn = substitute(toReturn, '^\( *\)\t', '\1' . s:TabSpace() , "") - endwhile - - return toReturn -endfunction - -" Function: s:ConvertLeadingWhiteSpace(line) {{{2 -" Converts the leading white space to tabs/spaces depending on &ts -" -" Args: -" -line: the line to convert -function s:ConvertLeadingWhiteSpace(line) - let toReturn = a:line - while toReturn =~ '^ *\t' - let toReturn = substitute(toReturn, '^ *\zs\t\ze', s:TabSpace(), "g") - endwhile - - if !&expandtab - let toReturn = s:ConvertLeadingSpacesToTabs(toReturn) - endif - - return toReturn -endfunction - - -" Function: s:CountNonESCedOccurances(str, searchstr, escChar) {{{2 -" This function counts the number of substrings contained in another string. -" These substrings are only counted if they are not escaped with escChar -" Args: -" -str: the string to look for searchstr in -" -searchstr: the substring to search for in str -" -escChar: the escape character which, when preceding an instance of -" searchstr, will cause it not to be counted -function s:CountNonESCedOccurances(str, searchstr, escChar) - "get the index of the first occurrence of searchstr - let indx = stridx(a:str, a:searchstr) - - "if there is an instance of searchstr in str process it - if indx != -1 - "get the remainder of str after this instance of searchstr is removed - let lensearchstr = strlen(a:searchstr) - let strLeft = strpart(a:str, indx+lensearchstr) - - "if this instance of searchstr is not escaped, add one to the count - "and recurse. If it is escaped, just recurse - if !s:IsEscaped(a:str, indx, a:escChar) - return 1 + s:CountNonESCedOccurances(strLeft, a:searchstr, a:escChar) - else - return s:CountNonESCedOccurances(strLeft, a:searchstr, a:escChar) - endif - endif -endfunction -" Function: s:DoesBlockHaveDelim(delim, top, bottom) {{{2 -" Returns 1 if the given block of lines has a delimiter (a:delim) in it -" Args: -" -delim: the comment delimiter to check the block for -" -top: the top line number of the block -" -bottom: the bottom line number of the block -function s:DoesBlockHaveDelim(delim, top, bottom) - let currentLine = a:top - while currentLine < a:bottom - let theline = getline(currentLine) - if s:FindDelimiterIndex(a:delim, theline) != -1 - return 1 - endif - let currentLine = currentLine + 1 - endwhile - return 0 -endfunction - -" Function: s:DoesBlockHaveMultipartDelim(top, bottom) {{{2 -" Returns 1 if the given block has a >= 1 multipart delimiter in it -" Args: -" -top: the top line number of the block -" -bottom: the bottom line number of the block -function s:DoesBlockHaveMultipartDelim(top, bottom) - if s:HasMultipartDelims() - if s:Multipart() - return s:DoesBlockHaveDelim(b:NERDLeft, a:top, a:bottom) || s:DoesBlockHaveDelim(b:NERDRight, a:top, a:bottom) - else - return s:DoesBlockHaveDelim(b:NERDLeftAlt, a:top, a:bottom) || s:DoesBlockHaveDelim(b:NERDRightAlt, a:top, a:bottom) - endif - endif - return 0 -endfunction - - -" Function: s:Esc(str) {{{2 -" Escapes all the tricky chars in the given string -function s:Esc(str) - let charsToEsc = '*/\."&$+' - return escape(a:str, charsToEsc) -endfunction - -" Function: s:FindDelimiterIndex(delimiter, line) {{{2 -" This function is used to get the string index of the input comment delimiter -" on the input line. If no valid comment delimiter is found in the line then -" -1 is returned -" Args: -" -delimiter: the delimiter we are looking to find the index of -" -line: the line we are looking for delimiter on -function s:FindDelimiterIndex(delimiter, line) - - "make sure the delimiter isnt empty otherwise we go into an infinite loop. - if a:delimiter == "" - return -1 - endif - - - let l:delimiter = a:delimiter - let lenDel = strlen(l:delimiter) - - "get the index of the first occurrence of the delimiter - let delIndx = stridx(a:line, l:delimiter) - - "keep looping thru the line till we either find a real comment delimiter - "or run off the EOL - while delIndx != -1 - - "if we are not off the EOL get the str before the possible delimiter - "in question and check if it really is a delimiter. If it is, return - "its position - if delIndx != -1 - if s:IsDelimValid(l:delimiter, delIndx, a:line) - return delIndx - endif - endif - - "we have not yet found a real comment delimiter so move past the - "current one we are lookin at - let restOfLine = strpart(a:line, delIndx + lenDel) - let distToNextDelim = stridx(restOfLine , l:delimiter) - - "if distToNextDelim is -1 then there is no more potential delimiters - "on the line so set delIndx to -1. Otherwise, move along the line by - "distToNextDelim - if distToNextDelim == -1 - let delIndx = -1 - else - let delIndx = delIndx + lenDel + distToNextDelim - endif - endwhile - - "there is no comment delimiter on this line - return -1 -endfunction - -" Function: s:FindBoundingLinesOfSexyCom(lineNum) {{{2 -" This function takes in a line number and tests whether this line number is -" the top/bottom/middle line of a sexy comment. If it is then the top/bottom -" lines of the sexy comment are returned -" Args: -" -lineNum: the line number that is to be tested whether it is the -" top/bottom/middle line of a sexy com -" Returns: -" A string that has the top/bottom lines of the sexy comment encoded in it. -" The format is 'topline,bottomline'. If a:lineNum turns out not to be the -" top/bottom/middle of a sexy comment then -1 is returned -function s:FindBoundingLinesOfSexyCom(lineNum) - - "find which delimiters to look for as the start/end delims of the comment - let left = '' - let right = '' - if s:Multipart() - let left = s:GetLeft(0,0,1) - let right = s:GetRight(0,0,1) - elseif s:AltMultipart() - let left = s:GetLeft(1,0,1) - let right = s:GetRight(1,0,1) - else - return [] - endif - - let sexyComMarker = s:GetSexyComMarker(0, 1) - - "initialise the top/bottom line numbers of the sexy comment to -1 - let top = -1 - let bottom = -1 - - let currentLine = a:lineNum - while top == -1 || bottom == -1 - let theLine = getline(currentLine) - - "check if the current line is the top of the sexy comment - if currentLine <= a:lineNum && theLine =~ '^[ \t]*' . left && theLine !~ '.*' . right && currentLine < s:NumLinesInBuf() - let top = currentLine - let currentLine = a:lineNum - - "check if the current line is the bottom of the sexy comment - elseif theLine =~ '^[ \t]*' . right && theLine !~ '.*' . left && currentLine > 1 - let bottom = currentLine - - "the right delimiter is on the same line as the last sexyComMarker - elseif theLine =~ '^[ \t]*' . sexyComMarker . '.*' . right - let bottom = currentLine - - "we have not found the top or bottom line so we assume currentLine is an - "intermediate line and look to prove otherwise - else - - "if the line doesnt start with a sexyComMarker then it is not a sexy - "comment - if theLine !~ '^[ \t]*' . sexyComMarker - return [] - endif - - endif - - "if top is -1 then we havent found the top yet so keep looking up - if top == -1 - let currentLine = currentLine - 1 - "if we have found the top line then go down looking for the bottom - else - let currentLine = currentLine + 1 - endif - - endwhile - - return [top, bottom] -endfunction - - -" Function: s:GetLeft(alt, space, esc) {{{2 -" returns the left/left-alternative delimiter -" Args: -" -alt: specifies whether to get left or left-alternative delim -" -space: specifies whether the delim should be spaced or not -" (the space string will only be added if NERDSpaceDelims is set) -" -esc: specifies whether the tricky chars in the delim should be ESCed -function s:GetLeft(alt, space, esc) - let delim = b:NERDLeft - - if a:alt - if b:NERDLeftAlt == '' - return '' - else - let delim = b:NERDLeftAlt - endif - endif - if delim == '' - return '' - endif - - if a:space && g:NERDSpaceDelims - let delim = delim . s:spaceStr - endif - - if a:esc - let delim = s:Esc(delim) - endif - - return delim -endfunction - -" Function: s:GetRight(alt, space, esc) {{{2 -" returns the right/right-alternative delimiter -" Args: -" -alt: specifies whether to get right or right-alternative delim -" -space: specifies whether the delim should be spaced or not -" (the space string will only be added if NERDSpaceDelims is set) -" -esc: specifies whether the tricky chars in the delim should be ESCed -function s:GetRight(alt, space, esc) - let delim = b:NERDRight - - if a:alt - if !s:AltMultipart() - return '' - else - let delim = b:NERDRightAlt - endif - endif - if delim == '' - return '' - endif - - if a:space && g:NERDSpaceDelims - let delim = s:spaceStr . delim - endif - - if a:esc - let delim = s:Esc(delim) - endif - - return delim -endfunction - - -" Function: s:GetSexyComMarker() {{{2 -" Returns the sexy comment marker for the current filetype. -" -" C style sexy comments are assumed if possible. If not then the sexy comment -" marker is the last char of the delimiter pair that has both left and right -" delims and has the longest left delim -" -" Args: -" -space: specifies whether the marker is to have a space string after it -" (the space string will only be added if NERDSpaceDelims is set) -" -esc: specifies whether the tricky chars in the marker are to be ESCed -function s:GetSexyComMarker(space, esc) - let sexyComMarker = b:NERDSexyComMarker - - "if there is no hardcoded marker then we find one - if sexyComMarker == '' - - "if the filetype has c style comments then use standard c sexy - "comments - if s:HasCStyleComments() - let sexyComMarker = '*' - else - "find a comment marker by getting the longest available left delim - "(that has a corresponding right delim) and taking the last char - let lenLeft = strlen(b:NERDLeft) - let lenLeftAlt = strlen(b:NERDLeftAlt) - let left = '' - let right = '' - if s:Multipart() && lenLeft >= lenLeftAlt - let left = b:NERDLeft - elseif s:AltMultipart() - let left = b:NERDLeftAlt - else - return -1 - endif - - "get the last char of left - let sexyComMarker = strpart(left, strlen(left)-1) - endif - endif - - if a:space && g:NERDSpaceDelims - let sexyComMarker = sexyComMarker . s:spaceStr - endif - - if a:esc - let sexyComMarker = s:Esc(sexyComMarker) - endif - - return sexyComMarker -endfunction - -" Function: s:GetSexyComLeft(space, esc) {{{2 -" Returns the left delimiter for sexy comments for this filetype or -1 if -" there is none. C style sexy comments are used if possible -" Args: -" -space: specifies if the delim has a space string on the end -" (the space string will only be added if NERDSpaceDelims is set) -" -esc: specifies whether the tricky chars in the string are ESCed -function s:GetSexyComLeft(space, esc) - let lenLeft = strlen(b:NERDLeft) - let lenLeftAlt = strlen(b:NERDLeftAlt) - let left = '' - - "assume c style sexy comments if possible - if s:HasCStyleComments() - let left = '/*' - else - "grab the longest left delim that has a right - if s:Multipart() && lenLeft >= lenLeftAlt - let left = b:NERDLeft - elseif s:AltMultipart() - let left = b:NERDLeftAlt - else - return -1 - endif - endif - - if a:space && g:NERDSpaceDelims - let left = left . s:spaceStr - endif - - if a:esc - let left = s:Esc(left) - endif - - return left -endfunction - -" Function: s:GetSexyComRight(space, esc) {{{2 -" Returns the right delimiter for sexy comments for this filetype or -1 if -" there is none. C style sexy comments are used if possible. -" Args: -" -space: specifies if the delim has a space string on the start -" (the space string will only be added if NERDSpaceDelims -" is specified for the current filetype) -" -esc: specifies whether the tricky chars in the string are ESCed -function s:GetSexyComRight(space, esc) - let lenLeft = strlen(b:NERDLeft) - let lenLeftAlt = strlen(b:NERDLeftAlt) - let right = '' - - "assume c style sexy comments if possible - if s:HasCStyleComments() - let right = '*/' - else - "grab the right delim that pairs with the longest left delim - if s:Multipart() && lenLeft >= lenLeftAlt - let right = b:NERDRight - elseif s:AltMultipart() - let right = b:NERDRightAlt - else - return -1 - endif - endif - - if a:space && g:NERDSpaceDelims - let right = s:spaceStr . right - endif - - if a:esc - let right = s:Esc(right) - endif - - return right -endfunction - -" Function: s:HasMultipartDelims() {{{2 -" Returns 1 iff the current filetype has at least one set of multipart delims -function s:HasMultipartDelims() - return s:Multipart() || s:AltMultipart() -endfunction - -" Function: s:HasLeadingTabs(...) {{{2 -" Returns 1 if any of the given strings have leading tabs -function s:HasLeadingTabs(...) - for s in a:000 - if s =~ '^\t.*' - return 1 - end - endfor - return 0 -endfunction -" Function: s:HasCStyleComments() {{{2 -" Returns 1 iff the current filetype has c style comment delimiters -function s:HasCStyleComments() - return (b:NERDLeft == '/*' && b:NERDRight == '*/') || (b:NERDLeftAlt == '/*' && b:NERDRightAlt == '*/') -endfunction - -" Function: s:IsCommentedNormOrSexy(lineNum) {{{2 -"This function is used to determine whether the given line is commented with -"either set of delimiters or if it is part of a sexy comment -" -" Args: -" -lineNum: the line number of the line to check -function s:IsCommentedNormOrSexy(lineNum) - let theLine = getline(a:lineNum) - - "if the line is commented normally return 1 - if s:IsCommented(b:NERDLeft, b:NERDRight, theLine) || s:IsCommented(b:NERDLeftAlt, b:NERDRightAlt, theLine) - return 1 - endif - - "if the line is part of a sexy comment return 1 - if s:IsInSexyComment(a:lineNum) - return 1 - endif - return 0 -endfunction - -" Function: s:IsCommented(left, right, line) {{{2 -"This function is used to determine whether the given line is commented with -"the given delimiters -" -" Args: -" -line: the line that to check if commented -" -left/right: the left and right delimiters to check for -function s:IsCommented(left, right, line) - "if the line isnt commented return true - if s:FindDelimiterIndex(a:left, a:line) != -1 && (s:FindDelimiterIndex(a:right, a:line) != -1 || !s:Multipart()) - return 1 - endif - return 0 -endfunction - -" Function: s:IsCommentedFromStartOfLine(left, line) {{{2 -"This function is used to determine whether the given line is commented with -"the given delimiters at the start of the line i.e the left delimiter is the -"first thing on the line (apart from spaces\tabs) -" -" Args: -" -line: the line that to check if commented -" -left: the left delimiter to check for -function s:IsCommentedFromStartOfLine(left, line) - let theLine = s:ConvertLeadingTabsToSpaces(a:line) - let numSpaces = strlen(substitute(theLine, '^\( *\).*$', '\1', '')) - let delimIndx = s:FindDelimiterIndex(a:left, theLine) - return delimIndx == numSpaces -endfunction - -" Function: s:IsCommentedOuttermost(left, right, leftAlt, rightAlt, line) {{{2 -" Finds the type of the outtermost delims on the line -" -" Args: -" -line: the line that to check if the outtermost comments on it are -" left/right -" -left/right: the left and right delimiters to check for -" -leftAlt/rightAlt: the left and right alternative delimiters to check for -" -" Returns: -" 0 if the line is not commented with either set of delims -" 1 if the line is commented with the left/right delim set -" 2 if the line is commented with the leftAlt/rightAlt delim set -function s:IsCommentedOuttermost(left, right, leftAlt, rightAlt, line) - "get the first positions of the left delims and the last positions of the - "right delims - let indxLeft = s:FindDelimiterIndex(a:left, a:line) - let indxLeftAlt = s:FindDelimiterIndex(a:leftAlt, a:line) - let indxRight = s:LastIndexOfDelim(a:right, a:line) - let indxRightAlt = s:LastIndexOfDelim(a:rightAlt, a:line) - - "check if the line has a left delim before a leftAlt delim - if (indxLeft <= indxLeftAlt || indxLeftAlt == -1) && indxLeft != -1 - "check if the line has a right delim after any rightAlt delim - if (indxRight > indxRightAlt && indxRight > indxLeft) || !s:Multipart() - return 1 - endif - - "check if the line has a leftAlt delim before a left delim - elseif (indxLeftAlt <= indxLeft || indxLeft == -1) && indxLeftAlt != -1 - "check if the line has a rightAlt delim after any right delim - if (indxRightAlt > indxRight && indxRightAlt > indxLeftAlt) || !s:AltMultipart() - return 2 - endif - else - return 0 - endif - - return 0 - -endfunction - - -" Function: s:IsDelimValid(delimiter, delIndx, line) {{{2 -" This function is responsible for determining whether a given instance of a -" comment delimiter is a real delimiter or not. For example, in java the -" // string is a comment delimiter but in the line: -" System.out.println("//"); -" it does not count as a comment delimiter. This function is responsible for -" distinguishing between such cases. It does so by applying a set of -" heuristics that are not fool proof but should work most of the time. -" -" Args: -" -delimiter: the delimiter we are validating -" -delIndx: the position of delimiter in line -" -line: the line that delimiter occurs in -" -" Returns: -" 0 if the given delimiter is not a real delimiter (as far as we can tell) , -" 1 otherwise -function s:IsDelimValid(delimiter, delIndx, line) - "get the delimiter without the escchars - let l:delimiter = a:delimiter - - "get the strings before and after the delimiter - let preComStr = strpart(a:line, 0, a:delIndx) - let postComStr = strpart(a:line, a:delIndx+strlen(delimiter)) - - "to check if the delimiter is real, make sure it isnt preceded by - "an odd number of quotes and followed by the same (which would indicate - "that it is part of a string and therefore is not a comment) - if !s:IsNumEven(s:CountNonESCedOccurances(preComStr, '"', "\\")) && !s:IsNumEven(s:CountNonESCedOccurances(postComStr, '"', "\\")) - return 0 - endif - if !s:IsNumEven(s:CountNonESCedOccurances(preComStr, "'", "\\")) && !s:IsNumEven(s:CountNonESCedOccurances(postComStr, "'", "\\")) - return 0 - endif - if !s:IsNumEven(s:CountNonESCedOccurances(preComStr, "`", "\\")) && !s:IsNumEven(s:CountNonESCedOccurances(postComStr, "`", "\\")) - return 0 - endif - - - "if the comment delimiter is escaped, assume it isnt a real delimiter - if s:IsEscaped(a:line, a:delIndx, "\\") - return 0 - endif - - "vim comments are so fuckin stupid!! Why the hell do they have comment - "delimiters that are used elsewhere in the syntax?!?! We need to check - "some conditions especially for vim - if &filetype == "vim" - if !s:IsNumEven(s:CountNonESCedOccurances(preComStr, '"', "\\")) - return 0 - endif - - "if the delimiter is on the very first char of the line or is the - "first non-tab/space char on the line then it is a valid comment delimiter - if a:delIndx == 0 || a:line =~ "^[ \t]\\{" . a:delIndx . "\\}\".*$" - return 1 - endif - - let numLeftParen =s:CountNonESCedOccurances(preComStr, "(", "\\") - let numRightParen =s:CountNonESCedOccurances(preComStr, ")", "\\") - - "if the quote is inside brackets then assume it isnt a comment - if numLeftParen > numRightParen - return 0 - endif - - "if the line has an even num of unescaped "'s then we can assume that - "any given " is not a comment delimiter - if s:IsNumEven(s:CountNonESCedOccurances(a:line, "\"", "\\")) - return 0 - endif - endif - - return 1 - -endfunction - -" Function: s:IsNumEven(num) {{{2 -" A small function the returns 1 if the input number is even and 0 otherwise -" Args: -" -num: the number to check -function s:IsNumEven(num) - return (a:num % 2) == 0 -endfunction - -" Function: s:IsEscaped(str, indx, escChar) {{{2 -" This function takes a string, an index into that string and an esc char and -" returns 1 if the char at the index is escaped (i.e if it is preceded by an -" odd number of esc chars) -" Args: -" -str: the string to check -" -indx: the index into str that we want to check -" -escChar: the escape char the char at indx may be ESCed with -function s:IsEscaped(str, indx, escChar) - "initialise numEscChars to 0 and look at the char before indx - let numEscChars = 0 - let curIndx = a:indx-1 - - "keep going back thru str until we either reach the start of the str or - "run out of esc chars - while curIndx >= 0 && strpart(a:str, curIndx, 1) == a:escChar - - "we have found another esc char so add one to the count and move left - "one char - let numEscChars = numEscChars + 1 - let curIndx = curIndx - 1 - - endwhile - - "if there is an odd num of esc chars directly before the char at indx then - "the char at indx is escaped - return !s:IsNumEven(numEscChars) -endfunction - -" Function: s:IsInSexyComment(line) {{{2 -" returns 1 if the given line number is part of a sexy comment -function s:IsInSexyComment(line) - return !empty(s:FindBoundingLinesOfSexyCom(a:line)) -endfunction - -" Function: s:IsSexyComment(topline, bottomline) {{{2 -" This function takes in 2 line numbers and returns 1 if the lines between and -" including the given line numbers are a sexy comment. It returns 0 otherwise. -" Args: -" -topline: the line that the possible sexy comment starts on -" -bottomline: the line that the possible sexy comment stops on -function s:IsSexyComment(topline, bottomline) - - "get the delim set that would be used for a sexy comment - let left = '' - let right = '' - if s:Multipart() - let left = b:NERDLeft - let right = b:NERDRight - elseif s:AltMultipart() - let left = b:NERDLeftAlt - let right = b:NERDRightAlt - else - return 0 - endif - - "swap the top and bottom line numbers around if need be - let topline = a:topline - let bottomline = a:bottomline - if bottomline < topline - topline = bottomline - bottomline = a:topline - endif - - "if there is < 2 lines in the comment it cannot be sexy - if (bottomline - topline) <= 0 - return 0 - endif - - "if the top line doesnt begin with a left delim then the comment isnt sexy - if getline(a:topline) !~ '^[ \t]*' . left - return 0 - endif - - "if there is a right delim on the top line then this isnt a sexy comment - if s:FindDelimiterIndex(right, getline(a:topline)) != -1 - return 0 - endif - - "if there is a left delim on the bottom line then this isnt a sexy comment - if s:FindDelimiterIndex(left, getline(a:bottomline)) != -1 - return 0 - endif - - "if the bottom line doesnt begin with a right delim then the comment isnt - "sexy - if getline(a:bottomline) !~ '^.*' . right . '$' - return 0 - endif - - let sexyComMarker = s:GetSexyComMarker(0, 1) - - "check each of the intermediate lines to make sure they start with a - "sexyComMarker - let currentLine = a:topline+1 - while currentLine < a:bottomline - let theLine = getline(currentLine) - - if theLine !~ '^[ \t]*' . sexyComMarker - return 0 - endif - - "if there is a right delim in an intermediate line then the block isnt - "a sexy comment - if s:FindDelimiterIndex(right, theLine) != -1 - return 0 - endif - - let currentLine = currentLine + 1 - endwhile - - "we have not found anything to suggest that this isnt a sexy comment so - return 1 - -endfunction - -" Function: s:LastIndexOfDelim(delim, str) {{{2 -" This function takes a string and a delimiter and returns the last index of -" that delimiter in string -" Args: -" -delim: the delimiter to look for -" -str: the string to look for delim in -function s:LastIndexOfDelim(delim, str) - let delim = a:delim - let lenDelim = strlen(delim) - - "set index to the first occurrence of delim. If there is no occurrence then - "bail - let indx = s:FindDelimiterIndex(delim, a:str) - if indx == -1 - return -1 - endif - - "keep moving to the next instance of delim in str till there is none left - while 1 - - "search for the next delim after the previous one - let searchStr = strpart(a:str, indx+lenDelim) - let indx2 = s:FindDelimiterIndex(delim, searchStr) - - "if we find a delim update indx to record the position of it, if we - "dont find another delim then indx is the last one so break out of - "this loop - if indx2 != -1 - let indx = indx + indx2 + lenDelim - else - break - endif - endwhile - - return indx - -endfunction - -" Function: s:LeftMostIndx(countCommentedLines, countEmptyLines, topline, bottomline) {{{2 -" This function takes in 2 line numbers and returns the index of the left most -" char (that is not a space or a tab) on all of these lines. -" Args: -" -countCommentedLines: 1 if lines that are commented are to be checked as -" well. 0 otherwise -" -countEmptyLines: 1 if empty lines are to be counted in the search -" -topline: the top line to be checked -" -bottomline: the bottom line to be checked -function s:LeftMostIndx(countCommentedLines, countEmptyLines, topline, bottomline) - - " declare the left most index as an extreme value - let leftMostIndx = 1000 - - " go thru the block line by line updating leftMostIndx - let currentLine = a:topline - while currentLine <= a:bottomline - - " get the next line and if it is allowed to be commented, or is not - " commented, check it - let theLine = getline(currentLine) - if a:countEmptyLines || theLine !~ '^[ \t]*$' - if a:countCommentedLines || (!s:IsCommented(b:NERDLeft, b:NERDRight, theLine) && !s:IsCommented(b:NERDLeftAlt, b:NERDRightAlt, theLine)) - " convert spaces to tabs and get the number of leading spaces for - " this line and update leftMostIndx if need be - let theLine = s:ConvertLeadingTabsToSpaces(theLine) - let leadSpaceOfLine = strlen( substitute(theLine, '\(^[ \t]*\).*$','\1','') ) - if leadSpaceOfLine < leftMostIndx - let leftMostIndx = leadSpaceOfLine - endif - endif - endif - - " move on to the next line - let currentLine = currentLine + 1 - endwhile - - if leftMostIndx == 1000 - return 0 - else - return leftMostIndx - endif -endfunction - -" Function: s:Multipart() {{{2 -" returns 1 if the current delims are multipart -function s:Multipart() - return b:NERDRight != '' -endfunction - -" Function: s:NerdEcho(msg, typeOfMsg) {{{2 -" Args: -" -msg: the message to echo -" -typeOfMsg: 0 = warning message -" 1 = normal message -function s:NerdEcho(msg, typeOfMsg) - if a:typeOfMsg == 0 - echohl WarningMsg - echo 'NERDCommenter:' . a:msg - echohl None - elseif a:typeOfMsg == 1 - echo 'NERDCommenter:' . a:msg - endif -endfunction - -" Function: s:NumberOfLeadingTabs(s) {{{2 -" returns the number of leading tabs in the given string -function s:NumberOfLeadingTabs(s) - return strlen(substitute(a:s, '^\(\t*\).*$', '\1', "")) -endfunction - -" Function: s:NumLinesInBuf() {{{2 -" Returns the number of lines in the current buffer -function s:NumLinesInBuf() - return line('$') -endfunction - -" Function: s:ReplaceDelims(toReplace1, toReplace2, replacor1, replacor2, str) {{{2 -" This function takes in a string, 2 delimiters in that string and 2 strings -" to replace these delimiters with. -" -" Args: -" -toReplace1: the first delimiter to replace -" -toReplace2: the second delimiter to replace -" -replacor1: the string to replace toReplace1 with -" -replacor2: the string to replace toReplace2 with -" -str: the string that the delimiters to be replaced are in -function s:ReplaceDelims(toReplace1, toReplace2, replacor1, replacor2, str) - let line = s:ReplaceLeftMostDelim(a:toReplace1, a:replacor1, a:str) - let line = s:ReplaceRightMostDelim(a:toReplace2, a:replacor2, line) - return line -endfunction - -" Function: s:ReplaceLeftMostDelim(toReplace, replacor, str) {{{2 -" This function takes a string and a delimiter and replaces the left most -" occurrence of this delimiter in the string with a given string -" -" Args: -" -toReplace: the delimiter in str that is to be replaced -" -replacor: the string to replace toReplace with -" -str: the string that contains toReplace -function s:ReplaceLeftMostDelim(toReplace, replacor, str) - let toReplace = a:toReplace - let replacor = a:replacor - "get the left most occurrence of toReplace - let indxToReplace = s:FindDelimiterIndex(toReplace, a:str) - - "if there IS an occurrence of toReplace in str then replace it and return - "the resulting string - if indxToReplace != -1 - let line = strpart(a:str, 0, indxToReplace) . replacor . strpart(a:str, indxToReplace+strlen(toReplace)) - return line - endif - - return a:str -endfunction - -" Function: s:ReplaceRightMostDelim(toReplace, replacor, str) {{{2 -" This function takes a string and a delimiter and replaces the right most -" occurrence of this delimiter in the string with a given string -" -" Args: -" -toReplace: the delimiter in str that is to be replaced -" -replacor: the string to replace toReplace with -" -str: the string that contains toReplace -" -function s:ReplaceRightMostDelim(toReplace, replacor, str) - let toReplace = a:toReplace - let replacor = a:replacor - let lenToReplace = strlen(toReplace) - - "get the index of the last delim in str - let indxToReplace = s:LastIndexOfDelim(toReplace, a:str) - - "if there IS a delimiter in str, replace it and return the result - let line = a:str - if indxToReplace != -1 - let line = strpart(a:str, 0, indxToReplace) . replacor . strpart(a:str, indxToReplace+strlen(toReplace)) - endif - return line -endfunction - -"FUNCTION: s:RestoreScreenState() {{{2 -" -"Sets the screen state back to what it was when s:SaveScreenState was last -"called. -" -function s:RestoreScreenState() - if !exists("t:NERDComOldTopLine") || !exists("t:NERDComOldPos") - throw 'NERDCommenter exception: cannot restore screen' - endif - - call cursor(t:NERDComOldTopLine, 0) - normal! zt - call setpos(".", t:NERDComOldPos) -endfunction - -" Function: s:RightMostIndx(countCommentedLines, countEmptyLines, topline, bottomline) {{{2 -" This function takes in 2 line numbers and returns the index of the right most -" char on all of these lines. -" Args: -" -countCommentedLines: 1 if lines that are commented are to be checked as -" well. 0 otherwise -" -countEmptyLines: 1 if empty lines are to be counted in the search -" -topline: the top line to be checked -" -bottomline: the bottom line to be checked -function s:RightMostIndx(countCommentedLines, countEmptyLines, topline, bottomline) - let rightMostIndx = -1 - - " go thru the block line by line updating rightMostIndx - let currentLine = a:topline - while currentLine <= a:bottomline - - " get the next line and see if it is commentable, otherwise it doesnt - " count - let theLine = getline(currentLine) - if a:countEmptyLines || theLine !~ '^[ \t]*$' - - if a:countCommentedLines || (!s:IsCommented(b:NERDLeft, b:NERDRight, theLine) && !s:IsCommented(b:NERDLeftAlt, b:NERDRightAlt, theLine)) - - " update rightMostIndx if need be - let theLine = s:ConvertLeadingTabsToSpaces(theLine) - let lineLen = strlen(theLine) - if lineLen > rightMostIndx - let rightMostIndx = lineLen - endif - endif - endif - - " move on to the next line - let currentLine = currentLine + 1 - endwhile - - return rightMostIndx -endfunction - -"FUNCTION: s:SaveScreenState() {{{2 -"Saves the current cursor position in the current buffer and the window -"scroll position -function s:SaveScreenState() - let t:NERDComOldPos = getpos(".") - let t:NERDComOldTopLine = line("w0") -endfunction - -" Function: s:SwapOutterMultiPartDelimsForPlaceHolders(line) {{{2 -" This function takes a line and swaps the outter most multi-part delims for -" place holders -" Args: -" -line: the line to swap the delims in -" -function s:SwapOutterMultiPartDelimsForPlaceHolders(line) - " find out if the line is commented using normal delims and/or - " alternate ones - let isCommented = s:IsCommented(b:NERDLeft, b:NERDRight, a:line) - let isCommentedAlt = s:IsCommented(b:NERDLeftAlt, b:NERDRightAlt, a:line) - - let line2 = a:line - - "if the line is commented and there is a right delimiter, replace - "the delims with place-holders - if isCommented && s:Multipart() - let line2 = s:ReplaceDelims(b:NERDLeft, b:NERDRight, g:NERDLPlace, g:NERDRPlace, a:line) - - "similarly if the line is commented with the alternative - "delimiters - elseif isCommentedAlt && s:AltMultipart() - let line2 = s:ReplaceDelims(b:NERDLeftAlt, b:NERDRightAlt, g:NERDLPlace, g:NERDRPlace, a:line) - endif - - return line2 -endfunction - -" Function: s:SwapOutterPlaceHoldersForMultiPartDelims(line) {{{2 -" This function takes a line and swaps the outtermost place holders for -" multi-part delims -" Args: -" -line: the line to swap the delims in -" -function s:SwapOutterPlaceHoldersForMultiPartDelims(line) - let left = '' - let right = '' - if s:Multipart() - let left = b:NERDLeft - let right = b:NERDRight - elseif s:AltMultipart() - let left = b:NERDLeftAlt - let right = b:NERDRightAlt - endif - - let line = s:ReplaceDelims(g:NERDLPlace, g:NERDRPlace, left, right, a:line) - return line -endfunction -" Function: s:TabbedCol(line, col) {{{2 -" Gets the col number for given line and existing col number. The new col -" number is the col number when all leading spaces are converted to tabs -" Args: -" -line:the line to get the rel col for -" -col: the abs col -function s:TabbedCol(line, col) - let lineTruncated = strpart(a:line, 0, a:col) - let lineSpacesToTabs = substitute(lineTruncated, s:TabSpace(), '\t', 'g') - return strlen(lineSpacesToTabs) -endfunction -"FUNCTION: s:TabSpace() {{{2 -"returns a string of spaces equal in length to &tabstop -function s:TabSpace() - let tabSpace = "" - let spacesPerTab = &tabstop - while spacesPerTab > 0 - let tabSpace = tabSpace . " " - let spacesPerTab = spacesPerTab - 1 - endwhile - return tabSpace -endfunction - -" Function: s:UnEsc(str, escChar) {{{2 -" This function removes all the escape chars from a string -" Args: -" -str: the string to remove esc chars from -" -escChar: the escape char to be removed -function s:UnEsc(str, escChar) - return substitute(a:str, a:escChar, "", "g") -endfunction - -" Function: s:UntabbedCol(line, col) {{{2 -" Takes a line and a col and returns the absolute column of col taking into -" account that a tab is worth 3 or 4 (or whatever) spaces. -" Args: -" -line:the line to get the abs col for -" -col: the col that doesnt take into account tabs -function s:UntabbedCol(line, col) - let lineTruncated = strpart(a:line, 0, a:col) - let lineTabsToSpaces = substitute(lineTruncated, '\t', s:TabSpace(), 'g') - return strlen(lineTabsToSpaces) -endfunction -" Section: Comment mapping setup {{{1 -" =========================================================================== - -" switch to/from alternative delimiters -nnoremap NERDCommenterAltDelims :call SwitchToAlternativeDelimiters(1) - -" comment out lines -nnoremap NERDCommenterComment :call NERDComment(0, "norm") -vnoremap NERDCommenterComment :call NERDComment(1, "norm") - -" toggle comments -nnoremap NERDCommenterToggle :call NERDComment(0, "toggle") -vnoremap NERDCommenterToggle :call NERDComment(1, "toggle") - -" minimal comments -nnoremap NERDCommenterMinimal :call NERDComment(0, "minimal") -vnoremap NERDCommenterMinimal :call NERDComment(1, "minimal") - -" sexy comments -nnoremap NERDCommenterSexy :call NERDComment(0, "sexy") -vnoremap NERDCommenterSexy :call NERDComment(1, "sexy") - -" invert comments -nnoremap NERDCommenterInvert :call NERDComment(0, "invert") -vnoremap NERDCommenterInvert :call NERDComment(1, "invert") - -" yank then comment -nmap NERDCommenterYank :call NERDComment(0, "yank") -vmap NERDCommenterYank :call NERDComment(1, "yank") - -" left aligned comments -nnoremap NERDCommenterAlignLeft :call NERDComment(0, "alignLeft") -vnoremap NERDCommenterAlignLeft :call NERDComment(1, "alignLeft") - -" left and right aligned comments -nnoremap NERDCommenterAlignBoth :call NERDComment(0, "alignBoth") -vnoremap NERDCommenterAlignBoth :call NERDComment(1, "alignBoth") - -" nested comments -nnoremap NERDCommenterNest :call NERDComment(0, "nested") -vnoremap NERDCommenterNest :call NERDComment(1, "nested") - -" uncomment -nnoremap NERDCommenterUncomment :call NERDComment(0, "uncomment") -vnoremap NERDCommenterUncomment :call NERDComment(1, "uncomment") - -" comment till the end of the line -nnoremap NERDCommenterToEOL :call NERDComment(0, "toEOL") - -" append comments -nmap NERDCommenterAppend :call NERDComment(0, "append") - -" insert comments -inoremap NERDCommenterInInsert :call NERDComment(0, "insert") - - -function! s:CreateMaps(target, combo) - if !hasmapto(a:target, 'n') - exec 'nmap ' . a:combo . ' ' . a:target - endif - - if !hasmapto(a:target, 'v') - exec 'vmap ' . a:combo . ' ' . a:target - endif -endfunction - -if g:NERDCreateDefaultMappings - call s:CreateMaps('NERDCommenterComment', ',cc') - call s:CreateMaps('NERDCommenterToggle', ',c') - call s:CreateMaps('NERDCommenterMinimal', ',cm') - call s:CreateMaps('NERDCommenterSexy', ',cs') - call s:CreateMaps('NERDCommenterInvert', ',ci') - call s:CreateMaps('NERDCommenterYank', ',cy') - call s:CreateMaps('NERDCommenterAlignLeft', ',cl') - call s:CreateMaps('NERDCommenterAlignBoth', ',cb') - call s:CreateMaps('NERDCommenterNest', ',cn') - call s:CreateMaps('NERDCommenterUncomment', ',cu') - call s:CreateMaps('NERDCommenterToEOL', ',c$') - call s:CreateMaps('NERDCommenterAppend', ',cA') - - if !hasmapto('NERDCommenterAltDelims', 'n') - nmap ,ca NERDCommenterAltDelims - endif -endif - - - -" Section: Menu item setup {{{1 -" =========================================================================== -"check if the user wants the menu to be displayed -if g:NERDMenuMode != 0 - - let menuRoot = "" - if g:NERDMenuMode == 1 - let menuRoot = 'comment' - elseif g:NERDMenuMode == 2 - let menuRoot = '&comment' - elseif g:NERDMenuMode == 3 - let menuRoot = '&Plugin.&comment' - endif - - function! s:CreateMenuItems(target, desc, root) - exec 'nmenu ' . a:root . '.' . a:desc . ' ' . a:target - exec 'vmenu ' . a:root . '.' . a:desc . ' ' . a:target - endfunction - call s:CreateMenuItems("NERDCommenterComment", 'Comment', menuRoot) - call s:CreateMenuItems("NERDCommenterToggle", 'Toggle', menuRoot) - call s:CreateMenuItems('NERDCommenterMinimal', 'Minimal', menuRoot) - call s:CreateMenuItems('NERDCommenterNest', 'Nested', menuRoot) - exec 'nmenu '. menuRoot .'.To\ EOL NERDCommenterToEOL' - call s:CreateMenuItems('NERDCommenterInvert', 'Invert', menuRoot) - call s:CreateMenuItems('NERDCommenterSexy', 'Sexy', menuRoot) - call s:CreateMenuItems('NERDCommenterYank', 'Yank\ then\ comment', menuRoot) - exec 'nmenu '. menuRoot .'.Append NERDCommenterAppend' - exec 'menu '. menuRoot .'.-Sep- :' - call s:CreateMenuItems('NERDCommenterAlignLeft', 'Left\ aligned', menuRoot) - call s:CreateMenuItems('NERDCommenterAlignBoth', 'Left\ and\ right\ aligned', menuRoot) - exec 'menu '. menuRoot .'.-Sep2- :' - call s:CreateMenuItems('NERDCommenterUncomment', 'Uncomment', menuRoot) - exec 'nmenu '. menuRoot .'.Switch\ Delimiters NERDCommenterAltDelims' - exec 'imenu '. menuRoot .'.Insert\ Comment\ Here NERDCommenterInInsert' - exec 'menu '. menuRoot .'.-Sep3- :' - exec 'menu '. menuRoot .'.Help :help NERDCommenterContents' -endif -" vim: set foldmethod=marker : diff --git a/vim/plugin/conque_term.vim b/vim/plugin/conque_term.vim deleted file mode 100644 index 963f640..0000000 --- a/vim/plugin/conque_term.vim +++ /dev/null @@ -1,216 +0,0 @@ -" FILE: plugin/conque_term.vim {{{ -" AUTHOR: Nico Raffo -" WEBSITE: http://conque.googlecode.com -" MODIFIED: 2011-09-02 -" VERSION: 2.3, for Vim 7.0 -" LICENSE: -" Conque - Vim terminal/console emulator -" Copyright (C) 2009-2011 Nico Raffo -" -" MIT License -" -" Permission is hereby granted, free of charge, to any person obtaining a copy -" of this software and associated documentation files (the "Software"), to deal -" in the Software without restriction, including without limitation the rights -" to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -" copies of the Software, and to permit persons to whom the Software is -" furnished to do so, subject to the following conditions: -" -" The above copyright notice and this permission notice shall be included in -" all copies or substantial portions of the Software. -" -" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -" OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -" THE SOFTWARE. -" }}} - -" See docs/conque_term.txt for help or type :help ConqueTerm - -if exists('g:ConqueTerm_Loaded') || v:version < 700 - finish -endif - -" ********************************************************************************************************** -" **** DEFAULT CONFIGURATION ******************************************************************************* -" ********************************************************************************************************** - -" DO NOT EDIT CONFIGURATION SETTINGS IN THIS FILE! -" Define these variables in your local .vimrc to over-ride the default values - -" {{{ - -" Fast mode {{{ -" Disables all features which could cause Conque to run slowly, including: -" * Disables terminal colors -" * Disables some multi-byte character handling -if !exists('g:ConqueTerm_FastMode') - let g:ConqueTerm_FastMode = 0 -endif " }}} - -" automatically go into insert mode when entering buffer {{{ -if !exists('g:ConqueTerm_InsertOnEnter') - let g:ConqueTerm_InsertOnEnter = 0 -endif " }}} - -" Allow user to use keys to switch window in insert mode. {{{ -if !exists('g:ConqueTerm_CWInsert') - let g:ConqueTerm_CWInsert = 0 -endif " }}} - -" Choose key mapping to leave insert mode {{{ -" If you choose something other than '', then will be sent to terminal -" Using a different key will usually fix Alt/Meta key issues -if !exists('g:ConqueTerm_EscKey') - let g:ConqueTerm_EscKey = '' -endif " }}} - -" Use this key to execute the current file in a split window. {{{ -" THIS IS A GLOBAL KEY MAPPING -if !exists('g:ConqueTerm_ExecFileKey') - let g:ConqueTerm_ExecFileKey = '' -endif " }}} - -" Use this key to send the current file contents to conque. {{{ -" THIS IS A GLOBAL KEY MAPPING -if !exists('g:ConqueTerm_SendFileKey') - let g:ConqueTerm_SendFileKey = '' -endif " }}} - -" Use this key to send selected text to conque. {{{ -" THIS IS A GLOBAL KEY MAPPING -if !exists('g:ConqueTerm_SendVisKey') - let g:ConqueTerm_SendVisKey = '' -endif " }}} - -" Use this key to toggle terminal key mappings. {{{ -" Only mapped inside of Conque buffers. -if !exists('g:ConqueTerm_ToggleKey') - let g:ConqueTerm_ToggleKey = '' -endif " }}} - -" Enable color. {{{ -" If your apps use a lot of color it will slow down the shell. -" 0 - no terminal colors. You still will see Vim syntax highlighting. -" 1 - limited terminal colors (recommended). Past terminal color history cleared regularly. -" 2 - all terminal colors. Terminal color history never cleared. -if !exists('g:ConqueTerm_Color') - let g:ConqueTerm_Color = 1 -endif " }}} - -" Color mode. Windows ONLY {{{ -" Set this variable to 'conceal' to use Vim's conceal mode for terminal colors. -" This makes colors render much faster, but has some odd baggage. -if !exists('g:ConqueTerm_ColorMode') - let g:ConqueTerm_ColorMode = '' -endif " }}} - -" TERM environment setting {{{ -if !exists('g:ConqueTerm_TERM') - let g:ConqueTerm_TERM = 'vt100' -endif " }}} - -" Syntax for your buffer {{{ -if !exists('g:ConqueTerm_Syntax') - let g:ConqueTerm_Syntax = 'conque_term' -endif " }}} - -" Keep on updating the shell window after you've switched to another buffer {{{ -if !exists('g:ConqueTerm_ReadUnfocused') - let g:ConqueTerm_ReadUnfocused = 0 -endif " }}} - -" Use this regular expression to highlight prompt {{{ -if !exists('g:ConqueTerm_PromptRegex') - let g:ConqueTerm_PromptRegex = '^\w\+@[0-9A-Za-z_.-]\+:[0-9A-Za-z_./\~,:-]\+\$' -endif " }}} - -" Choose which Python version to attempt to load first {{{ -" Valid values are 2, 3 or 0 (no preference) -if !exists('g:ConqueTerm_PyVersion') - let g:ConqueTerm_PyVersion = 2 -endif " }}} - -" Path to python.exe. (Windows only) {{{ -" By default, Conque will check C:\PythonNN\python.exe then will search system path -" If you have installed Python in an unusual location and it's not in your path, fill in the full path below -" E.g. 'C:\Program Files\Python\Python27\python.exe' -if !exists('g:ConqueTerm_PyExe') - let g:ConqueTerm_PyExe = '' -endif " }}} - -" Automatically close buffer when program exits {{{ -if !exists('g:ConqueTerm_CloseOnEnd') - let g:ConqueTerm_CloseOnEnd = 0 -endif " }}} - -" Send function key presses to terminal {{{ -if !exists('g:ConqueTerm_SendFunctionKeys') - let g:ConqueTerm_SendFunctionKeys = 0 -endif " }}} - -" Session support {{{ -if !exists('g:ConqueTerm_SessionSupport') - let g:ConqueTerm_SessionSupport = 0 -endif " }}} - -" hide Conque startup messages {{{ -" messages should only appear the first 3 times you start Vim with a new version of Conque -" and include important Conque feature and option descriptions -" TODO - disabled and unused for now -if !exists('g:ConqueTerm_StartMessages') - let g:ConqueTerm_StartMessages = 1 -endif " }}} - -" Windows character code page {{{ -" Leave at 0 to use current environment code page. -" Use 65001 for utf-8, although many console apps do not support it. -if !exists('g:ConqueTerm_CodePage') - let g:ConqueTerm_CodePage = 0 -endif " }}} - -" InsertCharPre support {{{ -" Disable this feature by default, still in Beta -if !exists('g:ConqueTerm_InsertCharPre') - let g:ConqueTerm_InsertCharPre = 0 -endif " }}} - -" }}} - -" ********************************************************************************************************** -" **** Startup ********************************************************************************************* -" ********************************************************************************************************** - -" Startup {{{ - -let g:ConqueTerm_Loaded = 1 -let g:ConqueTerm_Idx = 0 -let g:ConqueTerm_Version = 230 - -command! -nargs=+ -complete=shellcmd ConqueTerm call conque_term#open() -command! -nargs=+ -complete=shellcmd ConqueTermSplit call conque_term#open(, ['belowright split']) -command! -nargs=+ -complete=shellcmd ConqueTermVSplit call conque_term#open(, ['belowright vsplit']) -command! -nargs=+ -complete=shellcmd ConqueTermTab call conque_term#open(, ['tabnew']) - -" }}} - -" ********************************************************************************************************** -" **** Global Mappings & Autocommands ********************************************************************** -" ********************************************************************************************************** - -" Startup {{{ - -if exists('g:ConqueTerm_SessionSupport') && g:ConqueTerm_SessionSupport == 1 - autocmd SessionLoadPost * call conque_term#resume_session() -endif - -if maparg(g:ConqueTerm_ExecFileKey, 'n') == '' - exe 'nnoremap ' . g:ConqueTerm_ExecFileKey . ' :call conque_term#exec_file()' -endif - -" }}} - -" vim:foldmethod=marker