]> ruderich.org/simon Gitweb - config/dotfiles.git/blob - vim/bundle/surround/plugin/surround.vim
Switch plugins with more than one file to pathogen.
[config/dotfiles.git] / vim / bundle / surround / plugin / surround.vim
1 " surround.vim - Surroundings
2 " Author:       Tim Pope <vimNOSPAM@tpope.info>
3 " GetLatestVimScripts: 1697 1 :AutoInstall: surround.vim
4 " $Id: surround.vim,v 1.34 2008-02-15 21:43:42 tpope Exp $
5 "
6 " See surround.txt for help.  This can be accessed by doing
7 "
8 " :helptags ~/.vim/doc
9 " :help surround
10 "
11 " Licensed under the same terms as Vim itself.
12
13 " ============================================================================
14
15 " Exit quickly when:
16 " - this plugin was already loaded or disabled
17 " - when 'compatible' is set
18 if (exists("g:loaded_surround") && g:loaded_surround) || &cp
19     finish
20 endif
21 let g:loaded_surround = 1
22
23 let s:cpo_save = &cpo
24 set cpo&vim
25
26 " Input functions {{{1
27
28 function! s:getchar()
29     let c = getchar()
30     if c =~ '^\d\+$'
31         let c = nr2char(c)
32     endif
33     return c
34 endfunction
35
36 function! s:inputtarget()
37     let c = s:getchar()
38     while c =~ '^\d\+$'
39         let c = c . s:getchar()
40     endwhile
41     if c == " "
42         let c = c . s:getchar()
43     endif
44     if c =~ "\<Esc>\|\<C-C>\|\0"
45         return ""
46     else
47         return c
48     endif
49 endfunction
50
51 function! s:inputreplacement()
52     "echo '-- SURROUND --'
53     let c = s:getchar()
54     if c == " "
55         let c = c . s:getchar()
56     endif
57     if c =~ "\<Esc>" || c =~ "\<C-C>"
58         return ""
59     else
60         return c
61     endif
62 endfunction
63
64 function! s:beep()
65     exe "norm! \<Esc>"
66     return ""
67 endfunction
68
69 function! s:redraw()
70     redraw
71     return ""
72 endfunction
73
74 " }}}1
75
76 " Wrapping functions {{{1
77
78 function! s:extractbefore(str)
79     if a:str =~ '\r'
80         return matchstr(a:str,'.*\ze\r')
81     else
82         return matchstr(a:str,'.*\ze\n')
83     endif
84 endfunction
85
86 function! s:extractafter(str)
87     if a:str =~ '\r'
88         return matchstr(a:str,'\r\zs.*')
89     else
90         return matchstr(a:str,'\n\zs.*')
91     endif
92 endfunction
93
94 function! s:repeat(str,count)
95     let cnt = a:count
96     let str = ""
97     while cnt > 0
98         let str = str . a:str
99         let cnt = cnt - 1
100     endwhile
101     return str
102 endfunction
103
104 function! s:fixindent(str,spc)
105     let str = substitute(a:str,'\t',s:repeat(' ',&sw),'g')
106     let spc = substitute(a:spc,'\t',s:repeat(' ',&sw),'g')
107     let str = substitute(str,'\(\n\|\%^\).\@=','\1'.spc,'g')
108     if ! &et
109         let str = substitute(str,'\s\{'.&ts.'\}',"\t",'g')
110     endif
111     return str
112 endfunction
113
114 function! s:process(string)
115     let i = 0
116     while i < 7
117         let i = i + 1
118         let repl_{i} = ''
119         let m = matchstr(a:string,nr2char(i).'.\{-\}\ze'.nr2char(i))
120         if m != ''
121             let m = substitute(strpart(m,1),'\r.*','','')
122             let repl_{i} = input(substitute(m,':\s*$','','').': ')
123         endif
124     endwhile
125     let s = ""
126     let i = 0
127     while i < strlen(a:string)
128         let char = strpart(a:string,i,1)
129         if char2nr(char) < 8
130             let next = stridx(a:string,char,i+1)
131             if next == -1
132                 let s = s . char
133             else
134                 let insertion = repl_{char2nr(char)}
135                 let subs = strpart(a:string,i+1,next-i-1)
136                 let subs = matchstr(subs,'\r.*')
137                 while subs =~ '^\r.*\r'
138                     let sub = matchstr(subs,"^\r\\zs[^\r]*\r[^\r]*")
139                     let subs = strpart(subs,strlen(sub)+1)
140                     let r = stridx(sub,"\r")
141                     let insertion = substitute(insertion,strpart(sub,0,r),strpart(sub,r+1),'')
142                 endwhile
143                 let s = s . insertion
144                 let i = next
145             endif
146         else
147             let s = s . char
148         endif
149         let i = i + 1
150     endwhile
151     return s
152 endfunction
153
154 function! s:wrap(string,char,type,...)
155     let keeper = a:string
156     let newchar = a:char
157     let type = a:type
158     let linemode = type ==# 'V' ? 1 : 0
159     let special = a:0 ? a:1 : 0
160     let before = ""
161     let after  = ""
162     if type == "V"
163         let initspaces = matchstr(keeper,'\%^\s*')
164     else
165         let initspaces = matchstr(getline('.'),'\%^\s*')
166     endif
167     " Duplicate b's are just placeholders (removed)
168     let pairs = "b()B{}r[]a<>"
169     let extraspace = ""
170     if newchar =~ '^ '
171         let newchar = strpart(newchar,1)
172         let extraspace = ' '
173     endif
174     let idx = stridx(pairs,newchar)
175     if newchar == ' '
176         let before = ''
177         let after  = ''
178     elseif exists("b:surround_".char2nr(newchar))
179         let all    = s:process(b:surround_{char2nr(newchar)})
180         let before = s:extractbefore(all)
181         let after  =  s:extractafter(all)
182     elseif exists("g:surround_".char2nr(newchar))
183         let all    = s:process(g:surround_{char2nr(newchar)})
184         let before = s:extractbefore(all)
185         let after  =  s:extractafter(all)
186     elseif newchar ==# "p"
187         let before = "\n"
188         let after  = "\n\n"
189     elseif newchar =~# "[tT\<C-T><,]"
190         let dounmapp = 0
191         let dounmapb = 0
192         if !maparg(">","c")
193             let dounmapb= 1
194             " Hide from AsNeeded
195             exe "cn"."oremap > <CR>"
196             exe "cn"."oremap % %<C-V>"
197             "cm ap > <C-R>=getcmdline() =~ '^[^%?].*[%?]$' ? "\026\076" : "\026\076\015"<CR>
198         endif
199         let default = ""
200         if !maparg("%","c")
201             " This is to help when typing things like
202             " <a href="/images/<%= @image.filename %>">
203             " The downside is it breaks backspace, so lets disable it for now
204             "let dounmapp= 1
205             "exe "cn"."oremap % %<C-V>"
206         endif
207         if newchar ==# "T"
208             if !exists("s:lastdel")
209                 let s:lastdel = ""
210             endif
211             let default = matchstr(s:lastdel,'<\zs.\{-\}\ze>')
212         endif
213         let tag = input("<",default)
214         echo "<".substitute(tag,'>*$','>','')
215         "if dounmapr
216             "silent! cunmap <CR>
217         "endif
218         if dounmapb
219             silent! cunmap >
220         endif
221         if dounmapp
222             silent! cunmap %
223         endif
224         if tag != ""
225             let tag = substitute(tag,'>*$','','')
226             let before = '<'.tag.'>'
227             if tag =~ '/$'
228                 let after = ''
229             else
230                 let after  = '</'.substitute(tag,' .*','','').'>'
231             endif
232             if newchar == "\<C-T>" || newchar == ","
233                 if type ==# "v" || type ==# "V"
234                     let before = before . "\n\t"
235                 endif
236                 if type ==# "v"
237                     let after  = "\n". after
238                 endif
239             endif
240         endif
241     elseif newchar ==# 'l' || newchar == '\'
242         " LaTeX
243         let env = input('\begin{')
244         let env = '{' . env
245         let env = env . s:closematch(env)
246         echo '\begin'.env
247         if env != ""
248             let before = '\begin'.env
249             let after  = '\end'.matchstr(env,'[^}]*').'}'
250         endif
251         "if type ==# 'v' || type ==# 'V'
252             "let before = before ."\n\t"
253         "endif
254         "if type ==# 'v'
255             "let after  = "\n".initspaces.after
256         "endif
257     elseif newchar ==# 'f' || newchar ==# 'F'
258         let fnc = input('function: ')
259         if fnc != ""
260             let before = substitute(fnc,'($','','').'('
261             let after  = ')'
262             if newchar ==# 'F'
263                 let before = before . ' '
264                 let after  = ' ' . after
265             endif
266         endif
267     elseif idx >= 0
268         let spc = (idx % 3) == 1 ? " " : ""
269         let idx = idx / 3 * 3
270         let before = strpart(pairs,idx+1,1) . spc
271         let after  = spc . strpart(pairs,idx+2,1)
272     elseif newchar == "\<C-[>" || newchar == "\<C-]>"
273         let before = "{\n\t"
274         let after  = "\n}"
275     elseif newchar !~ '\a'
276         let before = newchar
277         let after  = newchar
278     else
279         let before = ''
280         let after  = ''
281     endif
282     "let before = substitute(before,'\n','\n'.initspaces,'g')
283     let after  = substitute(after ,'\n','\n'.initspaces,'g')
284     "let after  = substitute(after,"\n\\s*\<C-U>\\s*",'\n','g')
285     if type ==# 'V' || (special && type ==# "v")
286         let before = substitute(before,' \+$','','')
287         let after  = substitute(after ,'^ \+','','')
288         if after !~ '^\n'
289             let after  = initspaces.after
290         endif
291         if keeper !~ '\n$' && after !~ '^\n'
292             let keeper = keeper . "\n"
293         elseif keeper =~ '\n$' && after =~ '^\n'
294             let after = strpart(after,1)
295         endif
296         if before !~ '\n\s*$'
297             let before = before . "\n"
298             if special
299                 let before = before . "\t"
300             endif
301         endif
302     endif
303     if type ==# 'V'
304         let before = initspaces.before
305     endif
306     if before =~ '\n\s*\%$'
307         if type ==# 'v'
308             let keeper = initspaces.keeper
309         endif
310         let padding = matchstr(before,'\n\zs\s\+\%$')
311         let before  = substitute(before,'\n\s\+\%$','\n','')
312         let keeper = s:fixindent(keeper,padding)
313     endif
314     if type ==# 'V'
315         let keeper = before.keeper.after
316     elseif type =~ "^\<C-V>"
317         " Really we should be iterating over the buffer
318         let repl = substitute(before,'[\\~]','\\&','g').'\1'.substitute(after,'[\\~]','\\&','g')
319         let repl = substitute(repl,'\n',' ','g')
320         let keeper = substitute(keeper."\n",'\(.\{-\}\)\('.(special ? '\s\{-\}' : '').'\n\)',repl.'\n','g')
321         let keeper = substitute(keeper,'\n\%$','','')
322     else
323         let keeper = before.extraspace.keeper.extraspace.after
324     endif
325     return keeper
326 endfunction
327
328 function! s:wrapreg(reg,char,...)
329     let orig = getreg(a:reg)
330     let type = substitute(getregtype(a:reg),'\d\+$','','')
331     let special = a:0 ? a:1 : 0
332     let new = s:wrap(orig,a:char,type,special)
333     call setreg(a:reg,new,type)
334 endfunction
335 " }}}1
336
337 function! s:insert(...) " {{{1
338     " Optional argument causes the result to appear on 3 lines, not 1
339     "call inputsave()
340     let linemode = a:0 ? a:1 : 0
341     let char = s:inputreplacement()
342     while char == "\<CR>" || char == "\<C-S>"
343         " TODO: use total count for additional blank lines
344         let linemode = linemode + 1
345         let char = s:inputreplacement()
346     endwhile
347     "call inputrestore()
348     if char == ""
349         return ""
350     endif
351     "call inputsave()
352     let cb_save = &clipboard
353     let reg_save = @@
354     call setreg('"',"\r",'v')
355     call s:wrapreg('"',char,linemode)
356     " If line mode is used and the surrounding consists solely of a suffix,
357     " remove the initial newline.  This fits a use case of mine but is a
358     " little inconsistent.  Is there anyone that would prefer the simpler
359     " behavior of just inserting the newline?
360     if linemode && match(getreg('"'),'^\n\s*\zs.*') == 0
361         call setreg('"',matchstr(getreg('"'),'^\n\s*\zs.*'),getregtype('"'))
362     endif
363     " This can be used to append a placeholder to the end
364     if exists("g:surround_insert_tail")
365         call setreg('"',g:surround_insert_tail,"a".getregtype('"'))
366     endif
367     "if linemode
368         "call setreg('"',substitute(getreg('"'),'^\s\+','',''),'c')
369     "endif
370     if col('.') >= col('$')
371         norm! ""p
372     else
373         norm! ""P
374     endif
375     if linemode
376         call s:reindent()
377     endif
378     norm! `]
379     call search('\r','bW')
380     let @@ = reg_save
381     let &clipboard = cb_save
382     return "\<Del>"
383 endfunction " }}}1
384
385 function! s:reindent() " {{{1
386     if exists("b:surround_indent") ? b:surround_indent : (exists("g:surround_indent") && g:surround_indent)
387         silent norm! '[=']
388     endif
389 endfunction " }}}1
390
391 function! s:dosurround(...) " {{{1
392     let scount = v:count1
393     let char = (a:0 ? a:1 : s:inputtarget())
394     let spc = ""
395     if char =~ '^\d\+'
396         let scount = scount * matchstr(char,'^\d\+')
397         let char = substitute(char,'^\d\+','','')
398     endif
399     if char =~ '^ '
400         let char = strpart(char,1)
401         let spc = 1
402     endif
403     if char == 'a'
404         let char = '>'
405     endif
406     if char == 'r'
407         let char = ']'
408     endif
409     let newchar = ""
410     if a:0 > 1
411         let newchar = a:2
412         if newchar == "\<Esc>" || newchar == "\<C-C>" || newchar == ""
413             return s:beep()
414         endif
415     endif
416     let cb_save = &clipboard
417     set clipboard-=unnamed
418     let append = ""
419     let original = getreg('"')
420     let otype = getregtype('"')
421     call setreg('"',"")
422     let strcount = (scount == 1 ? "" : scount)
423     if char == '/'
424         exe 'norm '.strcount.'[/d'.strcount.']/'
425     else
426         exe 'norm d'.strcount.'i'.char
427     endif
428     let keeper = getreg('"')
429     let okeeper = keeper " for reindent below
430     if keeper == ""
431         call setreg('"',original,otype)
432         let &clipboard = cb_save
433         return ""
434     endif
435     let oldline = getline('.')
436     let oldlnum = line('.')
437     if char ==# "p"
438         call setreg('"','','V')
439     elseif char ==# "s" || char ==# "w" || char ==# "W"
440         " Do nothing
441         call setreg('"','')
442     elseif char =~ "[\"'`]"
443         exe "norm! i \<Esc>d2i".char
444         call setreg('"',substitute(getreg('"'),' ','',''))
445     elseif char == '/'
446         norm! "_x
447         call setreg('"','/**/',"c")
448         let keeper = substitute(substitute(keeper,'^/\*\s\=','',''),'\s\=\*$','','')
449     else
450         " One character backwards
451         call search('.','bW')
452         exe "norm da".char
453     endif
454     let removed = getreg('"')
455     let rem2 = substitute(removed,'\n.*','','')
456     let oldhead = strpart(oldline,0,strlen(oldline)-strlen(rem2))
457     let oldtail = strpart(oldline,  strlen(oldline)-strlen(rem2))
458     let regtype = getregtype('"')
459     if char =~# '[\[({<T]' || spc
460         let keeper = substitute(keeper,'^\s\+','','')
461         let keeper = substitute(keeper,'\s\+$','','')
462     endif
463     if col("']") == col("$") && col('.') + 1 == col('$')
464         if oldhead =~# '^\s*$' && a:0 < 2
465             let keeper = substitute(keeper,'\%^\n'.oldhead.'\(\s*.\{-\}\)\n\s*\%$','\1','')
466         endif
467         let pcmd = "p"
468     else
469         let pcmd = "P"
470     endif
471     if line('.') < oldlnum && regtype ==# "V"
472         let pcmd = "p"
473     endif
474     call setreg('"',keeper,regtype)
475     if newchar != ""
476         call s:wrapreg('"',newchar)
477     endif
478     silent exe 'norm! ""'.pcmd.'`['
479     if removed =~ '\n' || okeeper =~ '\n' || getreg('"') =~ '\n'
480         call s:reindent()
481     endif
482     if getline('.') =~ '^\s\+$' && keeper =~ '^\s*\n'
483         silent norm! cc
484     endif
485     call setreg('"',removed,regtype)
486     let s:lastdel = removed
487     let &clipboard = cb_save
488     if newchar == ""
489         silent! call repeat#set("\<Plug>Dsurround".char,scount)
490     else
491         silent! call repeat#set("\<Plug>Csurround".char.newchar,scount)
492     endif
493 endfunction " }}}1
494
495 function! s:changesurround() " {{{1
496     let a = s:inputtarget()
497     if a == ""
498         return s:beep()
499     endif
500     let b = s:inputreplacement()
501     if b == ""
502         return s:beep()
503     endif
504     call s:dosurround(a,b)
505 endfunction " }}}1
506
507 function! s:opfunc(type,...) " {{{1
508     let char = s:inputreplacement()
509     if char == ""
510         return s:beep()
511     endif
512     let reg = '"'
513     let sel_save = &selection
514     let &selection = "inclusive"
515     let cb_save  = &clipboard
516     set clipboard-=unnamed
517     let reg_save = getreg(reg)
518     let reg_type = getregtype(reg)
519     "call setreg(reg,"\n","c")
520     let type = a:type
521     if a:type == "char"
522         silent exe 'norm! v`[o`]"'.reg.'y'
523         let type = 'v'
524     elseif a:type == "line"
525         silent exe 'norm! `[V`]"'.reg.'y'
526         let type = 'V'
527     elseif a:type ==# "v" || a:type ==# "V" || a:type ==# "\<C-V>"
528         silent exe 'norm! gv"'.reg.'y'
529     elseif a:type =~ '^\d\+$'
530         let type = 'v'
531         silent exe 'norm! ^v'.a:type.'$h"'.reg.'y'
532         if mode() == 'v'
533             norm! v
534             return s:beep()
535         endif
536     else
537         let &selection = sel_save
538         let &clipboard = cb_save
539         return s:beep()
540     endif
541     let keeper = getreg(reg)
542     if type == "v" && a:type != "v"
543         let append = matchstr(keeper,'\_s\@<!\s*$')
544         let keeper = substitute(keeper,'\_s\@<!\s*$','','')
545     endif
546     call setreg(reg,keeper,type)
547     call s:wrapreg(reg,char,a:0)
548     if type == "v" && a:type != "v" && append != ""
549         call setreg(reg,append,"ac")
550     endif
551     silent exe 'norm! gv'.(reg == '"' ? '' : '"' . reg).'p`['
552     if type == 'V' || (getreg(reg) =~ '\n' && type == 'v')
553         call s:reindent()
554     endif
555     call setreg(reg,reg_save,reg_type)
556     let &selection = sel_save
557     let &clipboard = cb_save
558     if a:type =~ '^\d\+$'
559         silent! call repeat#set("\<Plug>Y".(a:0 ? "S" : "s")."surround".char,a:type)
560     endif
561 endfunction
562
563 function! s:opfunc2(arg)
564     call s:opfunc(a:arg,1)
565 endfunction " }}}1
566
567 function! s:closematch(str) " {{{1
568     " Close an open (, {, [, or < on the command line.
569     let tail = matchstr(a:str,'.[^\[\](){}<>]*$')
570     if tail =~ '^\[.\+'
571         return "]"
572     elseif tail =~ '^(.\+'
573         return ")"
574     elseif tail =~ '^{.\+'
575         return "}"
576     elseif tail =~ '^<.+'
577         return ">"
578     else
579         return ""
580     endif
581 endfunction " }}}1
582
583 nnoremap <silent> <Plug>Dsurround  :<C-U>call <SID>dosurround(<SID>inputtarget())<CR>
584 nnoremap <silent> <Plug>Csurround  :<C-U>call <SID>changesurround()<CR>
585 nnoremap <silent> <Plug>Yssurround :<C-U>call <SID>opfunc(v:count1)<CR>
586 nnoremap <silent> <Plug>YSsurround :<C-U>call <SID>opfunc2(v:count1)<CR>
587 " <C-U> discards the numerical argument but there's not much we can do with it
588 nnoremap <silent> <Plug>Ysurround  :<C-U>set opfunc=<SID>opfunc<CR>g@
589 nnoremap <silent> <Plug>YSurround  :<C-U>set opfunc=<SID>opfunc2<CR>g@
590 vnoremap <silent> <Plug>Vsurround  :<C-U>call <SID>opfunc(visualmode())<CR>
591 vnoremap <silent> <Plug>VSurround  :<C-U>call <SID>opfunc2(visualmode())<CR>
592 inoremap <silent> <Plug>Isurround  <C-R>=<SID>insert()<CR>
593 inoremap <silent> <Plug>ISurround  <C-R>=<SID>insert(1)<CR>
594
595 if !exists("g:surround_no_mappings") || ! g:surround_no_mappings
596     nmap          ds   <Plug>Dsurround
597     nmap          cs   <Plug>Csurround
598     nmap          ys   <Plug>Ysurround
599     nmap          yS   <Plug>YSurround
600     nmap          yss  <Plug>Yssurround
601     nmap          ySs  <Plug>YSsurround
602     nmap          ySS  <Plug>YSsurround
603     if !hasmapto("<Plug>Vsurround","v")
604         if exists(":xmap")
605             xmap  s    <Plug>Vsurround
606         else
607             vmap  s    <Plug>Vsurround
608         endif
609     endif
610     if !hasmapto("<Plug>VSurround","v")
611         if exists(":xmap")
612             xmap  S    <Plug>VSurround
613         else
614             vmap  S    <Plug>VSurround
615         endif
616     endif
617     if !hasmapto("<Plug>Isurround","i") && "" == mapcheck("<C-S>","i")
618         imap     <C-S> <Plug>Isurround
619     endif
620     imap        <C-G>s <Plug>Isurround
621     imap        <C-G>S <Plug>ISurround
622     "Implemented internally instead
623     "imap     <C-S><C-S> <Plug>ISurround
624 endif
625
626 let &cpo = s:cpo_save
627
628 " vim:set ft=vim sw=4 sts=4 et: