44c8976d6f30fde46693e1e8fa3ce19481e1863e
[tpope.git] / .vim / plugin / surround.vim
1 " surround.vim - Surroundings
2 " Author:       Tim Pope <vimNOSPAM@tpope.info>
3 " GetLatestVimScripts: 1697 1 :AutoInstall: surround.vim
4 " $Id$
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     set clipboard-=unnamed
354     let reg_save = @@
355     call setreg('"',"\r",'v')
356     call s:wrapreg('"',char,linemode)
357     " If line mode is used and the surrounding consists solely of a suffix,
358     " remove the initial newline.  This fits a use case of mine but is a
359     " little inconsistent.  Is there anyone that would prefer the simpler
360     " behavior of just inserting the newline?
361     if linemode && match(getreg('"'),'^\n\s*\zs.*') == 0
362         call setreg('"',matchstr(getreg('"'),'^\n\s*\zs.*'),getregtype('"'))
363     endif
364     " This can be used to append a placeholder to the end
365     if exists("g:surround_insert_tail")
366         call setreg('"',g:surround_insert_tail,"a".getregtype('"'))
367     endif
368     "if linemode
369         "call setreg('"',substitute(getreg('"'),'^\s\+','',''),'c')
370     "endif
371     if col('.') >= col('$')
372         norm! ""p
373     else
374         norm! ""P
375     endif
376     if linemode
377         call s:reindent()
378     endif
379     norm! `]
380     call search('\r','bW')
381     let @@ = reg_save
382     let &clipboard = cb_save
383     return "\<Del>"
384 endfunction " }}}1
385
386 function! s:reindent() " {{{1
387     if exists("b:surround_indent") ? b:surround_indent : (exists("g:surround_indent") && g:surround_indent)
388         silent norm! '[=']
389     endif
390 endfunction " }}}1
391
392 function! s:dosurround(...) " {{{1
393     let scount = v:count1
394     let char = (a:0 ? a:1 : s:inputtarget())
395     let spc = ""
396     if char =~ '^\d\+'
397         let scount = scount * matchstr(char,'^\d\+')
398         let char = substitute(char,'^\d\+','','')
399     endif
400     if char =~ '^ '
401         let char = strpart(char,1)
402         let spc = 1
403     endif
404     if char == 'a'
405         let char = '>'
406     endif
407     if char == 'r'
408         let char = ']'
409     endif
410     let newchar = ""
411     if a:0 > 1
412         let newchar = a:2
413         if newchar == "\<Esc>" || newchar == "\<C-C>" || newchar == ""
414             return s:beep()
415         endif
416     endif
417     let cb_save = &clipboard
418     set clipboard-=unnamed
419     let append = ""
420     let original = getreg('"')
421     let otype = getregtype('"')
422     call setreg('"',"")
423     let strcount = (scount == 1 ? "" : scount)
424     if char == '/'
425         exe 'norm '.strcount.'[/d'.strcount.']/'
426     else
427         exe 'norm d'.strcount.'i'.char
428     endif
429     let keeper = getreg('"')
430     let okeeper = keeper " for reindent below
431     if keeper == ""
432         call setreg('"',original,otype)
433         let &clipboard = cb_save
434         return ""
435     endif
436     let oldline = getline('.')
437     let oldlnum = line('.')
438     if char ==# "p"
439         call setreg('"','','V')
440     elseif char ==# "s" || char ==# "w" || char ==# "W"
441         " Do nothing
442         call setreg('"','')
443     elseif char =~ "[\"'`]"
444         exe "norm! i \<Esc>d2i".char
445         call setreg('"',substitute(getreg('"'),' ','',''))
446     elseif char == '/'
447         norm! "_x
448         call setreg('"','/**/',"c")
449         let keeper = substitute(substitute(keeper,'^/\*\s\=','',''),'\s\=\*$','','')
450     else
451         " One character backwards
452         call search('.','bW')
453         exe "norm da".char
454     endif
455     let removed = getreg('"')
456     let rem2 = substitute(removed,'\n.*','','')
457     let oldhead = strpart(oldline,0,strlen(oldline)-strlen(rem2))
458     let oldtail = strpart(oldline,  strlen(oldline)-strlen(rem2))
459     let regtype = getregtype('"')
460     if char =~# '[\[({<T]' || spc
461         let keeper = substitute(keeper,'^\s\+','','')
462         let keeper = substitute(keeper,'\s\+$','','')
463     endif
464     if col("']") == col("$") && col('.') + 1 == col('$')
465         if oldhead =~# '^\s*$' && a:0 < 2
466             let keeper = substitute(keeper,'\%^\n'.oldhead.'\(\s*.\{-\}\)\n\s*\%$','\1','')
467         endif
468         let pcmd = "p"
469     else
470         let pcmd = "P"
471     endif
472     if line('.') < oldlnum && regtype ==# "V"
473         let pcmd = "p"
474     endif
475     call setreg('"',keeper,regtype)
476     if newchar != ""
477         call s:wrapreg('"',newchar)
478     endif
479     silent exe 'norm! ""'.pcmd.'`['
480     if removed =~ '\n' || okeeper =~ '\n' || getreg('"') =~ '\n'
481         call s:reindent()
482     endif
483     if getline('.') =~ '^\s\+$' && keeper =~ '^\s*\n'
484         silent norm! cc
485     endif
486     call setreg('"',removed,regtype)
487     let s:lastdel = removed
488     let &clipboard = cb_save
489     if newchar == ""
490         silent! call repeat#set("\<Plug>Dsurround".char,scount)
491     else
492         silent! call repeat#set("\<Plug>Csurround".char.newchar,scount)
493     endif
494 endfunction " }}}1
495
496 function! s:changesurround() " {{{1
497     let a = s:inputtarget()
498     if a == ""
499         return s:beep()
500     endif
501     let b = s:inputreplacement()
502     if b == ""
503         return s:beep()
504     endif
505     call s:dosurround(a,b)
506 endfunction " }}}1
507
508 function! s:opfunc(type,...) " {{{1
509     let char = s:inputreplacement()
510     if char == ""
511         return s:beep()
512     endif
513     let reg = '"'
514     let sel_save = &selection
515     let &selection = "inclusive"
516     let cb_save  = &clipboard
517     set clipboard-=unnamed
518     let reg_save = getreg(reg)
519     let reg_type = getregtype(reg)
520     "call setreg(reg,"\n","c")
521     let type = a:type
522     if a:type == "char"
523         silent exe 'norm! v`[o`]"'.reg.'y'
524         let type = 'v'
525     elseif a:type == "line"
526         silent exe 'norm! `[V`]"'.reg.'y'
527         let type = 'V'
528     elseif a:type ==# "v" || a:type ==# "V" || a:type ==# "\<C-V>"
529         let ve = &virtualedit
530         set virtualedit=
531         silent exe 'norm! gv"'.reg.'y'
532         let &virtualedit = ve
533     elseif a:type =~ '^\d\+$'
534         let type = 'v'
535         silent exe 'norm! ^v'.a:type.'$h"'.reg.'y'
536         if mode() ==# 'v'
537             norm! v
538             return s:beep()
539         endif
540     else
541         let &selection = sel_save
542         let &clipboard = cb_save
543         return s:beep()
544     endif
545     let keeper = getreg(reg)
546     if type ==# "v" && a:type !=# "v"
547         let append = matchstr(keeper,'\_s\@<!\s*$')
548         let keeper = substitute(keeper,'\_s\@<!\s*$','','')
549     endif
550     call setreg(reg,keeper,type)
551     call s:wrapreg(reg,char,a:0)
552     if type ==# "v" && a:type !=# "v" && append != ""
553         call setreg(reg,append,"ac")
554     endif
555     silent exe 'norm! gv'.(reg == '"' ? '' : '"' . reg).'p`['
556     if type ==# 'V' || (getreg(reg) =~ '\n' && type ==# 'v')
557         call s:reindent()
558     endif
559     call setreg(reg,reg_save,reg_type)
560     let &selection = sel_save
561     let &clipboard = cb_save
562     if a:type =~ '^\d\+$'
563         silent! call repeat#set("\<Plug>Y".(a:0 ? "S" : "s")."surround".char,a:type)
564     endif
565 endfunction
566
567 function! s:opfunc2(arg)
568     call s:opfunc(a:arg,1)
569 endfunction " }}}1
570
571 function! s:closematch(str) " {{{1
572     " Close an open (, {, [, or < on the command line.
573     let tail = matchstr(a:str,'.[^\[\](){}<>]*$')
574     if tail =~ '^\[.\+'
575         return "]"
576     elseif tail =~ '^(.\+'
577         return ")"
578     elseif tail =~ '^{.\+'
579         return "}"
580     elseif tail =~ '^<.+'
581         return ">"
582     else
583         return ""
584     endif
585 endfunction " }}}1
586
587 nnoremap <silent> <Plug>Dsurround  :<C-U>call <SID>dosurround(<SID>inputtarget())<CR>
588 nnoremap <silent> <Plug>Csurround  :<C-U>call <SID>changesurround()<CR>
589 nnoremap <silent> <Plug>Yssurround :<C-U>call <SID>opfunc(v:count1)<CR>
590 nnoremap <silent> <Plug>YSsurround :<C-U>call <SID>opfunc2(v:count1)<CR>
591 " <C-U> discards the numerical argument but there's not much we can do with it
592 nnoremap <silent> <Plug>Ysurround  :<C-U>set opfunc=<SID>opfunc<CR>g@
593 nnoremap <silent> <Plug>YSurround  :<C-U>set opfunc=<SID>opfunc2<CR>g@
594 vnoremap <silent> <Plug>Vsurround  :<C-U>call <SID>opfunc(visualmode())<CR>
595 vnoremap <silent> <Plug>VSurround  :<C-U>call <SID>opfunc2(visualmode())<CR>
596 inoremap <silent> <Plug>Isurround  <C-R>=<SID>insert()<CR>
597 inoremap <silent> <Plug>ISurround  <C-R>=<SID>insert(1)<CR>
598
599 if !exists("g:surround_no_mappings") || ! g:surround_no_mappings
600     nmap          ds   <Plug>Dsurround
601     nmap          cs   <Plug>Csurround
602     nmap          ys   <Plug>Ysurround
603     nmap          yS   <Plug>YSurround
604     nmap          yss  <Plug>Yssurround
605     nmap          ySs  <Plug>YSsurround
606     nmap          ySS  <Plug>YSsurround
607     if !hasmapto("<Plug>Vsurround","v")
608         if exists(":xmap")
609             xmap  s    <Plug>Vsurround
610         else
611             vmap  s    <Plug>Vsurround
612         endif
613     endif
614     if !hasmapto("<Plug>VSurround","v")
615         if exists(":xmap")
616             xmap  S    <Plug>VSurround
617         else
618             vmap  S    <Plug>VSurround
619         endif
620     endif
621     if !hasmapto("<Plug>Isurround","i") && "" == mapcheck("<C-S>","i")
622         imap     <C-S> <Plug>Isurround
623     endif
624     imap        <C-G>s <Plug>Isurround
625     imap        <C-G>S <Plug>ISurround
626     "Implemented internally instead
627     "imap     <C-S><C-S> <Plug>ISurround
628 endif
629
630 let &cpo = s:cpo_save
631
632 " vim:set ft=vim sw=4 sts=4 et: