1" Tests for multi-line regexps with ":s".
2
3source shared.vim
4
5func Test_multiline_subst()
6  enew!
7  call append(0, ["1 aa",
8	      \ "bb",
9	      \ "cc",
10	      \ "2 dd",
11	      \ "ee",
12	      \ "3 ef",
13	      \ "gh",
14	      \ "4 ij",
15	      \ "5 a8",
16	      \ "8b c9",
17	      \ "9d",
18	      \ "6 e7",
19	      \ "77f",
20	      \ "xxxxx"])
21
22  1
23  " test if replacing a line break works with a back reference
24  /^1/,/^2/s/\n\(.\)/ \1/
25  " test if inserting a line break works with a back reference
26  /^3/,/^4/s/\(.\)$/\r\1/
27  " test if replacing a line break with another line break works
28  /^5/,/^6/s/\(\_d\{3}\)/x\1x/
29  call assert_equal('1 aa bb cc 2 dd ee', getline(1))
30  call assert_equal('3 e', getline(2))
31  call assert_equal('f', getline(3))
32  call assert_equal('g', getline(4))
33  call assert_equal('h', getline(5))
34  call assert_equal('4 i', getline(6))
35  call assert_equal('j', getline(7))
36  call assert_equal('5 ax8', getline(8))
37  call assert_equal('8xb cx9', getline(9))
38  call assert_equal('9xd', getline(10))
39  call assert_equal('6 ex7', getline(11))
40  call assert_equal('7x7f', getline(12))
41  call assert_equal('xxxxx', getline(13))
42  enew!
43endfunc
44
45func Test_substitute_variants()
46  " Validate that all the 2-/3-letter variants which embed the flags into the
47  " command name actually work.
48  enew!
49  let ln = 'Testing string'
50  let variants = [
51	\ { 'cmd': ':s/Test/test/c', 'exp': 'testing string', 'prompt': 'y' },
52	\ { 'cmd': ':s/foo/bar/ce', 'exp': ln },
53	\ { 'cmd': ':s/t/r/cg', 'exp': 'Tesring srring', 'prompt': 'a' },
54	\ { 'cmd': ':s/t/r/ci', 'exp': 'resting string', 'prompt': 'y' },
55	\ { 'cmd': ':s/t/r/cI', 'exp': 'Tesring string', 'prompt': 'y' },
56	\ { 'cmd': ':s/t/r/c', 'exp': 'Testing string', 'prompt': 'n' },
57	\ { 'cmd': ':s/t/r/cn', 'exp': ln },
58	\ { 'cmd': ':s/t/r/cp', 'exp': 'Tesring string', 'prompt': 'y' },
59	\ { 'cmd': ':s/t/r/cl', 'exp': 'Tesring string', 'prompt': 'y' },
60	\ { 'cmd': ':s/t/r/gc', 'exp': 'Tesring srring', 'prompt': 'a' },
61	\ { 'cmd': ':s/i/I/gc', 'exp': 'TestIng string', 'prompt': 'l' },
62	\ { 'cmd': ':s/foo/bar/ge', 'exp': ln },
63	\ { 'cmd': ':s/t/r/g', 'exp': 'Tesring srring' },
64	\ { 'cmd': ':s/t/r/gi', 'exp': 'resring srring' },
65	\ { 'cmd': ':s/t/r/gI', 'exp': 'Tesring srring' },
66	\ { 'cmd': ':s/t/r/gn', 'exp': ln },
67	\ { 'cmd': ':s/t/r/gp', 'exp': 'Tesring srring' },
68	\ { 'cmd': ':s/t/r/gl', 'exp': 'Tesring srring' },
69	\ { 'cmd': ':s//r/gr', 'exp': 'Testr strr' },
70	\ { 'cmd': ':s/t/r/ic', 'exp': 'resting string', 'prompt': 'y' },
71	\ { 'cmd': ':s/foo/bar/ie', 'exp': ln },
72	\ { 'cmd': ':s/t/r/i', 'exp': 'resting string' },
73	\ { 'cmd': ':s/t/r/iI', 'exp': 'Tesring string' },
74	\ { 'cmd': ':s/t/r/in', 'exp': ln },
75	\ { 'cmd': ':s/t/r/ip', 'exp': 'resting string' },
76	\ { 'cmd': ':s//r/ir', 'exp': 'Testr string' },
77	\ { 'cmd': ':s/t/r/Ic', 'exp': 'Tesring string', 'prompt': 'y' },
78	\ { 'cmd': ':s/foo/bar/Ie', 'exp': ln },
79	\ { 'cmd': ':s/t/r/Ig', 'exp': 'Tesring srring' },
80	\ { 'cmd': ':s/t/r/Ii', 'exp': 'resting string' },
81	\ { 'cmd': ':s/t/r/I', 'exp': 'Tesring string' },
82	\ { 'cmd': ':s/t/r/Ip', 'exp': 'Tesring string' },
83	\ { 'cmd': ':s/t/r/Il', 'exp': 'Tesring string' },
84	\ { 'cmd': ':s//r/Ir', 'exp': 'Testr string' },
85	\ { 'cmd': ':s//r/rc', 'exp': 'Testr string', 'prompt': 'y' },
86	\ { 'cmd': ':s//r/rg', 'exp': 'Testr strr' },
87	\ { 'cmd': ':s//r/ri', 'exp': 'Testr string' },
88	\ { 'cmd': ':s//r/rI', 'exp': 'Testr string' },
89	\ { 'cmd': ':s//r/rn', 'exp': 'Testing string' },
90	\ { 'cmd': ':s//r/rp', 'exp': 'Testr string' },
91	\ { 'cmd': ':s//r/rl', 'exp': 'Testr string' },
92	\ { 'cmd': ':s//r/r', 'exp': 'Testr string' },
93	\ { 'cmd': ':s/i/I/gc', 'exp': 'Testing string', 'prompt': 'q' },
94	\]
95
96  for var in variants
97    for run in [1, 2]
98      let cmd = var.cmd
99      if run == 2 && cmd =~ "/.*/.*/."
100	" Change  :s/from/to/{flags}  to  :s{flags}
101	let cmd = substitute(cmd, '/.*/', '', '')
102      endif
103      call setline(1, [ln])
104      let msg = printf('using "%s"', cmd)
105      let @/='ing'
106      let v:errmsg = ''
107      call feedkeys(cmd . "\<CR>" . get(var, 'prompt', ''), 'ntx')
108      " No error should exist (matters for testing e flag)
109      call assert_equal('', v:errmsg, msg)
110      call assert_equal(var.exp, getline('.'), msg)
111    endfor
112  endfor
113endfunc
114
115" Test the l, p, # flags.
116func Test_substitute_flags_lp()
117  new
118  call setline(1, "abc\tdef\<C-h>ghi")
119
120  let a = execute('s/a/a/p')
121  call assert_equal("\nabc     def^Hghi", a)
122
123  let a = execute('s/a/a/l')
124  call assert_equal("\nabc^Idef^Hghi$", a)
125
126  let a = execute('s/a/a/#')
127  call assert_equal("\n  1 abc     def^Hghi", a)
128
129  let a = execute('s/a/a/p#')
130  call assert_equal("\n  1 abc     def^Hghi", a)
131
132  let a = execute('s/a/a/l#')
133  call assert_equal("\n  1 abc^Idef^Hghi$", a)
134
135  let a = execute('s/a/a/')
136  call assert_equal("", a)
137
138  bwipe!
139endfunc
140
141func Test_substitute_repeat()
142  " This caused an invalid memory access.
143  split Xfile
144  s/^/x
145  call feedkeys("Qsc\<CR>y", 'tx')
146  bwipe!
147endfunc
148
149" Test %s/\n// which is implemented as a special case to use a
150" more efficient join rather than doing a regular substitution.
151func Test_substitute_join()
152  new
153
154  call setline(1, ["foo\tbar", "bar\<C-H>foo"])
155  let a = execute('%s/\n//')
156  call assert_equal("", a)
157  call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
158  call assert_equal('\n', histget("search", -1))
159
160  call setline(1, ["foo\tbar", "bar\<C-H>foo"])
161  let a = execute('%s/\n//g')
162  call assert_equal("", a)
163  call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
164  call assert_equal('\n', histget("search", -1))
165
166  call setline(1, ["foo\tbar", "bar\<C-H>foo"])
167  let a = execute('%s/\n//p')
168  call assert_equal("\nfoo     barbar^Hfoo", a)
169  call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
170  call assert_equal('\n', histget("search", -1))
171
172  call setline(1, ["foo\tbar", "bar\<C-H>foo"])
173  let a = execute('%s/\n//l')
174  call assert_equal("\nfoo^Ibarbar^Hfoo$", a)
175  call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
176  call assert_equal('\n', histget("search", -1))
177
178  call setline(1, ["foo\tbar", "bar\<C-H>foo"])
179  let a = execute('%s/\n//#')
180  call assert_equal("\n  1 foo     barbar^Hfoo", a)
181  call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
182  call assert_equal('\n', histget("search", -1))
183
184  call setline(1, ['foo', 'bar', 'baz', 'qux'])
185  call execute('1,2s/\n//')
186  call assert_equal(['foobarbaz', 'qux'], getline(1, '$'))
187
188  bwipe!
189endfunc
190
191func Test_substitute_count()
192  new
193  call setline(1, ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo'])
194  2
195
196  s/foo/bar/3
197  call assert_equal(['foo foo', 'bar foo', 'bar foo', 'bar foo', 'foo foo'],
198  \                 getline(1, '$'))
199
200  call assert_fails('s/foo/bar/0', 'E939:')
201
202  call setline(1, ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo'])
203  2,4s/foo/bar/ 10
204  call assert_equal(['foo foo', 'foo foo', 'foo foo', 'bar foo', 'bar foo'],
205        \           getline(1, '$'))
206
207  bwipe!
208endfunc
209
210" Test substitute 'n' flag (report number of matches, do not substitute).
211func Test_substitute_flag_n()
212  new
213  let lines = ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo']
214  call setline(1, lines)
215
216  call assert_equal("\n3 matches on 3 lines", execute('2,4s/foo/bar/n'))
217  call assert_equal("\n6 matches on 3 lines", execute('2,4s/foo/bar/gn'))
218
219  " c flag (confirm) should be ignored when using n flag.
220  call assert_equal("\n3 matches on 3 lines", execute('2,4s/foo/bar/nc'))
221
222  " No substitution should have been done.
223  call assert_equal(lines, getline(1, '$'))
224
225  %delete _
226  call setline(1, ['A', 'Bar', 'Baz'])
227  call assert_equal("\n1 match on 1 line", execute('s/\nB\@=//gn'))
228
229  bwipe!
230endfunc
231
232func Test_substitute_errors()
233  new
234  call setline(1, 'foobar')
235
236  call assert_fails('s/FOO/bar/', 'E486:')
237  call assert_fails('s/foo/bar/@', 'E488:')
238  call assert_fails('s/\(/bar/', 'E54:')
239  call assert_fails('s afooabara', 'E146:')
240  call assert_fails('s\\a', 'E10:')
241
242  setl nomodifiable
243  call assert_fails('s/foo/bar/', 'E21:')
244
245  call assert_fails("let s=substitute([], 'a', 'A', 'g')", 'E730:')
246  call assert_fails("let s=substitute('abcda', [], 'A', 'g')", 'E730:')
247  call assert_fails("let s=substitute('abcda', 'a', [], 'g')", 'E730:')
248  call assert_fails("let s=substitute('abcda', 'a', 'A', [])", 'E730:')
249
250  bwipe!
251endfunc
252
253" Test for *sub-replace-special* and *sub-replace-expression* on substitute().
254func Test_sub_replace_1()
255  " Run the tests with 'magic' on
256  set magic
257  set cpo&
258  call assert_equal('AA', substitute('A', 'A', '&&', ''))
259  call assert_equal('&', substitute('B', 'B', '\&', ''))
260  call assert_equal('C123456789987654321', substitute('C123456789', 'C\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)', '\0\9\8\7\6\5\4\3\2\1', ''))
261  call assert_equal('d', substitute('D', 'D', 'd', ''))
262  call assert_equal('~', substitute('E', 'E', '~', ''))
263  call assert_equal('~', substitute('F', 'F', '\~', ''))
264  call assert_equal('Gg', substitute('G', 'G', '\ugg', ''))
265  call assert_equal('Hh', substitute('H', 'H', '\Uh\Eh', ''))
266  call assert_equal('iI', substitute('I', 'I', '\lII', ''))
267  call assert_equal('jJ', substitute('J', 'J', '\LJ\EJ', ''))
268  call assert_equal('Kk', substitute('K', 'K', '\Uk\ek', ''))
269  call assert_equal("l\<C-V>\<C-M>l",
270			\ substitute('lLl', 'L', "\<C-V>\<C-M>", ''))
271  call assert_equal("m\<C-M>m", substitute('mMm', 'M', '\r', ''))
272  call assert_equal("n\<C-V>\<C-M>n",
273			\ substitute('nNn', 'N', "\\\<C-V>\<C-M>", ''))
274  call assert_equal("o\no", substitute('oOo', 'O', '\n', ''))
275  call assert_equal("p\<C-H>p", substitute('pPp', 'P', '\b', ''))
276  call assert_equal("q\tq", substitute('qQq', 'Q', '\t', ''))
277  call assert_equal('r\r', substitute('rRr', 'R', '\\', ''))
278  call assert_equal('scs', substitute('sSs', 'S', '\c', ''))
279  call assert_equal("u\nu", substitute('uUu', 'U', "\n", ''))
280  call assert_equal("v\<C-H>v", substitute('vVv', 'V', "\b", ''))
281  call assert_equal("w\\w", substitute('wWw', 'W', "\\", ''))
282  call assert_equal("x\<C-M>x", substitute('xXx', 'X', "\r", ''))
283  call assert_equal("YyyY", substitute('Y', 'Y', '\L\uyYy\l\EY', ''))
284  call assert_equal("zZZz", substitute('Z', 'Z', '\U\lZzZ\u\Ez', ''))
285  " \v or \V after $
286  call assert_equal('abxx', substitute('abcd', 'xy$\v|cd$', 'xx', ''))
287  call assert_equal('abxx', substitute('abcd', 'xy$\V\|cd\$', 'xx', ''))
288endfunc
289
290func Test_sub_replace_2()
291  " Run the tests with 'magic' off
292  set nomagic
293  set cpo&
294  call assert_equal('AA', substitute('A', 'A', '&&', ''))
295  call assert_equal('&', substitute('B', 'B', '\&', ''))
296  call assert_equal('C123456789987654321', substitute('C123456789', 'C\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)', '\0\9\8\7\6\5\4\3\2\1', ''))
297  call assert_equal('d', substitute('D', 'D', 'd', ''))
298  call assert_equal('~', substitute('E', 'E', '~', ''))
299  call assert_equal('~', substitute('F', 'F', '\~', ''))
300  call assert_equal('Gg', substitute('G', 'G', '\ugg', ''))
301  call assert_equal('Hh', substitute('H', 'H', '\Uh\Eh', ''))
302  call assert_equal('iI', substitute('I', 'I', '\lII', ''))
303  call assert_equal('jJ', substitute('J', 'J', '\LJ\EJ', ''))
304  call assert_equal('Kk', substitute('K', 'K', '\Uk\ek', ''))
305  call assert_equal("l\<C-V>\<C-M>l",
306			\ substitute('lLl', 'L', "\<C-V>\<C-M>", ''))
307  call assert_equal("m\<C-M>m", substitute('mMm', 'M', '\r', ''))
308  call assert_equal("n\<C-V>\<C-M>n",
309			\ substitute('nNn', 'N', "\\\<C-V>\<C-M>", ''))
310  call assert_equal("o\no", substitute('oOo', 'O', '\n', ''))
311  call assert_equal("p\<C-H>p", substitute('pPp', 'P', '\b', ''))
312  call assert_equal("q\tq", substitute('qQq', 'Q', '\t', ''))
313  call assert_equal('r\r', substitute('rRr', 'R', '\\', ''))
314  call assert_equal('scs', substitute('sSs', 'S', '\c', ''))
315  call assert_equal("t\<C-M>t", substitute('tTt', 'T', "\r", ''))
316  call assert_equal("u\nu", substitute('uUu', 'U', "\n", ''))
317  call assert_equal("v\<C-H>v", substitute('vVv', 'V', "\b", ''))
318  call assert_equal('w\w', substitute('wWw', 'W', "\\", ''))
319  call assert_equal('XxxX', substitute('X', 'X', '\L\uxXx\l\EX', ''))
320  call assert_equal('yYYy', substitute('Y', 'Y', '\U\lYyY\u\Ey', ''))
321endfunc
322
323func Test_sub_replace_3()
324  set magic&
325  set cpo&
326  call assert_equal('a\a', substitute('aAa', 'A', '\="\\"', ''))
327  call assert_equal('b\\b', substitute('bBb', 'B', '\="\\\\"', ''))
328  call assert_equal("c\rc", substitute('cCc', 'C', "\\=\"\r\"", ''))
329  call assert_equal("d\\\rd", substitute('dDd', 'D', "\\=\"\\\\\r\"", ''))
330  call assert_equal("e\\\\\re", substitute('eEe', 'E', "\\=\"\\\\\\\\\r\"", ''))
331  call assert_equal('f\rf', substitute('fFf', 'F', '\="\\r"', ''))
332  call assert_equal('j\nj', substitute('jJj', 'J', '\="\\n"', ''))
333  call assert_equal("k\<C-M>k", substitute('kKk', 'K', '\="\r"', ''))
334  call assert_equal("l\nl", substitute('lLl', 'L', '\="\n"', ''))
335endfunc
336
337" Test for submatch() on substitute().
338func Test_sub_replace_4()
339  set magic&
340  set cpo&
341  call assert_equal('a\a', substitute('aAa', 'A',
342		\ '\=substitute(submatch(0), ".", "\\", "")', ''))
343  call assert_equal('b\b', substitute('bBb', 'B',
344		\ '\=substitute(submatch(0), ".", "\\\\", "")', ''))
345  call assert_equal("c\<C-V>\<C-M>c", substitute('cCc', 'C', '\=substitute(submatch(0), ".", "\<C-V>\<C-M>", "")', ''))
346  call assert_equal("d\<C-V>\<C-M>d", substitute('dDd', 'D', '\=substitute(submatch(0), ".", "\\\<C-V>\<C-M>", "")', ''))
347  call assert_equal("e\\\<C-V>\<C-M>e", substitute('eEe', 'E', '\=substitute(submatch(0), ".", "\\\\\<C-V>\<C-M>", "")', ''))
348  call assert_equal("f\<C-M>f", substitute('fFf', 'F', '\=substitute(submatch(0), ".", "\\r", "")', ''))
349  call assert_equal("j\nj", substitute('jJj', 'J', '\=substitute(submatch(0), ".", "\\n", "")', ''))
350  call assert_equal("k\rk", substitute('kKk', 'K', '\=substitute(submatch(0), ".", "\r", "")', ''))
351  call assert_equal("l\nl", substitute('lLl', 'L', '\=substitute(submatch(0), ".", "\n", "")', ''))
352endfunc
353
354func Test_sub_replace_5()
355  set magic&
356  set cpo&
357  call assert_equal('A123456789987654321', substitute('A123456789',
358		\ 'A\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)',
359		\ '\=submatch(0) . submatch(9) . submatch(8) . ' .
360		\ 'submatch(7) . submatch(6) . submatch(5) . ' .
361		\ 'submatch(4) . submatch(3) . submatch(2) . submatch(1)',
362		\ ''))
363   call assert_equal("[['A123456789'], ['9'], ['8'], ['7'], ['6'], " .
364		\ "['5'], ['4'], ['3'], ['2'], ['1']]",
365		\ substitute('A123456789',
366		\ 'A\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)',
367		\ '\=string([submatch(0, 1), submatch(9, 1), ' .
368		\ 'submatch(8, 1), 7->submatch(1), submatch(6, 1), ' .
369		\ 'submatch(5, 1), submatch(4, 1), submatch(3, 1), ' .
370		\ 'submatch(2, 1), submatch(1, 1)])',
371		\ ''))
372endfunc
373
374func Test_sub_replace_6()
375  set magic&
376  set cpo+=/
377  call assert_equal('a', substitute('A', 'A', 'a', ''))
378  call assert_equal('%', substitute('B', 'B', '%', ''))
379  set cpo-=/
380  call assert_equal('c', substitute('C', 'C', 'c', ''))
381  call assert_equal('%', substitute('D', 'D', '%', ''))
382endfunc
383
384func Test_sub_replace_7()
385  set magic&
386  set cpo&
387  call assert_equal('AA', substitute('AA', 'A.', '\=submatch(0)', ''))
388  call assert_equal("B\nB", substitute("B\nB", 'B.', '\=submatch(0)', ''))
389  call assert_equal("['B\n']B", substitute("B\nB", 'B.', '\=string(submatch(0, 1))', ''))
390  call assert_equal('-abab', substitute('-bb', '\zeb', 'a', 'g'))
391  call assert_equal('c-cbcbc', substitute('-bb', '\ze', 'c', 'g'))
392endfunc
393
394" Test for *:s%* on :substitute.
395func Test_sub_replace_8()
396  new
397  set magic&
398  set cpo&
399  $put =',,X'
400  s/\(^\|,\)\ze\(,\|X\)/\1N/g
401  call assert_equal('N,,NX', getline("$"))
402  $put =',,Y'
403  let cmd = ':s/\(^\|,\)\ze\(,\|Y\)/\1N/gc'
404  call feedkeys(cmd . "\<CR>a", "xt")
405  call assert_equal('N,,NY', getline("$"))
406  :$put =',,Z'
407  let cmd = ':s/\(^\|,\)\ze\(,\|Z\)/\1N/gc'
408  call feedkeys(cmd . "\<CR>yy", "xt")
409  call assert_equal('N,,NZ', getline("$"))
410  enew! | close
411endfunc
412
413func Test_sub_replace_9()
414  new
415  set magic&
416  set cpo&
417  $put ='xxx'
418  call feedkeys(":s/x/X/gc\<CR>yyq", "xt")
419  call assert_equal('XXx', getline("$"))
420  enew! | close
421endfunc
422
423func Test_sub_replace_10()
424   set magic&
425   set cpo&
426   call assert_equal('a1a2a3a', substitute('123', '\zs', 'a', 'g'))
427   call assert_equal('aaa', substitute('123', '\zs.', 'a', 'g'))
428   call assert_equal('1a2a3a', substitute('123', '.\zs', 'a', 'g'))
429   call assert_equal('a1a2a3a', substitute('123', '\ze', 'a', 'g'))
430   call assert_equal('a1a2a3', substitute('123', '\ze.', 'a', 'g'))
431   call assert_equal('aaa', substitute('123', '.\ze', 'a', 'g'))
432   call assert_equal('aa2a3a', substitute('123', '1\|\ze', 'a', 'g'))
433   call assert_equal('1aaa', substitute('123', '1\zs\|[23]', 'a', 'g'))
434endfunc
435
436func SubReplacer(text, submatches)
437  return a:text .. a:submatches[0] .. a:text
438endfunc
439func SubReplacer20(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, submatches)
440  return a:t3 .. a:submatches[0] .. a:t11
441endfunc
442
443func Test_substitute_partial()
444   call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacer', ['foo']), 'g'))
445
446   " 19 arguments plus one is just OK
447   let Replacer = function('SubReplacer20', repeat(['foo'], 19))
448   call assert_equal('1foo2foo3', substitute('123', '2', Replacer, 'g'))
449
450   " 20 arguments plus one is too many
451   let Replacer = function('SubReplacer20', repeat(['foo'], 20))
452   call assert_fails("call substitute('123', '2', Replacer, 'g')", 'E118')
453endfunc
454
455" Tests for *sub-replace-special* and *sub-replace-expression* on :substitute.
456
457" Execute a list of :substitute command tests
458func Run_SubCmd_Tests(tests)
459  enew!
460  for t in a:tests
461    let start = line('.') + 1
462    let end = start + len(t[2]) - 1
463    " TODO: why is there a one second delay the first time we get here?
464    exe "normal o" . t[0]
465    call cursor(start, 1)
466    exe t[1]
467    call assert_equal(t[2], getline(start, end), t[1])
468  endfor
469  enew!
470endfunc
471
472func Test_sub_cmd_1()
473  set magic
474  set cpo&
475
476  " List entry format: [input, cmd, output]
477  let tests = [['A', 's/A/&&/', ['AA']],
478	      \ ['B', 's/B/\&/', ['&']],
479	      \ ['C123456789', 's/C\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\0\9\8\7\6\5\4\3\2\1/', ['C123456789987654321']],
480	      \ ['D', 's/D/d/', ['d']],
481	      \ ['E', 's/E/~/', ['d']],
482	      \ ['F', 's/F/\~/', ['~']],
483	      \ ['G', 's/G/\ugg/', ['Gg']],
484	      \ ['H', 's/H/\Uh\Eh/', ['Hh']],
485	      \ ['I', 's/I/\lII/', ['iI']],
486	      \ ['J', 's/J/\LJ\EJ/', ['jJ']],
487	      \ ['K', 's/K/\Uk\ek/', ['Kk']],
488	      \ ['lLl', "s/L/\<C-V>\<C-M>/", ["l\<C-V>", 'l']],
489	      \ ['mMm', 's/M/\r/', ['m', 'm']],
490	      \ ['nNn', "s/N/\\\<C-V>\<C-M>/", ["n\<C-V>", 'n']],
491	      \ ['oOo', 's/O/\n/', ["o\no"]],
492	      \ ['pPp', 's/P/\b/', ["p\<C-H>p"]],
493	      \ ['qQq', 's/Q/\t/', ["q\tq"]],
494	      \ ['rRr', 's/R/\\/', ['r\r']],
495	      \ ['sSs', 's/S/\c/', ['scs']],
496	      \ ['tTt', "s/T/\<C-V>\<C-J>/", ["t\<C-V>\<C-J>t"]],
497	      \ ['U', 's/U/\L\uuUu\l\EU/', ['UuuU']],
498	      \ ['V', 's/V/\U\lVvV\u\Ev/', ['vVVv']]
499	      \ ]
500  call Run_SubCmd_Tests(tests)
501endfunc
502
503func Test_sub_cmd_2()
504  set nomagic
505  set cpo&
506
507  " List entry format: [input, cmd, output]
508  let tests = [['A', 's/A/&&/', ['&&']],
509	      \ ['B', 's/B/\&/', ['B']],
510	      \ ['C123456789', 's/\mC\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\0\9\8\7\6\5\4\3\2\1/', ['C123456789987654321']],
511	      \ ['D', 's/D/d/', ['d']],
512	      \ ['E', 's/E/~/', ['~']],
513	      \ ['F', 's/F/\~/', ['~']],
514	      \ ['G', 's/G/\ugg/', ['Gg']],
515	      \ ['H', 's/H/\Uh\Eh/', ['Hh']],
516	      \ ['I', 's/I/\lII/', ['iI']],
517	      \ ['J', 's/J/\LJ\EJ/', ['jJ']],
518	      \ ['K', 's/K/\Uk\ek/', ['Kk']],
519	      \ ['lLl', "s/L/\<C-V>\<C-M>/", ["l\<C-V>", 'l']],
520	      \ ['mMm', 's/M/\r/', ['m', 'm']],
521	      \ ['nNn', "s/N/\\\<C-V>\<C-M>/", ["n\<C-V>", 'n']],
522	      \ ['oOo', 's/O/\n/', ["o\no"]],
523	      \ ['pPp', 's/P/\b/', ["p\<C-H>p"]],
524	      \ ['qQq', 's/Q/\t/', ["q\tq"]],
525	      \ ['rRr', 's/R/\\/', ['r\r']],
526	      \ ['sSs', 's/S/\c/', ['scs']],
527	      \ ['tTt', "s/T/\<C-V>\<C-J>/", ["t\<C-V>\<C-J>t"]],
528	      \ ['U', 's/U/\L\uuUu\l\EU/', ['UuuU']],
529	      \ ['V', 's/V/\U\lVvV\u\Ev/', ['vVVv']]
530	      \ ]
531  call Run_SubCmd_Tests(tests)
532endfunc
533
534func Test_sub_cmd_3()
535  set nomagic
536  set cpo&
537
538  " List entry format: [input, cmd, output]
539  let tests = [['aAa', "s/A/\\='\\'/", ['a\a']],
540	      \ ['bBb', "s/B/\\='\\\\'/", ['b\\b']],
541	      \ ['cCc', "s/C/\\='\<C-V>\<C-M>'/", ["c\<C-V>", 'c']],
542	      \ ['dDd', "s/D/\\='\\\<C-V>\<C-M>'/", ["d\\\<C-V>", 'd']],
543	      \ ['eEe', "s/E/\\='\\\\\<C-V>\<C-M>'/", ["e\\\\\<C-V>", 'e']],
544	      \ ['fFf', "s/F/\\='\r'/", ['f', 'f']],
545	      \ ['gGg', "s/G/\\='\<C-V>\<C-J>'/", ["g\<C-V>", 'g']],
546	      \ ['hHh', "s/H/\\='\\\<C-V>\<C-J>'/", ["h\\\<C-V>", 'h']],
547	      \ ['iIi', "s/I/\\='\\\\\<C-V>\<C-J>'/", ["i\\\\\<C-V>", 'i']],
548	      \ ['jJj', "s/J/\\='\n'/", ['j', 'j']],
549	      \ ['kKk', 's/K/\="\r"/', ['k', 'k']],
550	      \ ['lLl', 's/L/\="\n"/', ['l', 'l']]
551	      \ ]
552  call Run_SubCmd_Tests(tests)
553endfunc
554
555" Test for submatch() on :substitute.
556func Test_sub_cmd_4()
557  set magic&
558  set cpo&
559
560  " List entry format: [input, cmd, output]
561  let tests = [ ['aAa', "s/A/\\=substitute(submatch(0), '.', '\\', '')/",
562	      \				['a\a']],
563	      \ ['bBb', "s/B/\\=substitute(submatch(0), '.', '\\', '')/",
564	      \				['b\b']],
565	      \ ['cCc', "s/C/\\=substitute(submatch(0), '.', '\<C-V>\<C-M>', '')/",
566	      \				["c\<C-V>", 'c']],
567	      \ ['dDd', "s/D/\\=substitute(submatch(0), '.', '\\\<C-V>\<C-M>', '')/",
568	      \				["d\<C-V>", 'd']],
569	      \ ['eEe', "s/E/\\=substitute(submatch(0), '.', '\\\\\<C-V>\<C-M>', '')/",
570	      \				["e\\\<C-V>", 'e']],
571	      \ ['fFf', "s/F/\\=substitute(submatch(0), '.', '\\r', '')/",
572	      \				['f', 'f']],
573	      \ ['gGg', 's/G/\=substitute(submatch(0), ".", "\<C-V>\<C-J>", "")/',
574	      \				["g\<C-V>", 'g']],
575	      \ ['hHh', 's/H/\=substitute(submatch(0), ".", "\\\<C-V>\<C-J>", "")/',
576	      \				["h\<C-V>", 'h']],
577	      \ ['iIi', 's/I/\=substitute(submatch(0), ".", "\\\\\<C-V>\<C-J>", "")/',
578	      \				["i\\\<C-V>", 'i']],
579	      \ ['jJj', "s/J/\\=substitute(submatch(0), '.', '\\n', '')/",
580	      \				['j', 'j']],
581	      \ ['kKk', "s/K/\\=substitute(submatch(0), '.', '\\r', '')/",
582	      \				['k', 'k']],
583	      \ ['lLl', "s/L/\\=substitute(submatch(0), '.', '\\n', '')/",
584	      \				['l', 'l']],
585	      \ ]
586  call Run_SubCmd_Tests(tests)
587endfunc
588
589func Test_sub_cmd_5()
590  set magic&
591  set cpo&
592
593  " List entry format: [input, cmd, output]
594  let tests = [ ['A123456789', 's/A\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\=submatch(0) . submatch(9) . submatch(8) . submatch(7) . submatch(6) . submatch(5) . submatch(4) . submatch(3) . submatch(2) . submatch(1)/', ['A123456789987654321']],
595	      \ ['B123456789', 's/B\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\=string([submatch(0, 1), submatch(9, 1), submatch(8, 1), submatch(7, 1), submatch(6, 1), submatch(5, 1), submatch(4, 1), submatch(3, 1), submatch(2, 1), submatch(1, 1)])/', ["[['B123456789'], ['9'], ['8'], ['7'], ['6'], ['5'], ['4'], ['3'], ['2'], ['1']]"]],
596	      \ ]
597  call Run_SubCmd_Tests(tests)
598endfunc
599
600" Test for *:s%* on :substitute.
601func Test_sub_cmd_6()
602  set magic&
603  set cpo+=/
604
605  " List entry format: [input, cmd, output]
606  let tests = [ ['A', 's/A/a/', ['a']],
607	      \ ['B', 's/B/%/', ['a']],
608	      \ ]
609  call Run_SubCmd_Tests(tests)
610
611  set cpo-=/
612  let tests = [ ['C', 's/C/c/', ['c']],
613	      \ ['D', 's/D/%/', ['%']],
614	      \ ]
615  call Run_SubCmd_Tests(tests)
616
617  set cpo&
618endfunc
619
620" Test for :s replacing \n with  line break.
621func Test_sub_cmd_7()
622  set magic&
623  set cpo&
624
625  " List entry format: [input, cmd, output]
626  let tests = [ ["A\<C-V>\<C-M>A", 's/A./\=submatch(0)/', ['A', 'A']],
627	      \ ["B\<C-V>\<C-J>B", 's/B./\=submatch(0)/', ['B', 'B']],
628	      \ ["C\<C-V>\<C-J>C", 's/C./\=strtrans(string(submatch(0, 1)))/', [strtrans("['C\<C-J>']C")]],
629	      \ ["D\<C-V>\<C-J>\nD", 's/D.\nD/\=strtrans(string(submatch(0, 1)))/', [strtrans("['D\<C-J>', 'D']")]],
630	      \ ["E\<C-V>\<C-J>\n\<C-V>\<C-J>\n\<C-V>\<C-J>\n\<C-V>\<C-J>\n\<C-V>\<C-J>E", 's/E\_.\{-}E/\=strtrans(string(submatch(0, 1)))/', [strtrans("['E\<C-J>', '\<C-J>', '\<C-J>', '\<C-J>', '\<C-J>E']")]],
631	      \ ]
632  call Run_SubCmd_Tests(tests)
633
634  exe "normal oQ\nQ\<Esc>k"
635  call assert_fails('s/Q[^\n]Q/\=submatch(0)."foobar"/', 'E486')
636  enew!
637endfunc
638
639func TitleString()
640  let check = 'foo' =~ 'bar'
641  return ""
642endfunc
643
644func Test_sub_cmd_8()
645  set titlestring=%{TitleString()}
646
647  enew!
648  call append(0, ['', 'test_one', 'test_two'])
649  call cursor(1,1)
650  /^test_one/s/.*/\="foo\nbar"/
651  call assert_equal('foo', getline(2))
652  call assert_equal('bar', getline(3))
653  call feedkeys(':/^test_two/s/.*/\="foo\nbar"/c', "t")
654  call feedkeys("\<CR>y", "xt")
655  call assert_equal('foo', getline(4))
656  call assert_equal('bar', getline(5))
657
658  enew!
659  set titlestring&
660endfunc
661
662func Test_sub_cmd_9()
663  new
664  let input = ['1 aaa', '2 aaa', '3 aaa']
665  call setline(1, input)
666  func Foo()
667    return submatch(0)
668  endfunc
669  %s/aaa/\=Foo()/gn
670  call assert_equal(input, getline(1, '$'))
671  call assert_equal(1, &modifiable)
672
673  delfunc Foo
674  bw!
675endfunc
676
677func Test_nocatch_sub_failure_handling()
678  " normal error results in all replacements
679  func Foo()
680    foobar
681  endfunc
682  new
683  call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
684  %s/aaa/\=Foo()/g
685  call assert_equal(['1 0', '2 0', '3 0'], getline(1, 3))
686
687  " Trow without try-catch causes abort after the first line.
688  " We cannot test this, since it would stop executing the test script.
689
690  " try/catch does not result in any changes
691  func! Foo()
692    throw 'error'
693  endfunc
694  call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
695  let error_caught = 0
696  try
697    %s/aaa/\=Foo()/g
698  catch
699    let error_caught = 1
700  endtry
701  call assert_equal(1, error_caught)
702  call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3))
703
704  " Same, but using "n" flag so that "sandbox" gets set
705  call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
706  let error_caught = 0
707  try
708    %s/aaa/\=Foo()/gn
709  catch
710    let error_caught = 1
711  endtry
712  call assert_equal(1, error_caught)
713  call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3))
714
715  delfunc Foo
716  bwipe!
717endfunc
718
719" Test ":s/pat/sub/" with different ~s in sub.
720func Test_replace_with_tilde()
721  new
722  " Set the last replace string to empty
723  s/^$//
724  call append(0, ['- Bug in "vPPPP" on this text:'])
725  normal gg
726  s/u/~u~/
727  call assert_equal('- Bug in "vPPPP" on this text:', getline(1))
728  s/i/~u~/
729  call assert_equal('- Bug uuun "vPPPP" on this text:', getline(1))
730  s/o/~~~/
731  call assert_equal('- Bug uuun "vPPPP" uuuuuuuuun this text:', getline(1))
732  close!
733endfunc
734
735func Test_replace_keeppatterns()
736  new
737  a
738foobar
739
740substitute foo asdf
741
742one two
743.
744
745  normal gg
746  /^substitute
747  s/foo/bar/
748  call assert_equal('foo', @/)
749  call assert_equal('substitute bar asdf', getline('.'))
750
751  /^substitute
752  keeppatterns s/asdf/xyz/
753  call assert_equal('^substitute', @/)
754  call assert_equal('substitute bar xyz', getline('.'))
755
756  exe "normal /bar /e\<CR>"
757  call assert_equal(15, col('.'))
758  normal -
759  keeppatterns /xyz
760  call assert_equal('bar ', @/)
761  call assert_equal('substitute bar xyz', getline('.'))
762  exe "normal 0dn"
763  call assert_equal('xyz', getline('.'))
764
765  close!
766endfunc
767
768func Test_sub_beyond_end()
769  new
770  call setline(1, '#')
771  let @/ = '^#\n\zs'
772  s///e
773  call assert_equal('#', getline(1))
774  bwipe!
775endfunc
776
777" Test for repeating last substitution using :~ and :&r
778func Test_repeat_last_sub()
779  new
780  call setline(1, ['blue green yellow orange white'])
781  s/blue/red/
782  let @/ = 'yellow'
783  ~
784  let @/ = 'white'
785  :&r
786  let @/ = 'green'
787  s//gray
788  call assert_equal('red gray red orange red', getline(1))
789  close!
790endfunc
791
792" Test for Vi compatible substitution:
793"     \/{string}/, \?{string}? and \&{string}&
794func Test_sub_vi_compatibility()
795  new
796  call setline(1, ['blue green yellow orange blue'])
797  let @/ = 'orange'
798  s\/white/
799  let @/ = 'blue'
800  s\?amber?
801  let @/ = 'white'
802  s\&green&
803  call assert_equal('amber green yellow white green', getline(1))
804  close!
805endfunc
806
807" Test for substitute with the new text longer than the original text
808func Test_sub_expand_text()
809  new
810  call setline(1, 'abcabcabcabcabcabcabcabc')
811  s/b/\=repeat('B', 10)/g
812  call assert_equal(repeat('aBBBBBBBBBBc', 8), getline(1))
813  close!
814endfunc
815
816" Test for command failures when the last substitute pattern is not set.
817func Test_sub_with_no_last_pat()
818  let lines =<< trim [SCRIPT]
819    call assert_fails('~', 'E33:')
820    call assert_fails('s//abc/g', 'E35:')
821    call assert_fails('s\/bar', 'E35:')
822    call assert_fails('s\&bar&', 'E33:')
823    call writefile(v:errors, 'Xresult')
824    qall!
825  [SCRIPT]
826  call writefile(lines, 'Xscript')
827  if RunVim([], [], '--clean -S Xscript')
828    call assert_equal([], readfile('Xresult'))
829  endif
830
831  let lines =<< trim [SCRIPT]
832    set cpo+=/
833    call assert_fails('s/abc/%/', 'E33:')
834    call writefile(v:errors, 'Xresult')
835    qall!
836  [SCRIPT]
837  call writefile(lines, 'Xscript')
838  if RunVim([], [], '--clean -S Xscript')
839    call assert_equal([], readfile('Xresult'))
840  endif
841
842  call delete('Xscript')
843  call delete('Xresult')
844endfunc
845
846func Test_substitute()
847  call assert_equal('a1a2a3a', substitute('123', '\zs', 'a', 'g'))
848  " Substitute with special keys
849  call assert_equal("a\<End>c", substitute('abc', "a.c", "a\<End>c", ''))
850endfunc
851
852func Test_substitute_expr()
853  let g:val = 'XXX'
854  call assert_equal('XXX', substitute('yyy', 'y*', '\=g:val', ''))
855  call assert_equal('XXX', substitute('yyy', 'y*', {-> g:val}, ''))
856  call assert_equal("-\u1b \uf2-", substitute("-%1b %f2-", '%\(\x\x\)',
857			   \ '\=nr2char("0x" . submatch(1))', 'g'))
858  call assert_equal("-\u1b \uf2-", substitute("-%1b %f2-", '%\(\x\x\)',
859			   \ {-> nr2char("0x" . submatch(1))}, 'g'))
860
861  call assert_equal('231', substitute('123', '\(.\)\(.\)\(.\)',
862	\ {-> submatch(2) . submatch(3) . submatch(1)}, ''))
863
864  func Recurse()
865    return substitute('yyy', 'y\(.\)y', {-> submatch(1)}, '')
866  endfunc
867  " recursive call works
868  call assert_equal('-y-x-', substitute('xxx', 'x\(.\)x', {-> '-' . Recurse() . '-' . submatch(1) . '-'}, ''))
869
870  call assert_fails("let s=submatch([])", 'E745:')
871  call assert_fails("let s=submatch(2, [])", 'E745:')
872endfunc
873
874func Test_invalid_submatch()
875  " This was causing invalid memory access in Vim-7.4.2232 and older
876  call assert_fails("call substitute('x', '.', {-> submatch(10)}, '')", 'E935:')
877  call assert_fails('eval submatch(-1)', 'E935:')
878  call assert_equal('', submatch(0))
879  call assert_equal('', submatch(1))
880  call assert_equal([], submatch(0, 1))
881  call assert_equal([], submatch(1, 1))
882endfunc
883
884func Test_substitute_expr_arg()
885  call assert_equal('123456789-123456789=', substitute('123456789',
886	\ '\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)',
887	\ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))
888
889  call assert_equal('123456-123456=789', substitute('123456789',
890	\ '\(.\)\(.\)\(.\)\(a*\)\(n*\)\(.\)\(.\)\(.\)\(x*\)',
891	\ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))
892
893  call assert_equal('123456789-123456789x=', substitute('123456789',
894	\ '\(.\)\(.\)\(.*\)',
895	\ {m -> m[0] . '-' . m[1] . m[2] . m[3] . 'x' . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))
896
897  call assert_fails("call substitute('xxx', '.', {m -> string(add(m, 'x'))}, '')", 'E742:')
898  call assert_fails("call substitute('xxx', '.', {m -> string(insert(m, 'x'))}, '')", 'E742:')
899  call assert_fails("call substitute('xxx', '.', {m -> string(extend(m, ['x']))}, '')", 'E742:')
900  call assert_fails("call substitute('xxx', '.', {m -> string(remove(m, 1))}, '')", 'E742:')
901endfunc
902
903" Test for using a function to supply the substitute string
904func Test_substitute_using_func()
905  func Xfunc()
906    return '1234'
907  endfunc
908  call assert_equal('a1234f', substitute('abcdef', 'b..e',
909        \ function("Xfunc"), ''))
910  delfunc Xfunc
911endfunc
912
913" Test for using submatch() with a multiline match
914func Test_substitute_multiline_submatch()
915  new
916  call setline(1, ['line1', 'line2', 'line3', 'line4'])
917  %s/^line1\(\_.\+\)line4$/\=submatch(1)/
918  call assert_equal(['', 'line2', 'line3', ''], getline(1, '$'))
919  close!
920endfunc
921
922" vim: shiftwidth=2 sts=2 expandtab
923