1 " FILE: plugin/conque_term.vim {{{
3 " AUTHOR: Nico Raffo <nicoraffo@gmail.com>
5 " VERSION: 1.1, for Vim 7.0
7 " Conque - pty interaction in Vim
8 " Copyright (C) 2009-2010 Nico Raffo
12 " Permission is hereby granted, free of charge, to any person obtaining a copy
13 " of this software and associated documentation files (the "Software"), to deal
14 " in the Software without restriction, including without limitation the rights
15 " to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 " copies of the Software, and to permit persons to whom the Software is
17 " furnished to do so, subject to the following conditions:
19 " The above copyright notice and this permission notice shall be included in
20 " all copies or substantial portions of the Software.
22 " THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 " IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 " FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 " AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 " LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 " OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 " **********************************************************************************************************
33 " **** VIM FUNCTIONS ***************************************************************************************
34 " **********************************************************************************************************
37 function! conque_term#open(...) "{{{
38 let command = get(a:000, 0, '')
39 let hooks = get(a:000, 1, [])
41 " bare minimum validation
43 echohl WarningMsg | echomsg "Conque requires the Python interface to be installed" | echohl None
47 echohl WarningMsg | echomsg "No command found" | echohl None
50 let l:cargs = split(command, '\s')
51 if !executable(l:cargs[0])
52 echohl WarningMsg | echomsg "Not an executable: " . l:cargs[0] | echohl None
57 " set buffer window options
58 let g:ConqueTerm_BufName = substitute(command, ' ', '\\ ', 'g') . "\\ -\\ " . g:ConqueTerm_Idx
59 call conque_term#set_buffer_settings(command, hooks)
60 let b:ConqueTerm_Var = 'ConqueTerm_' . g:ConqueTerm_Idx
61 let g:ConqueTerm_Var = 'ConqueTerm_' . g:ConqueTerm_Idx
62 let g:ConqueTerm_Idx += 1
66 let l:config = '{"color":' . string(g:ConqueTerm_Color) . ',"TERM":"' . g:ConqueTerm_TERM . '"}'
67 execute 'python ' . b:ConqueTerm_Var . ' = Conque()'
68 execute "python " . b:ConqueTerm_Var . ".open('" . conque_term#python_escape(command) . "', " . l:config . ")"
70 echohl WarningMsg | echomsg "Unable to open command: " . command | echohl None
74 " set buffer mappings and auto commands
75 call conque_term#set_mappings('start')
82 function! conque_term#set_buffer_settings(command, pre_hooks) "{{{
84 " optional hooks to execute, e.g. 'split'
88 sil exe "edit " . g:ConqueTerm_BufName
91 setlocal nocompatible " conque won't work in compatible mode
92 setlocal nopaste " conque won't work in paste mode
93 setlocal buftype=nofile " this buffer is not a file, you can't save it
94 setlocal nonumber " hide line numbers
95 setlocal foldcolumn=0 " reasonable left margin
96 setlocal nowrap " default to no wrap (esp with MySQL)
97 setlocal noswapfile " don't bother creating a .swp file
98 setlocal updatetime=50 " trigger cursorhold event after 50ms / XXX - global
99 setlocal scrolloff=0 " don't use buffer lines. it makes the 'clear' command not work as expected
100 setlocal sidescrolloff=0 " don't use buffer lines. it makes the 'clear' command not work as expected
101 setlocal sidescroll=1 " don't use buffer lines. it makes the 'clear' command not work as expected
102 setlocal foldmethod=manual " don't fold on {{{}}} and stuff
103 setlocal bufhidden=hide " when buffer is no longer displayed, don't wipe it out
104 setfiletype conque_term " useful
105 sil exe "setlocal syntax=" . g:ConqueTerm_Syntax
109 " set key mappings and auto commands
110 function! conque_term#set_mappings(action) "{{{
113 if a:action == 'toggle'
114 if exists('b:conque_on') && b:conque_on == 1
115 let l:action = 'stop'
116 echohl WarningMsg | echomsg "Terminal is paused" | echohl None
118 let l:action = 'start'
119 echohl WarningMsg | echomsg "Terminal is resumed" | echohl None
122 let l:action = a:action
125 " if mappings are being removed, add 'un'
126 let map_modifier = 'nore'
127 if l:action == 'stop'
128 let map_modifier = 'un'
131 " remove all auto commands
132 if l:action == 'stop'
133 execute 'autocmd! ' . b:ConqueTerm_Var
136 execute 'augroup ' . b:ConqueTerm_Var
138 " handle unexpected closing of shell, passes HUP to parent and all child processes
139 execute 'autocmd ' . b:ConqueTerm_Var . ' BufUnload <buffer> python ' . b:ConqueTerm_Var . '.proc.signal(1)'
141 " check for resized/scrolled buffer when entering buffer
142 execute 'autocmd ' . b:ConqueTerm_Var . ' BufEnter <buffer> python ' . b:ConqueTerm_Var . '.update_window_size()'
143 execute 'autocmd ' . b:ConqueTerm_Var . ' VimResized python ' . b:ConqueTerm_Var . '.update_window_size()'
145 " set/reset updatetime on entering/exiting buffer
146 autocmd BufEnter <buffer> set updatetime=50
147 autocmd BufLeave <buffer> set updatetime=2000
149 " check for resized/scrolled buffer when entering insert mode
150 " XXX - messed up since we enter insert mode at each updatetime
151 "execute 'autocmd InsertEnter <buffer> python ' . b:ConqueTerm_Var . '.screen.align()'
153 " read more output when this isn't the current buffer
154 if g:ConqueTerm_ReadUnfocused == 1
155 execute 'autocmd ' . b:ConqueTerm_Var . ' CursorHold * call conque_term#read_all()'
158 " poll for more output
159 sil execute 'autocmd ' . b:ConqueTerm_Var . ' CursorHoldI <buffer> python ' . b:ConqueTerm_Var . '.auto_read()'
162 " use F22 key to get more input
163 if l:action == 'start'
164 sil exe 'i' . map_modifier . 'map <silent> <buffer> <expr> <F22> "\<left>\<right>"'
165 sil exe 'i' . map_modifier . 'map <silent> <buffer> <expr> <F23> "\<right>\<left>"'
167 sil exe 'i' . map_modifier . 'map <silent> <buffer> <expr> <F22>'
168 sil exe 'i' . map_modifier . 'map <silent> <buffer> <expr> <F23>'
172 for c in range(1, 31)
177 if l:action == 'start'
178 sil exe 'i' . map_modifier . 'map <silent> <buffer> <C-' . nr2char(64 + c) . '> <C-o>:python ' . b:ConqueTerm_Var . '.write(chr(' . c . '))<CR>'
180 sil exe 'i' . map_modifier . 'map <silent> <buffer> <C-' . nr2char(64 + c) . '>'
183 if l:action == 'start'
184 sil exe 'n' . map_modifier . 'map <silent> <buffer> <C-c> <C-o>:python ' . b:ConqueTerm_Var . '.write(chr(3))<CR>'
186 sil exe 'n' . map_modifier . 'map <silent> <buffer> <C-c>'
190 if !exists('g:ConqueTerm_EscKey') || g:ConqueTerm_EscKey == '<Esc>'
191 " use <Esc><Esc> to send <Esc> to terminal
192 if l:action == 'start'
193 sil exe 'i' . map_modifier . 'map <silent> <buffer> <Esc><Esc> <C-o>:python ' . b:ConqueTerm_Var . '.write(chr(27))<CR>'
195 sil exe 'i' . map_modifier . 'map <silent> <buffer> <Esc><Esc>'
198 " use <Esc> to send <Esc> to terminal
199 if l:action == 'start'
200 sil exe 'i' . map_modifier . 'map <silent> <buffer> ' . g:ConqueTerm_EscKey . ' <Esc>'
201 sil exe 'i' . map_modifier . 'map <silent> <buffer> <Esc> <C-o>:python ' . b:ConqueTerm_Var . '.write(chr(27))<CR>'
203 sil exe 'i' . map_modifier . 'map <silent> <buffer> ' . g:ConqueTerm_EscKey
204 sil exe 'i' . map_modifier . 'map <silent> <buffer> <Esc>'
208 " Map <C-w> in insert mode
209 if exists('g:ConqueTerm_CWInsert') && g:ConqueTerm_CWInsert == 1
210 inoremap <silent> <buffer> <C-w>j <Esc><C-w>j
211 inoremap <silent> <buffer> <C-w>k <Esc><C-w>k
212 inoremap <silent> <buffer> <C-w>h <Esc><C-w>h
213 inoremap <silent> <buffer> <C-w>l <Esc><C-w>l
214 inoremap <silent> <buffer> <C-w>w <Esc><C-w>w
218 for i in range(33, 127)
221 if l:action == 'start'
222 sil exe "i" . map_modifier . "map <silent> <buffer> <Bar> <C-o>:python " . b:ConqueTerm_Var . ".write(chr(124))<CR>"
224 sil exe "i" . map_modifier . "map <silent> <buffer> <Bar>"
228 if l:action == 'start'
229 sil exe "i" . map_modifier . "map <silent> <buffer> " . nr2char(i) . " <C-o>:python " . b:ConqueTerm_Var . ".write(chr(" . i . "))<CR>"
231 sil exe "i" . map_modifier . "map <silent> <buffer> " . nr2char(i)
236 for i in range(128, 255)
237 if l:action == 'start'
238 sil exe "i" . map_modifier . "map <silent> <buffer> " . nr2char(i) . " <C-o>:python " . b:ConqueTerm_Var . ".write('" . nr2char(i) . "')<CR>"
240 sil exe "i" . map_modifier . "map <silent> <buffer> " . nr2char(i)
245 if l:action == 'start'
246 sil exe 'i' . map_modifier . 'map <silent> <buffer> <BS> <C-o>:python ' . b:ConqueTerm_Var . '.write(u"\u0008")<CR>'
247 sil exe 'i' . map_modifier . 'map <silent> <buffer> <Space> <C-o>:python ' . b:ConqueTerm_Var . '.write(" ")<CR>'
248 sil exe 'i' . map_modifier . 'map <silent> <buffer> <Up> <C-o>:python ' . b:ConqueTerm_Var . '.write(u"\u001b[A")<CR>'
249 sil exe 'i' . map_modifier . 'map <silent> <buffer> <Down> <C-o>:python ' . b:ConqueTerm_Var . '.write(u"\u001b[B")<CR>'
250 sil exe 'i' . map_modifier . 'map <silent> <buffer> <Right> <C-o>:python ' . b:ConqueTerm_Var . '.write(u"\u001b[C")<CR>'
251 sil exe 'i' . map_modifier . 'map <silent> <buffer> <Left> <C-o>:python ' . b:ConqueTerm_Var . '.write(u"\u001b[D")<CR>'
253 sil exe 'i' . map_modifier . 'map <silent> <buffer> <BS>'
254 sil exe 'i' . map_modifier . 'map <silent> <buffer> <Space>'
255 sil exe 'i' . map_modifier . 'map <silent> <buffer> <Up>'
256 sil exe 'i' . map_modifier . 'map <silent> <buffer> <Down>'
257 sil exe 'i' . map_modifier . 'map <silent> <buffer> <Right>'
258 sil exe 'i' . map_modifier . 'map <silent> <buffer> <Left>'
261 " send selected text into conque
262 if l:action == 'start'
263 sil exe 'v' . map_modifier . 'map <silent> <F9> :<C-u>call conque_term#send_selected(visualmode())<CR>'
265 sil exe 'v' . map_modifier . 'map <silent> <F9>'
269 if l:action == 'start'
270 sil exe 'n' . map_modifier . 'map <silent> <buffer> p :python ' . b:ConqueTerm_Var . '.write(vim.eval("@@"))<CR>a'
271 sil exe 'n' . map_modifier . 'map <silent> <buffer> P :python ' . b:ConqueTerm_Var . '.write(vim.eval("@@"))<CR>a'
272 sil exe 'n' . map_modifier . 'map <silent> <buffer> ]p :python ' . b:ConqueTerm_Var . '.write(vim.eval("@@"))<CR>a'
273 sil exe 'n' . map_modifier . 'map <silent> <buffer> [p :python ' . b:ConqueTerm_Var . '.write(vim.eval("@@"))<CR>a'
275 sil exe 'n' . map_modifier . 'map <silent> <buffer> p'
276 sil exe 'n' . map_modifier . 'map <silent> <buffer> P'
277 sil exe 'n' . map_modifier . 'map <silent> <buffer> ]p'
278 sil exe 'n' . map_modifier . 'map <silent> <buffer> [p'
280 if has('gui_running')
281 if l:action == 'start'
282 sil exe 'i' . map_modifier . 'map <buffer> <S-Insert> <Esc>:<C-u>python ' . b:ConqueTerm_Var . ".write(vim.eval('@+'))<CR>a"
284 sil exe 'i' . map_modifier . 'map <buffer> <S-Insert>'
288 " disable other normal mode keys which insert text
289 if l:action == 'start'
290 sil exe 'n' . map_modifier . 'map <silent> <buffer> r :echo "Replace mode disabled in shell."<CR>'
291 sil exe 'n' . map_modifier . 'map <silent> <buffer> R :echo "Replace mode disabled in shell."<CR>'
292 sil exe 'n' . map_modifier . 'map <silent> <buffer> c :echo "Change mode disabled in shell."<CR>'
293 sil exe 'n' . map_modifier . 'map <silent> <buffer> C :echo "Change mode disabled in shell."<CR>'
294 sil exe 'n' . map_modifier . 'map <silent> <buffer> s :echo "Change mode disabled in shell."<CR>'
295 sil exe 'n' . map_modifier . 'map <silent> <buffer> S :echo "Change mode disabled in shell."<CR>'
297 sil exe 'n' . map_modifier . 'map <silent> <buffer> r'
298 sil exe 'n' . map_modifier . 'map <silent> <buffer> R'
299 sil exe 'n' . map_modifier . 'map <silent> <buffer> c'
300 sil exe 'n' . map_modifier . 'map <silent> <buffer> C'
301 sil exe 'n' . map_modifier . 'map <silent> <buffer> s'
302 sil exe 'n' . map_modifier . 'map <silent> <buffer> S'
305 " set conque as on or off
306 if l:action == 'start'
312 " map command to start stop the shell
313 if a:action == 'start'
314 nnoremap <F5> :<C-u>call conque_term#set_mappings('toggle')<CR>
320 " send selected text from another buffer
321 function! conque_term#send_selected(type) "{{{
324 " save user's sb settings
325 let sb_save = &switchbuf
328 " yank current selection
329 sil exe "normal! `<" . a:type . "`>y"
332 let @@ = substitute(@@, '^[\r\n]*', '', '')
333 let @@ = substitute(@@, '[\r\n]*$', '', '')
335 " execute yanked text
336 sil exe ":sb " . g:ConqueTerm_BufName
337 sil exe 'python ' . g:ConqueTerm_Var . '.paste_selection()'
339 " reset original values
341 sil exe 'set switchbuf=' . sb_save
348 " read from all known conque buffers
349 function! conque_term#read_all() "{{{
350 " don't run this if we're in a conque buffer
351 if exists('b:ConqueTerm_Var')
356 for i in range(1, g:ConqueTerm_Idx - 1)
357 execute 'python ConqueTerm_' . string(i) . '.read(1)'
360 " probably a deleted buffer
367 " util function to add enough \s to pass a string to python
368 function! conque_term#python_escape(input) "{{{
369 let l:cleaned = a:input
370 let l:cleaned = substitute(l:cleaned, '\\', '\\\\', 'g')
371 let l:cleaned = substitute(l:cleaned, '\n', '\\n', 'g')
372 let l:cleaned = substitute(l:cleaned, '\r', '\\r', 'g')
373 let l:cleaned = substitute(l:cleaned, "'", "\\\\'", 'g')
377 " **********************************************************************************************************
378 " **** PYTHON **********************************************************************************************
379 " **********************************************************************************************************
385 import vim, re, time, math
387 # CONFIG CONSTANTS {{{
394 13:'cr' # carriage return
396 # 11 : 'vt', # vertical tab
397 # 12 : 'ff', # form feed
398 # 14 : 'so', # shift out
399 # 15 : 'si' # shift in
411 'G':'cursor_to_column',
420 # 'L':'insert_lines',
421 # 'M':'delete_lines',
424 # Alternate escape sequences, no [
425 CONQUE_ESCAPE_PLAIN = {
431 # 'N':'single_shift_2',
432 # 'O':'single_shift_3',
433 # '=':'alternate_keypad',
434 # '>':'numeric_keypad',
436 # '8':'restore_cursor',
438 # Uber alternate escape sequences, with # or ?
439 CONQUE_ESCAPE_QUESTION = {
440 '1h':'new_line_mode',
442 '4h':'smooth_scrolling',
443 '5h':'reverse_video',
444 '6h':'relative_origin',
445 '7h':'set_auto_wrap',
446 '8h':'set_auto_repeat',
447 '9h':'set_interlacing_mode',
448 '1l':'set_cursor_key',
451 '4l':'set_jump_scrolling',
453 '6l':'absolute_origin',
454 '7l':'reset_auto_wrap',
455 '8l':'reset_auto_repeat',
456 '9l':'reset_interlacing_mode'
459 CONQUE_ESCAPE_HASH = {
460 '8':'screen_alignment_test'
462 # '3':'double_height_top',
463 # '4':'double_height_bottom',
464 # '5':'single_height_single_width',
465 # '6':'single_height_double_width',
469 0: {'description':'Normal (default)', 'attributes': {'cterm':'NONE','ctermfg':'NONE','ctermbg':'NONE','gui':'NONE','guifg':'NONE','guibg':'NONE'}, 'normal':True},
470 1: {'description':'Bold', 'attributes': {'cterm':'BOLD','gui':'BOLD'}, 'normal':False},
471 4: {'description':'Underlined', 'attributes': {'cterm':'UNDERLINE','gui':'UNDERLINE'}, 'normal':False},
472 5: {'description':'Blink (appears as Bold)', 'attributes': {'cterm':'BOLD','gui':'BOLD'}, 'normal':False},
473 7: {'description':'Inverse', 'attributes': {'cterm':'REVERSE','gui':'REVERSE'}, 'normal':False},
474 8: {'description':'Invisible (hidden)', 'attributes': {'ctermfg':'0','ctermbg':'0','guifg':'#000000','guibg':'#000000'}, 'normal':False},
475 22: {'description':'Normal (neither bold nor faint)', 'attributes': {'cterm':'NONE','gui':'NONE'}, 'normal':True},
476 24: {'description':'Not underlined', 'attributes': {'cterm':'NONE','gui':'NONE'}, 'normal':True},
477 25: {'description':'Steady (not blinking)', 'attributes': {'cterm':'NONE','gui':'NONE'}, 'normal':True},
478 27: {'description':'Positive (not inverse)', 'attributes': {'cterm':'NONE','gui':'NONE'}, 'normal':True},
479 28: {'description':'Visible (not hidden)', 'attributes': {'ctermfg':'NONE','ctermbg':'NONE','guifg':'NONE','guibg':'NONE'}, 'normal':True},
480 30: {'description':'Set foreground color to Black', 'attributes': {'ctermfg':'16','guifg':'#000000'}, 'normal':False},
481 31: {'description':'Set foreground color to Red', 'attributes': {'ctermfg':'1','guifg':'#ff0000'}, 'normal':False},
482 32: {'description':'Set foreground color to Green', 'attributes': {'ctermfg':'2','guifg':'#00ff00'}, 'normal':False},
483 33: {'description':'Set foreground color to Yellow', 'attributes': {'ctermfg':'3','guifg':'#ffff00'}, 'normal':False},
484 34: {'description':'Set foreground color to Blue', 'attributes': {'ctermfg':'4','guifg':'#0000ff'}, 'normal':False},
485 35: {'description':'Set foreground color to Magenta', 'attributes': {'ctermfg':'5','guifg':'#990099'}, 'normal':False},
486 36: {'description':'Set foreground color to Cyan', 'attributes': {'ctermfg':'6','guifg':'#009999'}, 'normal':False},
487 37: {'description':'Set foreground color to White', 'attributes': {'ctermfg':'7','guifg':'#ffffff'}, 'normal':False},
488 39: {'description':'Set foreground color to default (original)', 'attributes': {'ctermfg':'NONE','guifg':'NONE'}, 'normal':True},
489 40: {'description':'Set background color to Black', 'attributes': {'ctermbg':'16','guibg':'#000000'}, 'normal':False},
490 41: {'description':'Set background color to Red', 'attributes': {'ctermbg':'1','guibg':'#ff0000'}, 'normal':False},
491 42: {'description':'Set background color to Green', 'attributes': {'ctermbg':'2','guibg':'#00ff00'}, 'normal':False},
492 43: {'description':'Set background color to Yellow', 'attributes': {'ctermbg':'3','guibg':'#ffff00'}, 'normal':False},
493 44: {'description':'Set background color to Blue', 'attributes': {'ctermbg':'4','guibg':'#0000ff'}, 'normal':False},
494 45: {'description':'Set background color to Magenta', 'attributes': {'ctermbg':'5','guibg':'#990099'}, 'normal':False},
495 46: {'description':'Set background color to Cyan', 'attributes': {'ctermbg':'6','guibg':'#009999'}, 'normal':False},
496 47: {'description':'Set background color to White', 'attributes': {'ctermbg':'7','guibg':'#ffffff'}, 'normal':False},
497 49: {'description':'Set background color to default (original).', 'attributes': {'ctermbg':'NONE','guibg':'NONE'}, 'normal':True},
498 90: {'description':'Set foreground color to Black', 'attributes': {'ctermfg':'8','guifg':'#000000'}, 'normal':False},
499 91: {'description':'Set foreground color to Red', 'attributes': {'ctermfg':'9','guifg':'#ff0000'}, 'normal':False},
500 92: {'description':'Set foreground color to Green', 'attributes': {'ctermfg':'10','guifg':'#00ff00'}, 'normal':False},
501 93: {'description':'Set foreground color to Yellow', 'attributes': {'ctermfg':'11','guifg':'#ffff00'}, 'normal':False},
502 94: {'description':'Set foreground color to Blue', 'attributes': {'ctermfg':'12','guifg':'#0000ff'}, 'normal':False},
503 95: {'description':'Set foreground color to Magenta', 'attributes': {'ctermfg':'13','guifg':'#990099'}, 'normal':False},
504 96: {'description':'Set foreground color to Cyan', 'attributes': {'ctermfg':'14','guifg':'#009999'}, 'normal':False},
505 97: {'description':'Set foreground color to White', 'attributes': {'ctermfg':'15','guifg':'#ffffff'}, 'normal':False},
506 100: {'description':'Set background color to Black', 'attributes': {'ctermbg':'8','guibg':'#000000'}, 'normal':False},
507 101: {'description':'Set background color to Red', 'attributes': {'ctermbg':'9','guibg':'#ff0000'}, 'normal':False},
508 102: {'description':'Set background color to Green', 'attributes': {'ctermbg':'10','guibg':'#00ff00'}, 'normal':False},
509 103: {'description':'Set background color to Yellow', 'attributes': {'ctermbg':'11','guibg':'#ffff00'}, 'normal':False},
510 104: {'description':'Set background color to Blue', 'attributes': {'ctermbg':'12','guibg':'#0000ff'}, 'normal':False},
511 105: {'description':'Set background color to Magenta', 'attributes': {'ctermbg':'13','guibg':'#990099'}, 'normal':False},
512 106: {'description':'Set background color to Cyan', 'attributes': {'ctermbg':'14','guibg':'#009999'}, 'normal':False},
513 107: {'description':'Set background color to White', 'attributes': {'ctermbg':'15','guibg':'#ffffff'}, 'normal':False}
517 # regular expression matching (almost) all control sequences
518 CONQUE_SEQ_REGEX = re.compile(ur"(\u001b\[?\??#?[0-9;]*[a-zA-Z@]|\u001b\][0-9];.*?\u0007|[\u0007-\u000f])", re.UNICODE)
519 CONQUE_SEQ_REGEX_CTL = re.compile(ur"^[\u0007-\u000f]$", re.UNICODE)
520 CONQUE_SEQ_REGEX_CSI = re.compile(ur"^\u001b\[", re.UNICODE)
521 CONQUE_SEQ_REGEX_TITLE = re.compile(ur"^\u001b\]", re.UNICODE)
522 CONQUE_SEQ_REGEX_HASH = re.compile(ur"^\u001b#", re.UNICODE)
523 CONQUE_SEQ_REGEX_ESC = re.compile(ur"^\u001b", re.UNICODE)
526 CONQUE_TABLE_OUTPUT = re.compile("^\s*\|\s.*\s\|\s*$|^\s*\+[=+-]+\+\s*$")
530 ###################################################################################################
533 # CLASS PROPERTIES {{{
541 # terminal dimensions and scrolling region
542 columns = 80 # same as $COLUMNS
543 lines = 24 # same as $LINES
544 working_columns = 80 # can be changed by CSI ? 3 l/h
545 working_lines = 24 # can be changed by CSI r
547 # top/bottom of the scroll region
548 top = 1 # relative to top of screen
549 bottom = 24 # relative to top of screen
552 l = 1 # current cursor line
553 c = 1 # current cursor column
558 # absolute coordinate mode
559 absolute_coords = True
573 # don't wrap table output
576 # wrap CUF/CUB around line breaks
582 def __init__(self): # {{{
583 self.screen = ConqueScreen()
586 # start program and initialize this instance
587 def open(self, command, options): # {{{
590 self.columns = vim.current.window.width
591 self.lines = vim.current.window.height
592 self.working_columns = vim.current.window.width
593 self.working_lines = vim.current.window.height
594 self.bottom = vim.current.window.height
597 self.enable_colors = options['color']
603 self.proc = ConqueSubprocess()
604 self.proc.open(command, { 'TERM' : options['TERM'], 'CONQUE' : '1', 'LINES' : str(self.lines), 'COLUMNS' : str(self.columns)})
608 def write(self, input): # {{{
611 # check if window size has changed
612 self.update_window_size()
615 self.proc.write(input)
619 # read from pty, and update buffer
620 def read(self, timeout = 1): # {{{
621 # read from subprocess
622 output = self.proc.read(timeout)
623 # and strip null chars
624 output = output.replace(chr(0), '')
633 chunks = CONQUE_SEQ_REGEX.split(output)
639 # don't go through all the csi regex if length is one (no matches)
642 self.plain_text(chunks[0])
654 # Check for control character match {{{
655 if CONQUE_SEQ_REGEX_CTL.match(s[0]):
659 getattr(self, 'ctl_' + CONQUE_CTL[nr])()
665 # check for escape sequence match {{{
666 elif CONQUE_SEQ_REGEX_CSI.match(s):
668 if s[-1] in CONQUE_ESCAPE:
669 csi = self.parse_csi(s[2:])
671 getattr(self, 'csi_' + CONQUE_ESCAPE[s[-1]])(csi)
677 # check for title match {{{
678 elif CONQUE_SEQ_REGEX_TITLE.match(s):
680 self.change_title(s[2], s[4:-1])
683 # check for hash match {{{
684 elif CONQUE_SEQ_REGEX_HASH.match(s):
686 if s[-1] in CONQUE_ESCAPE_HASH:
687 getattr(self, 'hash_' + CONQUE_ESCAPE_HASH[s[-1]])()
693 # check for other escape match {{{
694 elif CONQUE_SEQ_REGEX_ESC.match(s):
696 if s[-1] in CONQUE_ESCAPE_PLAIN:
697 getattr(self, 'esc_' + CONQUE_ESCAPE_PLAIN[s[-1]])()
703 # else process plain text {{{
708 # set cursor position
709 self.screen.set_cursor(self.l, self.c)
711 vim.command('redraw')
717 def auto_read(self): # {{{
720 vim.command('call feedkeys("\<F23>", "t")')
722 vim.command('call feedkeys("\<F22>", "t")')
723 self.screen.set_cursor(self.l, self.c)
726 ###############################################################################################
729 def plain_text(self, input):
731 current_line = self.screen[self.l]
733 if len(current_line) < self.working_columns:
734 current_line = current_line + ' ' * (self.c - len(current_line))
736 # if line is wider than screen
737 if self.c + len(input) - 1 > self.working_columns:
738 # Table formatting hack
739 if self.unwrap_tables and CONQUE_TABLE_OUTPUT.match(input):
740 self.screen[self.l] = current_line[ : self.c - 1] + input + current_line[ self.c + len(input) - 1 : ]
741 self.apply_color(self.c, self.c + len(input))
745 diff = self.c + len(input) - self.working_columns - 1
746 # if autowrap is enabled
748 self.screen[self.l] = current_line[ : self.c - 1] + input[ : -1 * diff ]
749 self.apply_color(self.c, self.working_columns)
752 remaining = input[ -1 * diff : ]
754 self.plain_text(remaining)
756 self.screen[self.l] = current_line[ : self.c - 1] + input[ : -1 * diff - 1 ] + input[-1]
757 self.apply_color(self.c, self.working_columns)
758 self.c = self.working_columns
762 self.screen[self.l] = current_line[ : self.c - 1] + input + current_line[ self.c + len(input) - 1 : ]
763 self.apply_color(self.c, self.c + len(input))
766 def apply_color(self, start, end):
769 # stop here if coloration is disabled
770 if not self.enable_colors:
773 real_line = self.screen.get_real_line(self.l)
775 # check for previous overlapping coloration
778 if self.color_history.has_key(real_line):
779 for i in range(len(self.color_history[real_line])):
780 syn = self.color_history[real_line][i]
782 if syn['start'] >= start and syn['start'] < end:
784 vim.command('syn clear ' + syn['name'])
789 self.exec_highlight(real_line, end, syn['end'], syn['highlight'])
790 elif syn['end'] > start and syn['end'] <= end:
792 vim.command('syn clear ' + syn['name'])
795 if syn['start'] < start:
797 self.exec_highlight(real_line, syn['start'], start, syn['highlight'])
802 del self.color_history[real_line][di]
804 # if there are no new colors
805 if len(self.color_changes) == 0:
809 for attr in self.color_changes.keys():
810 highlight = highlight + ' ' + attr + '=' + self.color_changes[attr]
812 # execute the highlight
813 self.exec_highlight(real_line, start, end, highlight)
815 def exec_highlight(self, real_line, start, end, highlight):
816 unique_key = str(self.proc.pid)
818 syntax_name = 'EscapeSequenceAt_' + unique_key + '_' + str(self.l) + '_' + str(start) + '_' + str(len(self.color_history) + 1)
819 syntax_options = ' contains=ALLBUT,ConqueString,MySQLString,MySQLKeyword oneline'
820 syntax_region = 'syntax match ' + syntax_name + ' /\%' + str(real_line) + 'l\%>' + str(start - 1) + 'c.*\%<' + str(end + 1) + 'c/' + syntax_options
821 syntax_highlight = 'highlight ' + syntax_name + highlight
823 vim.command(syntax_region)
824 vim.command(syntax_highlight)
826 # add syntax name to history
827 if not self.color_history.has_key(real_line):
828 self.color_history[real_line] = []
830 self.color_history[real_line].append({'name':syntax_name, 'start':start, 'end':end, 'highlight':highlight})
834 ###############################################################################################
835 # Control functions {{{
838 # if we're in a scrolling region, scroll instead of moving cursor down
839 if self.lines != self.working_lines and self.l == self.bottom:
840 del self.screen[self.top]
841 self.screen.insert(self.bottom, '')
842 elif self.l == self.bottom:
843 self.screen.append('')
847 self.color_changes = {}
852 self.color_changes = {}
862 # default tabstop location
863 ts = self.working_columns
866 for i in range(self.c, len(self.tabstops)):
877 ###############################################################################################
880 def csi_font(self, csi): # {{{
881 if not self.enable_colors:
885 if len(csi['vals']) == 0:
888 # 256 xterm color foreground
889 if len(csi['vals']) == 3 and csi['vals'][0] == 38 and csi['vals'][1] == 5:
890 self.color_changes['ctermfg'] = str(csi['vals'][2])
891 self.color_changes['guifg'] = '#' + self.xterm_to_rgb(csi['vals'][2])
893 # 256 xterm color background
894 elif len(csi['vals']) == 3 and csi['vals'][0] == 48 and csi['vals'][1] == 5:
895 self.color_changes['ctermbg'] = str(csi['vals'][2])
896 self.color_changes['guibg'] = '#' + self.xterm_to_rgb(csi['vals'][2])
900 for val in csi['vals']:
901 if CONQUE_FONT.has_key(val):
903 # ignore starting normal colors
904 if CONQUE_FONT[val]['normal'] and len(self.color_changes) == 0:
907 # clear color changes
908 elif CONQUE_FONT[val]['normal']:
910 self.color_changes = {}
911 # save these color attributes for next plain_text() call
914 for attr in CONQUE_FONT[val]['attributes'].keys():
915 if self.color_changes.has_key(attr) and (attr == 'cterm' or attr == 'gui'):
916 self.color_changes[attr] += ',' + CONQUE_FONT[val]['attributes'][attr]
918 self.color_changes[attr] = CONQUE_FONT[val]['attributes'][attr]
921 def csi_clear_line(self, csi): # {{{
924 # this escape defaults to 0
925 if len(csi['vals']) == 0:
931 # 0 means cursor right
933 self.screen[self.l] = self.screen[self.l][0 : self.c - 1]
935 # 1 means cursor left
936 elif csi['val'] == 1:
937 self.screen[self.l] = ' ' * (self.c) + self.screen[self.l][self.c : ]
940 elif csi['val'] == 2:
941 self.screen[self.l] = ''
944 if csi['val'] == 2 or (csi['val'] == 0 and self.c == 1):
945 real_line = self.screen.get_real_line(self.l)
946 if self.color_history.has_key(real_line):
947 for syn in self.color_history[real_line]:
948 vim.command('syn clear ' + syn['name'])
954 def csi_cursor_right(self, csi): # {{{
955 # we use 1 even if escape explicitly specifies 0
962 if self.wrap_cursor and self.c + csi['val'] > self.working_columns:
963 self.l += int(math.floor( (self.c + csi['val']) / self.working_columns ))
964 self.c = (self.c + csi['val']) % self.working_columns
967 self.c = self.bound(self.c + csi['val'], 1, self.working_columns)
970 def csi_cursor_left(self, csi): # {{{
971 # we use 1 even if escape explicitly specifies 0
975 if self.wrap_cursor and csi['val'] >= self.c:
976 self.l += int(math.floor( (self.c - csi['val']) / self.working_columns ))
977 self.c = self.working_columns - (csi['val'] - self.c) % self.working_columns
980 self.c = self.bound(self.c - csi['val'], 1, self.working_columns)
983 def csi_cursor_to_column(self, csi): # {{{
984 self.c = self.bound(csi['val'], 1, self.working_columns)
987 def csi_cursor_up(self, csi): # {{{
988 self.l = self.bound(self.l - csi['val'], self.top, self.bottom)
990 self.color_changes = {}
993 def csi_cursor_down(self, csi): # {{{
994 self.l = self.bound(self.l + csi['val'], self.top, self.bottom)
996 self.color_changes = {}
999 def csi_clear_screen(self, csi): # {{{
1001 if len(csi['vals']) == 0:
1004 # 2 == clear entire screen
1011 elif csi['val'] == 0:
1012 for l in range(self.bound(self.l + 1, 1, self.lines), self.lines + 1):
1015 # clear end of current line
1016 self.csi_clear_line(self.parse_csi('K'))
1019 elif csi['val'] == 1:
1020 for l in range(1, self.bound(self.l, 1, self.lines + 1)):
1023 # clear beginning of current line
1024 self.csi_clear_line(self.parse_csi('1K'))
1027 if csi['val'] == 2 or csi['val'] == 0:
1028 real_line = self.screen.get_real_line(self.l)
1029 for line in self.color_history.keys():
1030 if line >= real_line:
1031 for syn in self.color_history[line]:
1032 vim.command('syn clear ' + syn['name'])
1034 self.color_changes = {}
1037 def csi_delete_chars(self, csi): # {{{
1038 self.screen[self.l] = self.screen[self.l][ : self.c ] + self.screen[self.l][ self.c + csi['val'] : ]
1041 def csi_add_spaces(self, csi): # {{{
1042 self.screen[self.l] = self.screen[self.l][ : self.c - 1] + ' ' * csi['val'] + self.screen[self.l][self.c : ]
1045 def csi_cursor(self, csi): # {{{
1046 if len(csi['vals']) == 2:
1047 new_line = csi['vals'][0]
1048 new_col = csi['vals'][1]
1053 if self.absolute_coords:
1054 self.l = self.bound(new_line, 1, self.lines)
1056 self.l = self.bound(self.top + new_line - 1, self.top, self.bottom)
1058 self.c = self.bound(new_col, 1, self.working_columns)
1059 if self.c > len(self.screen[self.l]):
1060 self.screen[self.l] = self.screen[self.l] + ' ' * (self.c - len(self.screen[self.l]))
1064 def csi_set_coords(self, csi): # {{{
1065 if len(csi['vals']) == 2:
1066 new_start = csi['vals'][0]
1067 new_end = csi['vals'][1]
1070 new_end = vim.current.window.height
1072 self.top = new_start
1073 self.bottom = new_end
1074 self.working_lines = new_end - new_start + 1
1076 # if cursor is outside scrolling region, reset it
1077 if self.l < self.top:
1079 elif self.l > self.bottom:
1080 self.l = self.bottom
1082 self.color_changes = {}
1085 def csi_tab_clear(self, csi): # {{{
1086 # this escape defaults to 0
1087 if len(csi['vals']) == 0:
1093 self.tabstops[self.c - 1] = False
1094 elif csi['val'] == 3:
1095 for i in range(0, self.columns + 1):
1096 self.tabstops[i] = False
1099 def csi_set(self, csi): # {{{
1102 self.csi_clear_screen(self.parse_csi('2J'))
1103 self.working_columns = 132
1106 elif csi['val'] == 6:
1107 self.absolute_coords = False
1110 elif csi['val'] == 7:
1111 self.autowrap = True
1114 self.color_changes = {}
1117 def csi_reset(self, csi): # {{{
1120 self.csi_clear_screen(self.parse_csi('2J'))
1121 self.working_columns = 80
1124 elif csi['val'] == 6:
1125 self.absolute_coords = True
1128 elif csi['val'] == 7:
1129 self.autowrap = False
1132 self.color_changes = {}
1137 ###############################################################################################
1140 def esc_scroll_up(self): # {{{
1143 self.color_changes = {}
1146 def esc_next_line(self): # {{{
1151 def esc_set_tab(self): # {{{
1153 if self.c <= len(self.tabstops):
1154 self.tabstops[self.c - 1] = True
1157 def esc_scroll_down(self): # {{{
1158 if self.l == self.top:
1159 del self.screen[self.bottom]
1160 self.screen.insert(self.top, '')
1164 self.color_changes = {}
1169 ###############################################################################################
1170 # HASH functions {{{
1172 def hash_screen_alignment_test(self): # {{{
1173 self.csi_clear_screen(self.parse_csi('2J'))
1174 self.working_lines = self.lines
1175 for l in range(1, self.lines + 1):
1176 self.screen[l] = 'E' * self.working_columns
1181 ###############################################################################################
1184 def change_title(self, key, val):
1187 if key == '0' or key == '2':
1189 vim.command('setlocal statusline=' + re.escape(val))
1192 self.write(vim.eval('@@'))
1195 def paste_selection(self):
1196 self.write(vim.eval('@@'))
1198 def update_window_size(self):
1200 if vim.current.window.width != self.columns or vim.current.window.height != self.lines:
1202 # reset all window size attributes to default
1203 self.columns = vim.current.window.width
1204 self.lines = vim.current.window.height
1205 self.working_columns = vim.current.window.width
1206 self.working_lines = vim.current.window.height
1207 self.bottom = vim.current.window.height
1209 # reset screen object attributes
1210 self.l = self.screen.reset_size(self.l)
1213 self.init_tabstops()
1217 # signal process that screen size has changed
1218 self.proc.window_resize(self.lines, self.columns)
1220 def init_tabstops(self):
1221 for i in range(0, self.columns + 1):
1223 self.tabstops.append(True)
1225 self.tabstops.append(False)
1229 ###############################################################################################
1232 def parse_csi(self, s): # {{{
1233 attr = { 'key' : s[-1], 'flag' : '', 'val' : 1, 'vals' : [] }
1245 vals = full.split(';')
1248 val = re.sub("\D", "", val)
1251 attr['vals'].append(int(val))
1253 if len(attr['vals']) == 1:
1254 attr['val'] = int(attr['vals'][0])
1259 def bound(self, val, min, max): # {{{
1269 def xterm_to_rgb(self, color_code): # {{{
1271 ascii_colors = ['000000', 'CD0000', '00CD00', 'CDCD00', '0000EE', 'CD00CD', '00CDCD', 'E5E5E5',
1272 '7F7F7F', 'FF0000', '00FF00', 'FFFF00', '5C5CFF', 'FF00FF', '00FFFF', 'FFFFFF']
1273 return ascii_colors[color_code]
1275 elif color_code < 232:
1276 cc = int(color_code) - 16
1278 p1 = "%02x" % (math.floor(cc / 36) * (255/5))
1279 p2 = "%02x" % (math.floor((cc % 36) / 6) * (255/5))
1280 p3 = "%02x" % (math.floor(cc % 6) * (255/5))
1284 grey_tone = "%02x" % math.floor((255/24) * (color_code - 232))
1285 return grey_tone + grey_tone + grey_tone
1291 import os, signal, pty, tty, select, fcntl, termios, struct
1293 ###################################################################################################
1294 class ConqueSubprocess:
1299 # stdout+stderr file descriptor
1303 def __init__(self): # {{{
1307 # create the pty or whatever (whatever == windows)
1308 def open(self, command, env = {}): # {{{
1309 command_arr = command.split()
1310 executable = command_arr[0]
1314 self.pid, self.fd = pty.fork()
1320 # child proc, replace with command after altering terminal attributes
1323 # set requested environment variables
1324 for k in env.keys():
1325 os.environ[k] = env[k]
1327 # set some attributes
1329 attrs = tty.tcgetattr(1)
1330 attrs[0] = attrs[0] ^ tty.IGNBRK
1331 attrs[0] = attrs[0] | tty.BRKINT | tty.IXANY | tty.IMAXBEL
1332 attrs[2] = attrs[2] | tty.HUPCL
1333 attrs[3] = attrs[3] | tty.ICANON | tty.ECHO | tty.ISIG | tty.ECHOKE
1334 attrs[6][tty.VMIN] = 1
1335 attrs[6][tty.VTIME] = 0
1336 tty.tcsetattr(1, tty.TCSANOW, attrs)
1340 os.execvp(executable, args)
1342 # else master, do nothing
1349 # XXX - select.poll() doesn't work in OS X!!!!!!!
1350 def read(self, timeout = 1): # {{{
1353 read_timeout = float(timeout) / 1000
1356 # what, no do/while?
1358 s_read, s_write, s_error = select.select( [ self.fd ], [], [], read_timeout)
1363 lines = os.read( self.fd, 32 )
1366 output = output + lines
1376 # I guess this one's not bad
1377 def write(self, input): # {{{
1379 os.write(self.fd, input)
1385 def signal(self, signum): # {{{
1387 os.kill(self.pid, signum)
1392 # get process status
1393 def get_status(self): #{{{
1398 if os.waitpid( self.pid, os.WNOHANG )[0]:
1407 # update window size in kernel, then send SIGWINCH to fg process
1408 def window_resize(self, lines, columns): # {{{
1410 fcntl.ioctl(self.fd, termios.TIOCSWINSZ, struct.pack("HHHH", lines, columns, 0, 0))
1411 os.kill(self.pid, signal.SIGWINCH)
1418 ###################################################################################################
1419 # ConqueScreen is an extention of the vim.current.buffer object
1420 # It restricts the working indices of the buffer object to the scroll region which pty is expecting
1421 # It also uses 1-based indexes, to match escape sequence commands
1424 # s = ConqueScreen()
1426 # s[5] = 'Set 5th line in terminal to this line'
1427 # s.append('Add new line to terminal')
1428 # s[5] = 'Since previous append() command scrolled the terminal down, this is a different line than first cb[5] call'
1433 class ConqueScreen(object):
1435 # CLASS PROPERTIES {{{
1440 # screen and scrolling regions
1449 def __init__(self): # {{{
1450 self.buffer = vim.current.buffer
1453 self.screen_width = vim.current.window.width
1454 self.screen_height = vim.current.window.height
1457 ###############################################################################################
1459 def __len__(self): # {{{
1460 return len(self.buffer)
1463 def __getitem__(self, key): # {{{
1464 real_line = self.get_real_idx(key)
1466 # if line is past buffer end, add lines to buffer
1467 if real_line >= len(self.buffer):
1468 for i in range(len(self.buffer), real_line + 1):
1469 self.append(' ' * self.screen_width)
1471 return self.buffer[ real_line ]
1474 def __setitem__(self, key, value): # {{{
1475 real_line = self.get_real_idx(key)
1477 # if line is past end of screen, append
1478 if real_line == len(self.buffer):
1479 self.buffer.append(value)
1481 self.buffer[ real_line ] = value
1484 def __delitem__(self, key): # {{{
1485 del self.buffer[ self.screen_top + key - 2 ]
1488 def append(self, value): # {{{
1489 if len(self.buffer) > self.screen_top + self.screen_height - 1:
1490 self.buffer[len(self.buffer) - 1] = value
1492 self.buffer.append(value)
1494 if len(self.buffer) > self.screen_top + self.screen_height - 1:
1495 self.screen_top += 1
1496 if vim.current.buffer.number == self.buffer.number:
1497 vim.command('normal G')
1500 def insert(self, line, value): # {{{
1502 l = self.screen_top + line - 2
1503 self.buffer[l:l] = [ value ]
1508 ###############################################################################################
1510 def get_top(self): # {{{
1511 return self.screen_top
1514 def get_real_idx(self, line): # {{{
1515 return (self.screen_top + line - 2)
1518 def get_real_line(self, line): # {{{
1519 return (self.screen_top + line - 1)
1522 def set_screen_width(self, width): # {{{
1523 self.screen_width = width
1528 ###############################################################################################
1529 def clear(self): # {{{
1530 self.buffer.append(' ')
1531 vim.command('normal Gzt')
1532 self.screen_top = len(self.buffer)
1535 def set_cursor(self, line, column): # {{{
1537 real_line = self.screen_top + line - 1
1538 if real_line > len(self.buffer):
1539 for l in range(len(self.buffer) - 1, real_line):
1540 self.buffer.append('')
1543 real_column = column
1544 if len(self.buffer[real_line - 1]) < real_column:
1545 self.buffer[real_line - 1] = self.buffer[real_line - 1] + ' ' * (real_column - len(self.buffer[real_line - 1]))
1547 # python version is occasionally grumpy
1549 vim.current.window.cursor = (real_line, real_column - 1)
1551 vim.command('call cursor(' + str(real_line) + ', ' + str(real_column) + ')')
1554 def reset_size(self, line): # {{{
1559 # save cursor line number
1560 real_line = self.screen_top + line
1563 self.screen_width = vim.current.window.width
1564 self.screen_height = vim.current.window.height
1565 self.screen_top = len(self.buffer) - vim.current.window.height + 1
1566 if self.screen_top < 1:
1570 # align bottom of buffer to bottom of screen
1571 vim.command('normal ' + str(self.screen_height) + 'kG')
1573 # return new relative line number
1574 return (real_line - self.screen_top)
1577 def scroll_to_bottom(self): # {{{
1578 vim.current.window.cursor = (len(self.buffer) - 1, 1)
1581 def align(self): # {{{
1582 # align bottom of buffer to bottom of screen
1583 vim.command('normal ' + str(self.screen_height) + 'kG')