blob: af450d595b4fb4fe02dc235657b938546c8091f9 [file] [log] [blame]
Yegappan Lakshmanan5e877ba2022-03-25 21:19:26 +00001" Tests for the substitute (:s) command
Bram Moolenaarcd055da2016-09-02 19:50:48 +02002
Bram Moolenaar9f6277b2020-02-11 22:04:02 +01003source shared.vim
Bram Moolenaar7a2217b2021-06-06 12:33:49 +02004source check.vim
Bram Moolenaara04f4572022-09-13 13:45:26 +01005source screendump.vim
Bram Moolenaar9f6277b2020-02-11 22:04:02 +01006
Bram Moolenaar1e115362019-01-09 23:01:02 +01007func Test_multiline_subst()
Bram Moolenaarcd055da2016-09-02 19:50:48 +02008 enew!
9 call append(0, ["1 aa",
10 \ "bb",
11 \ "cc",
12 \ "2 dd",
13 \ "ee",
14 \ "3 ef",
15 \ "gh",
16 \ "4 ij",
17 \ "5 a8",
18 \ "8b c9",
19 \ "9d",
20 \ "6 e7",
21 \ "77f",
22 \ "xxxxx"])
23
24 1
25 " test if replacing a line break works with a back reference
26 /^1/,/^2/s/\n\(.\)/ \1/
27 " test if inserting a line break works with a back reference
28 /^3/,/^4/s/\(.\)$/\r\1/
29 " test if replacing a line break with another line break works
30 /^5/,/^6/s/\(\_d\{3}\)/x\1x/
31 call assert_equal('1 aa bb cc 2 dd ee', getline(1))
32 call assert_equal('3 e', getline(2))
33 call assert_equal('f', getline(3))
34 call assert_equal('g', getline(4))
35 call assert_equal('h', getline(5))
36 call assert_equal('4 i', getline(6))
37 call assert_equal('j', getline(7))
38 call assert_equal('5 ax8', getline(8))
39 call assert_equal('8xb cx9', getline(9))
40 call assert_equal('9xd', getline(10))
41 call assert_equal('6 ex7', getline(11))
42 call assert_equal('7x7f', getline(12))
43 call assert_equal('xxxxx', getline(13))
44 enew!
Bram Moolenaar1e115362019-01-09 23:01:02 +010045endfunc
Bram Moolenaar8c50d502017-02-17 18:28:24 +010046
Bram Moolenaar1e115362019-01-09 23:01:02 +010047func Test_substitute_variants()
Bram Moolenaar8c50d502017-02-17 18:28:24 +010048 " Validate that all the 2-/3-letter variants which embed the flags into the
49 " command name actually work.
50 enew!
51 let ln = 'Testing string'
52 let variants = [
53 \ { 'cmd': ':s/Test/test/c', 'exp': 'testing string', 'prompt': 'y' },
54 \ { 'cmd': ':s/foo/bar/ce', 'exp': ln },
55 \ { 'cmd': ':s/t/r/cg', 'exp': 'Tesring srring', 'prompt': 'a' },
56 \ { 'cmd': ':s/t/r/ci', 'exp': 'resting string', 'prompt': 'y' },
57 \ { 'cmd': ':s/t/r/cI', 'exp': 'Tesring string', 'prompt': 'y' },
Bram Moolenaarea3db912020-02-02 15:32:13 +010058 \ { 'cmd': ':s/t/r/c', 'exp': 'Testing string', 'prompt': 'n' },
Bram Moolenaar8c50d502017-02-17 18:28:24 +010059 \ { 'cmd': ':s/t/r/cn', 'exp': ln },
60 \ { 'cmd': ':s/t/r/cp', 'exp': 'Tesring string', 'prompt': 'y' },
61 \ { 'cmd': ':s/t/r/cl', 'exp': 'Tesring string', 'prompt': 'y' },
62 \ { 'cmd': ':s/t/r/gc', 'exp': 'Tesring srring', 'prompt': 'a' },
Bram Moolenaarea3db912020-02-02 15:32:13 +010063 \ { 'cmd': ':s/i/I/gc', 'exp': 'TestIng string', 'prompt': 'l' },
Bram Moolenaar8c50d502017-02-17 18:28:24 +010064 \ { 'cmd': ':s/foo/bar/ge', 'exp': ln },
65 \ { 'cmd': ':s/t/r/g', 'exp': 'Tesring srring' },
66 \ { 'cmd': ':s/t/r/gi', 'exp': 'resring srring' },
67 \ { 'cmd': ':s/t/r/gI', 'exp': 'Tesring srring' },
68 \ { 'cmd': ':s/t/r/gn', 'exp': ln },
69 \ { 'cmd': ':s/t/r/gp', 'exp': 'Tesring srring' },
70 \ { 'cmd': ':s/t/r/gl', 'exp': 'Tesring srring' },
71 \ { 'cmd': ':s//r/gr', 'exp': 'Testr strr' },
72 \ { 'cmd': ':s/t/r/ic', 'exp': 'resting string', 'prompt': 'y' },
73 \ { 'cmd': ':s/foo/bar/ie', 'exp': ln },
74 \ { 'cmd': ':s/t/r/i', 'exp': 'resting string' },
75 \ { 'cmd': ':s/t/r/iI', 'exp': 'Tesring string' },
76 \ { 'cmd': ':s/t/r/in', 'exp': ln },
77 \ { 'cmd': ':s/t/r/ip', 'exp': 'resting string' },
78 \ { 'cmd': ':s//r/ir', 'exp': 'Testr string' },
79 \ { 'cmd': ':s/t/r/Ic', 'exp': 'Tesring string', 'prompt': 'y' },
80 \ { 'cmd': ':s/foo/bar/Ie', 'exp': ln },
81 \ { 'cmd': ':s/t/r/Ig', 'exp': 'Tesring srring' },
82 \ { 'cmd': ':s/t/r/Ii', 'exp': 'resting string' },
83 \ { 'cmd': ':s/t/r/I', 'exp': 'Tesring string' },
84 \ { 'cmd': ':s/t/r/Ip', 'exp': 'Tesring string' },
85 \ { 'cmd': ':s/t/r/Il', 'exp': 'Tesring string' },
86 \ { 'cmd': ':s//r/Ir', 'exp': 'Testr string' },
87 \ { 'cmd': ':s//r/rc', 'exp': 'Testr string', 'prompt': 'y' },
88 \ { 'cmd': ':s//r/rg', 'exp': 'Testr strr' },
89 \ { 'cmd': ':s//r/ri', 'exp': 'Testr string' },
90 \ { 'cmd': ':s//r/rI', 'exp': 'Testr string' },
91 \ { 'cmd': ':s//r/rn', 'exp': 'Testing string' },
92 \ { 'cmd': ':s//r/rp', 'exp': 'Testr string' },
93 \ { 'cmd': ':s//r/rl', 'exp': 'Testr string' },
94 \ { 'cmd': ':s//r/r', 'exp': 'Testr string' },
Bram Moolenaarea3db912020-02-02 15:32:13 +010095 \ { 'cmd': ':s/i/I/gc', 'exp': 'Testing string', 'prompt': 'q' },
Bram Moolenaar8c50d502017-02-17 18:28:24 +010096 \]
97
98 for var in variants
99 for run in [1, 2]
100 let cmd = var.cmd
101 if run == 2 && cmd =~ "/.*/.*/."
102 " Change :s/from/to/{flags} to :s{flags}
103 let cmd = substitute(cmd, '/.*/', '', '')
104 endif
105 call setline(1, [ln])
106 let msg = printf('using "%s"', cmd)
107 let @/='ing'
108 let v:errmsg = ''
109 call feedkeys(cmd . "\<CR>" . get(var, 'prompt', ''), 'ntx')
110 " No error should exist (matters for testing e flag)
111 call assert_equal('', v:errmsg, msg)
112 call assert_equal(var.exp, getline('.'), msg)
113 endfor
114 endfor
Bram Moolenaar1e115362019-01-09 23:01:02 +0100115endfunc
Bram Moolenaarba748c82017-02-26 14:00:07 +0100116
Bram Moolenaar94747162019-02-10 21:55:26 +0100117" Test the l, p, # flags.
118func Test_substitute_flags_lp()
119 new
120 call setline(1, "abc\tdef\<C-h>ghi")
121
122 let a = execute('s/a/a/p')
123 call assert_equal("\nabc def^Hghi", a)
124
125 let a = execute('s/a/a/l')
126 call assert_equal("\nabc^Idef^Hghi$", a)
127
128 let a = execute('s/a/a/#')
129 call assert_equal("\n 1 abc def^Hghi", a)
130
131 let a = execute('s/a/a/p#')
132 call assert_equal("\n 1 abc def^Hghi", a)
133
134 let a = execute('s/a/a/l#')
135 call assert_equal("\n 1 abc^Idef^Hghi$", a)
136
137 let a = execute('s/a/a/')
138 call assert_equal("", a)
139
140 bwipe!
141endfunc
142
Bram Moolenaarba748c82017-02-26 14:00:07 +0100143func Test_substitute_repeat()
144 " This caused an invalid memory access.
Bram Moolenaarb18b4962022-09-02 21:55:50 +0100145 split Xsubfile
Bram Moolenaarba748c82017-02-26 14:00:07 +0100146 s/^/x
147 call feedkeys("Qsc\<CR>y", 'tx')
148 bwipe!
149endfunc
Bram Moolenaar1a333bc2017-08-30 20:21:58 +0200150
Bram Moolenaard77aa4d2019-02-10 22:50:14 +0100151" Test %s/\n// which is implemented as a special case to use a
152" more efficient join rather than doing a regular substitution.
153func Test_substitute_join()
154 new
155
156 call setline(1, ["foo\tbar", "bar\<C-H>foo"])
157 let a = execute('%s/\n//')
158 call assert_equal("", a)
159 call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
160 call assert_equal('\n', histget("search", -1))
161
162 call setline(1, ["foo\tbar", "bar\<C-H>foo"])
163 let a = execute('%s/\n//g')
164 call assert_equal("", a)
165 call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
166 call assert_equal('\n', histget("search", -1))
167
168 call setline(1, ["foo\tbar", "bar\<C-H>foo"])
169 let a = execute('%s/\n//p')
170 call assert_equal("\nfoo barbar^Hfoo", a)
171 call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
172 call assert_equal('\n', histget("search", -1))
173
174 call setline(1, ["foo\tbar", "bar\<C-H>foo"])
175 let a = execute('%s/\n//l')
176 call assert_equal("\nfoo^Ibarbar^Hfoo$", a)
177 call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
178 call assert_equal('\n', histget("search", -1))
179
180 call setline(1, ["foo\tbar", "bar\<C-H>foo"])
181 let a = execute('%s/\n//#')
182 call assert_equal("\n 1 foo barbar^Hfoo", a)
183 call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
184 call assert_equal('\n', histget("search", -1))
185
Bram Moolenaarea3db912020-02-02 15:32:13 +0100186 call setline(1, ['foo', 'bar', 'baz', 'qux'])
187 call execute('1,2s/\n//')
188 call assert_equal(['foobarbaz', 'qux'], getline(1, '$'))
189
Bram Moolenaard77aa4d2019-02-10 22:50:14 +0100190 bwipe!
191endfunc
192
193func Test_substitute_count()
194 new
195 call setline(1, ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo'])
196 2
197
198 s/foo/bar/3
199 call assert_equal(['foo foo', 'bar foo', 'bar foo', 'bar foo', 'foo foo'],
200 \ getline(1, '$'))
201
202 call assert_fails('s/foo/bar/0', 'E939:')
203
Bram Moolenaarea3db912020-02-02 15:32:13 +0100204 call setline(1, ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo'])
205 2,4s/foo/bar/ 10
206 call assert_equal(['foo foo', 'foo foo', 'foo foo', 'bar foo', 'bar foo'],
207 \ getline(1, '$'))
208
Bram Moolenaard77aa4d2019-02-10 22:50:14 +0100209 bwipe!
210endfunc
211
212" Test substitute 'n' flag (report number of matches, do not substitute).
213func Test_substitute_flag_n()
214 new
215 let lines = ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo']
216 call setline(1, lines)
217
218 call assert_equal("\n3 matches on 3 lines", execute('2,4s/foo/bar/n'))
219 call assert_equal("\n6 matches on 3 lines", execute('2,4s/foo/bar/gn'))
220
221 " c flag (confirm) should be ignored when using n flag.
222 call assert_equal("\n3 matches on 3 lines", execute('2,4s/foo/bar/nc'))
223
224 " No substitution should have been done.
225 call assert_equal(lines, getline(1, '$'))
226
Bram Moolenaarea3db912020-02-02 15:32:13 +0100227 %delete _
228 call setline(1, ['A', 'Bar', 'Baz'])
229 call assert_equal("\n1 match on 1 line", execute('s/\nB\@=//gn'))
230
Bram Moolenaard77aa4d2019-02-10 22:50:14 +0100231 bwipe!
232endfunc
233
234func Test_substitute_errors()
235 new
236 call setline(1, 'foobar')
237
238 call assert_fails('s/FOO/bar/', 'E486:')
239 call assert_fails('s/foo/bar/@', 'E488:')
Bram Moolenaar9b7bf9e2020-07-11 22:14:59 +0200240 call assert_fails('s/\(/bar/', 'E54:')
Bram Moolenaar5d98dc22020-01-29 21:57:34 +0100241 call assert_fails('s afooabara', 'E146:')
242 call assert_fails('s\\a', 'E10:')
Bram Moolenaard77aa4d2019-02-10 22:50:14 +0100243
244 setl nomodifiable
245 call assert_fails('s/foo/bar/', 'E21:')
246
Bram Moolenaar0e05de42020-03-25 22:23:46 +0100247 call assert_fails("let s=substitute([], 'a', 'A', 'g')", 'E730:')
248 call assert_fails("let s=substitute('abcda', [], 'A', 'g')", 'E730:')
249 call assert_fails("let s=substitute('abcda', 'a', [], 'g')", 'E730:')
250 call assert_fails("let s=substitute('abcda', 'a', 'A', [])", 'E730:')
Bram Moolenaar531be472020-09-23 22:38:05 +0200251 call assert_fails("let s=substitute('abc', '\\%(', 'A', 'g')", 'E53:')
Bram Moolenaar0e05de42020-03-25 22:23:46 +0100252
Bram Moolenaard77aa4d2019-02-10 22:50:14 +0100253 bwipe!
254endfunc
255
Bram Moolenaar1a333bc2017-08-30 20:21:58 +0200256" Test for *sub-replace-special* and *sub-replace-expression* on substitute().
257func Test_sub_replace_1()
258 " Run the tests with 'magic' on
259 set magic
260 set cpo&
261 call assert_equal('AA', substitute('A', 'A', '&&', ''))
262 call assert_equal('&', substitute('B', 'B', '\&', ''))
263 call assert_equal('C123456789987654321', substitute('C123456789', 'C\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)', '\0\9\8\7\6\5\4\3\2\1', ''))
264 call assert_equal('d', substitute('D', 'D', 'd', ''))
265 call assert_equal('~', substitute('E', 'E', '~', ''))
266 call assert_equal('~', substitute('F', 'F', '\~', ''))
267 call assert_equal('Gg', substitute('G', 'G', '\ugg', ''))
268 call assert_equal('Hh', substitute('H', 'H', '\Uh\Eh', ''))
269 call assert_equal('iI', substitute('I', 'I', '\lII', ''))
270 call assert_equal('jJ', substitute('J', 'J', '\LJ\EJ', ''))
271 call assert_equal('Kk', substitute('K', 'K', '\Uk\ek', ''))
272 call assert_equal("l\<C-V>\<C-M>l",
273 \ substitute('lLl', 'L', "\<C-V>\<C-M>", ''))
274 call assert_equal("m\<C-M>m", substitute('mMm', 'M', '\r', ''))
275 call assert_equal("n\<C-V>\<C-M>n",
276 \ substitute('nNn', 'N', "\\\<C-V>\<C-M>", ''))
277 call assert_equal("o\no", substitute('oOo', 'O', '\n', ''))
278 call assert_equal("p\<C-H>p", substitute('pPp', 'P', '\b', ''))
279 call assert_equal("q\tq", substitute('qQq', 'Q', '\t', ''))
280 call assert_equal('r\r', substitute('rRr', 'R', '\\', ''))
281 call assert_equal('scs', substitute('sSs', 'S', '\c', ''))
282 call assert_equal("u\nu", substitute('uUu', 'U', "\n", ''))
283 call assert_equal("v\<C-H>v", substitute('vVv', 'V', "\b", ''))
284 call assert_equal("w\\w", substitute('wWw', 'W', "\\", ''))
285 call assert_equal("x\<C-M>x", substitute('xXx', 'X', "\r", ''))
286 call assert_equal("YyyY", substitute('Y', 'Y', '\L\uyYy\l\EY', ''))
287 call assert_equal("zZZz", substitute('Z', 'Z', '\U\lZzZ\u\Ez', ''))
Bram Moolenaar004a6782020-04-11 17:09:31 +0200288 " \v or \V after $
289 call assert_equal('abxx', substitute('abcd', 'xy$\v|cd$', 'xx', ''))
290 call assert_equal('abxx', substitute('abcd', 'xy$\V\|cd\$', 'xx', ''))
Bram Moolenaar1a333bc2017-08-30 20:21:58 +0200291endfunc
292
293func Test_sub_replace_2()
294 " Run the tests with 'magic' off
295 set nomagic
296 set cpo&
297 call assert_equal('AA', substitute('A', 'A', '&&', ''))
298 call assert_equal('&', substitute('B', 'B', '\&', ''))
299 call assert_equal('C123456789987654321', substitute('C123456789', 'C\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)', '\0\9\8\7\6\5\4\3\2\1', ''))
300 call assert_equal('d', substitute('D', 'D', 'd', ''))
301 call assert_equal('~', substitute('E', 'E', '~', ''))
302 call assert_equal('~', substitute('F', 'F', '\~', ''))
303 call assert_equal('Gg', substitute('G', 'G', '\ugg', ''))
304 call assert_equal('Hh', substitute('H', 'H', '\Uh\Eh', ''))
305 call assert_equal('iI', substitute('I', 'I', '\lII', ''))
306 call assert_equal('jJ', substitute('J', 'J', '\LJ\EJ', ''))
307 call assert_equal('Kk', substitute('K', 'K', '\Uk\ek', ''))
308 call assert_equal("l\<C-V>\<C-M>l",
309 \ substitute('lLl', 'L', "\<C-V>\<C-M>", ''))
310 call assert_equal("m\<C-M>m", substitute('mMm', 'M', '\r', ''))
311 call assert_equal("n\<C-V>\<C-M>n",
312 \ substitute('nNn', 'N', "\\\<C-V>\<C-M>", ''))
313 call assert_equal("o\no", substitute('oOo', 'O', '\n', ''))
314 call assert_equal("p\<C-H>p", substitute('pPp', 'P', '\b', ''))
315 call assert_equal("q\tq", substitute('qQq', 'Q', '\t', ''))
316 call assert_equal('r\r', substitute('rRr', 'R', '\\', ''))
317 call assert_equal('scs', substitute('sSs', 'S', '\c', ''))
318 call assert_equal("t\<C-M>t", substitute('tTt', 'T', "\r", ''))
319 call assert_equal("u\nu", substitute('uUu', 'U', "\n", ''))
320 call assert_equal("v\<C-H>v", substitute('vVv', 'V', "\b", ''))
321 call assert_equal('w\w', substitute('wWw', 'W', "\\", ''))
322 call assert_equal('XxxX', substitute('X', 'X', '\L\uxXx\l\EX', ''))
323 call assert_equal('yYYy', substitute('Y', 'Y', '\U\lYyY\u\Ey', ''))
324endfunc
325
326func Test_sub_replace_3()
327 set magic&
328 set cpo&
329 call assert_equal('a\a', substitute('aAa', 'A', '\="\\"', ''))
330 call assert_equal('b\\b', substitute('bBb', 'B', '\="\\\\"', ''))
331 call assert_equal("c\rc", substitute('cCc', 'C', "\\=\"\r\"", ''))
332 call assert_equal("d\\\rd", substitute('dDd', 'D', "\\=\"\\\\\r\"", ''))
333 call assert_equal("e\\\\\re", substitute('eEe', 'E', "\\=\"\\\\\\\\\r\"", ''))
334 call assert_equal('f\rf', substitute('fFf', 'F', '\="\\r"', ''))
335 call assert_equal('j\nj', substitute('jJj', 'J', '\="\\n"', ''))
336 call assert_equal("k\<C-M>k", substitute('kKk', 'K', '\="\r"', ''))
337 call assert_equal("l\nl", substitute('lLl', 'L', '\="\n"', ''))
338endfunc
339
340" Test for submatch() on substitute().
341func Test_sub_replace_4()
342 set magic&
343 set cpo&
344 call assert_equal('a\a', substitute('aAa', 'A',
345 \ '\=substitute(submatch(0), ".", "\\", "")', ''))
346 call assert_equal('b\b', substitute('bBb', 'B',
347 \ '\=substitute(submatch(0), ".", "\\\\", "")', ''))
348 call assert_equal("c\<C-V>\<C-M>c", substitute('cCc', 'C', '\=substitute(submatch(0), ".", "\<C-V>\<C-M>", "")', ''))
349 call assert_equal("d\<C-V>\<C-M>d", substitute('dDd', 'D', '\=substitute(submatch(0), ".", "\\\<C-V>\<C-M>", "")', ''))
350 call assert_equal("e\\\<C-V>\<C-M>e", substitute('eEe', 'E', '\=substitute(submatch(0), ".", "\\\\\<C-V>\<C-M>", "")', ''))
351 call assert_equal("f\<C-M>f", substitute('fFf', 'F', '\=substitute(submatch(0), ".", "\\r", "")', ''))
352 call assert_equal("j\nj", substitute('jJj', 'J', '\=substitute(submatch(0), ".", "\\n", "")', ''))
353 call assert_equal("k\rk", substitute('kKk', 'K', '\=substitute(submatch(0), ".", "\r", "")', ''))
354 call assert_equal("l\nl", substitute('lLl', 'L', '\=substitute(submatch(0), ".", "\n", "")', ''))
355endfunc
356
357func Test_sub_replace_5()
358 set magic&
359 set cpo&
360 call assert_equal('A123456789987654321', substitute('A123456789',
361 \ 'A\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)',
362 \ '\=submatch(0) . submatch(9) . submatch(8) . ' .
363 \ 'submatch(7) . submatch(6) . submatch(5) . ' .
364 \ 'submatch(4) . submatch(3) . submatch(2) . submatch(1)',
365 \ ''))
366 call assert_equal("[['A123456789'], ['9'], ['8'], ['7'], ['6'], " .
367 \ "['5'], ['4'], ['3'], ['2'], ['1']]",
368 \ substitute('A123456789',
369 \ 'A\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)',
370 \ '\=string([submatch(0, 1), submatch(9, 1), ' .
Bram Moolenaarf6ed61e2019-09-07 19:05:09 +0200371 \ 'submatch(8, 1), 7->submatch(1), submatch(6, 1), ' .
Bram Moolenaar1a333bc2017-08-30 20:21:58 +0200372 \ 'submatch(5, 1), submatch(4, 1), submatch(3, 1), ' .
373 \ 'submatch(2, 1), submatch(1, 1)])',
374 \ ''))
375endfunc
376
377func Test_sub_replace_6()
378 set magic&
379 set cpo+=/
380 call assert_equal('a', substitute('A', 'A', 'a', ''))
381 call assert_equal('%', substitute('B', 'B', '%', ''))
382 set cpo-=/
383 call assert_equal('c', substitute('C', 'C', 'c', ''))
384 call assert_equal('%', substitute('D', 'D', '%', ''))
385endfunc
386
387func Test_sub_replace_7()
388 set magic&
389 set cpo&
390 call assert_equal('AA', substitute('AA', 'A.', '\=submatch(0)', ''))
391 call assert_equal("B\nB", substitute("B\nB", 'B.', '\=submatch(0)', ''))
392 call assert_equal("['B\n']B", substitute("B\nB", 'B.', '\=string(submatch(0, 1))', ''))
393 call assert_equal('-abab', substitute('-bb', '\zeb', 'a', 'g'))
394 call assert_equal('c-cbcbc', substitute('-bb', '\ze', 'c', 'g'))
395endfunc
396
397" Test for *:s%* on :substitute.
398func Test_sub_replace_8()
399 new
400 set magic&
401 set cpo&
402 $put =',,X'
403 s/\(^\|,\)\ze\(,\|X\)/\1N/g
404 call assert_equal('N,,NX', getline("$"))
405 $put =',,Y'
406 let cmd = ':s/\(^\|,\)\ze\(,\|Y\)/\1N/gc'
407 call feedkeys(cmd . "\<CR>a", "xt")
408 call assert_equal('N,,NY', getline("$"))
409 :$put =',,Z'
410 let cmd = ':s/\(^\|,\)\ze\(,\|Z\)/\1N/gc'
411 call feedkeys(cmd . "\<CR>yy", "xt")
412 call assert_equal('N,,NZ', getline("$"))
413 enew! | close
414endfunc
415
416func Test_sub_replace_9()
417 new
418 set magic&
419 set cpo&
420 $put ='xxx'
421 call feedkeys(":s/x/X/gc\<CR>yyq", "xt")
422 call assert_equal('XXx', getline("$"))
423 enew! | close
424endfunc
425
426func Test_sub_replace_10()
427 set magic&
428 set cpo&
429 call assert_equal('a1a2a3a', substitute('123', '\zs', 'a', 'g'))
430 call assert_equal('aaa', substitute('123', '\zs.', 'a', 'g'))
431 call assert_equal('1a2a3a', substitute('123', '.\zs', 'a', 'g'))
432 call assert_equal('a1a2a3a', substitute('123', '\ze', 'a', 'g'))
433 call assert_equal('a1a2a3', substitute('123', '\ze.', 'a', 'g'))
434 call assert_equal('aaa', substitute('123', '.\ze', 'a', 'g'))
435 call assert_equal('aa2a3a', substitute('123', '1\|\ze', 'a', 'g'))
436 call assert_equal('1aaa', substitute('123', '1\zs\|[23]', 'a', 'g'))
437endfunc
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200438
Bram Moolenaarb0745b22019-11-09 22:28:11 +0100439func SubReplacer(text, submatches)
440 return a:text .. a:submatches[0] .. a:text
441endfunc
zeertzjq48db5da2022-09-16 12:10:03 +0100442func SubReplacerVar(text, ...)
443 return a:text .. a:1[0] .. a:text
444endfunc
Bram Moolenaar4c054e92019-11-10 00:13:50 +0100445func SubReplacer20(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, submatches)
446 return a:t3 .. a:submatches[0] .. a:t11
447endfunc
Bram Moolenaarb0745b22019-11-09 22:28:11 +0100448
449func Test_substitute_partial()
zeertzjq48db5da2022-09-16 12:10:03 +0100450 call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacer', ['foo']), 'g'))
451 call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacerVar', ['foo']), 'g'))
Bram Moolenaar4c054e92019-11-10 00:13:50 +0100452
zeertzjq48db5da2022-09-16 12:10:03 +0100453 " 19 arguments plus one is just OK
454 let Replacer = function('SubReplacer20', repeat(['foo'], 19))
455 call assert_equal('1foo2foo3', substitute('123', '2', Replacer, 'g'))
Bram Moolenaar4c054e92019-11-10 00:13:50 +0100456
zeertzjq48db5da2022-09-16 12:10:03 +0100457 " 20 arguments plus one is too many
458 let Replacer = function('SubReplacer20', repeat(['foo'], 20))
459 call assert_fails("call substitute('123', '2', Replacer, 'g')", 'E118:')
Bram Moolenaarb0745b22019-11-09 22:28:11 +0100460endfunc
461
Bram Moolenaar7a2217b2021-06-06 12:33:49 +0200462func Test_substitute_float()
463 CheckFeature float
464
465 call assert_equal('number 1.23', substitute('number ', '$', { -> 1.23 }, ''))
466 vim9 assert_equal('number 1.23', substitute('number ', '$', () => 1.23, ''))
467endfunc
468
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200469" Tests for *sub-replace-special* and *sub-replace-expression* on :substitute.
470
471" Execute a list of :substitute command tests
472func Run_SubCmd_Tests(tests)
473 enew!
474 for t in a:tests
475 let start = line('.') + 1
476 let end = start + len(t[2]) - 1
477 exe "normal o" . t[0]
478 call cursor(start, 1)
479 exe t[1]
480 call assert_equal(t[2], getline(start, end), t[1])
481 endfor
482 enew!
483endfunc
484
485func Test_sub_cmd_1()
486 set magic
487 set cpo&
488
489 " List entry format: [input, cmd, output]
490 let tests = [['A', 's/A/&&/', ['AA']],
491 \ ['B', 's/B/\&/', ['&']],
492 \ ['C123456789', 's/C\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\0\9\8\7\6\5\4\3\2\1/', ['C123456789987654321']],
493 \ ['D', 's/D/d/', ['d']],
494 \ ['E', 's/E/~/', ['d']],
495 \ ['F', 's/F/\~/', ['~']],
496 \ ['G', 's/G/\ugg/', ['Gg']],
497 \ ['H', 's/H/\Uh\Eh/', ['Hh']],
498 \ ['I', 's/I/\lII/', ['iI']],
499 \ ['J', 's/J/\LJ\EJ/', ['jJ']],
500 \ ['K', 's/K/\Uk\ek/', ['Kk']],
501 \ ['lLl', "s/L/\<C-V>\<C-M>/", ["l\<C-V>", 'l']],
502 \ ['mMm', 's/M/\r/', ['m', 'm']],
503 \ ['nNn', "s/N/\\\<C-V>\<C-M>/", ["n\<C-V>", 'n']],
504 \ ['oOo', 's/O/\n/', ["o\no"]],
505 \ ['pPp', 's/P/\b/', ["p\<C-H>p"]],
506 \ ['qQq', 's/Q/\t/', ["q\tq"]],
507 \ ['rRr', 's/R/\\/', ['r\r']],
508 \ ['sSs', 's/S/\c/', ['scs']],
509 \ ['tTt', "s/T/\<C-V>\<C-J>/", ["t\<C-V>\<C-J>t"]],
510 \ ['U', 's/U/\L\uuUu\l\EU/', ['UuuU']],
zeertzjq3269efd2022-06-12 11:13:05 +0100511 \ ['V', 's/V/\U\lVvV\u\Ev/', ['vVVv']],
512 \ ['\', 's/\\/\\\\/', ['\\']]
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200513 \ ]
514 call Run_SubCmd_Tests(tests)
515endfunc
516
517func Test_sub_cmd_2()
518 set nomagic
519 set cpo&
520
521 " List entry format: [input, cmd, output]
522 let tests = [['A', 's/A/&&/', ['&&']],
523 \ ['B', 's/B/\&/', ['B']],
524 \ ['C123456789', 's/\mC\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\0\9\8\7\6\5\4\3\2\1/', ['C123456789987654321']],
525 \ ['D', 's/D/d/', ['d']],
526 \ ['E', 's/E/~/', ['~']],
527 \ ['F', 's/F/\~/', ['~']],
528 \ ['G', 's/G/\ugg/', ['Gg']],
529 \ ['H', 's/H/\Uh\Eh/', ['Hh']],
530 \ ['I', 's/I/\lII/', ['iI']],
531 \ ['J', 's/J/\LJ\EJ/', ['jJ']],
532 \ ['K', 's/K/\Uk\ek/', ['Kk']],
533 \ ['lLl', "s/L/\<C-V>\<C-M>/", ["l\<C-V>", 'l']],
534 \ ['mMm', 's/M/\r/', ['m', 'm']],
535 \ ['nNn', "s/N/\\\<C-V>\<C-M>/", ["n\<C-V>", 'n']],
536 \ ['oOo', 's/O/\n/', ["o\no"]],
537 \ ['pPp', 's/P/\b/', ["p\<C-H>p"]],
538 \ ['qQq', 's/Q/\t/', ["q\tq"]],
539 \ ['rRr', 's/R/\\/', ['r\r']],
540 \ ['sSs', 's/S/\c/', ['scs']],
541 \ ['tTt', "s/T/\<C-V>\<C-J>/", ["t\<C-V>\<C-J>t"]],
542 \ ['U', 's/U/\L\uuUu\l\EU/', ['UuuU']],
zeertzjq3269efd2022-06-12 11:13:05 +0100543 \ ['V', 's/V/\U\lVvV\u\Ev/', ['vVVv']],
544 \ ['\', 's/\\/\\\\/', ['\\']]
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200545 \ ]
546 call Run_SubCmd_Tests(tests)
547endfunc
548
549func Test_sub_cmd_3()
550 set nomagic
551 set cpo&
552
553 " List entry format: [input, cmd, output]
554 let tests = [['aAa', "s/A/\\='\\'/", ['a\a']],
555 \ ['bBb', "s/B/\\='\\\\'/", ['b\\b']],
556 \ ['cCc', "s/C/\\='\<C-V>\<C-M>'/", ["c\<C-V>", 'c']],
557 \ ['dDd', "s/D/\\='\\\<C-V>\<C-M>'/", ["d\\\<C-V>", 'd']],
558 \ ['eEe', "s/E/\\='\\\\\<C-V>\<C-M>'/", ["e\\\\\<C-V>", 'e']],
559 \ ['fFf', "s/F/\\='\r'/", ['f', 'f']],
560 \ ['gGg', "s/G/\\='\<C-V>\<C-J>'/", ["g\<C-V>", 'g']],
561 \ ['hHh', "s/H/\\='\\\<C-V>\<C-J>'/", ["h\\\<C-V>", 'h']],
562 \ ['iIi', "s/I/\\='\\\\\<C-V>\<C-J>'/", ["i\\\\\<C-V>", 'i']],
563 \ ['jJj', "s/J/\\='\n'/", ['j', 'j']],
564 \ ['kKk', 's/K/\="\r"/', ['k', 'k']],
565 \ ['lLl', 's/L/\="\n"/', ['l', 'l']]
566 \ ]
567 call Run_SubCmd_Tests(tests)
568endfunc
569
Bram Moolenaarf1699962019-08-31 17:48:19 +0200570" Test for submatch() on :substitute.
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200571func Test_sub_cmd_4()
572 set magic&
573 set cpo&
574
575 " List entry format: [input, cmd, output]
576 let tests = [ ['aAa', "s/A/\\=substitute(submatch(0), '.', '\\', '')/",
Bram Moolenaar1e115362019-01-09 23:01:02 +0100577 \ ['a\a']],
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200578 \ ['bBb', "s/B/\\=substitute(submatch(0), '.', '\\', '')/",
Bram Moolenaar1e115362019-01-09 23:01:02 +0100579 \ ['b\b']],
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200580 \ ['cCc', "s/C/\\=substitute(submatch(0), '.', '\<C-V>\<C-M>', '')/",
581 \ ["c\<C-V>", 'c']],
582 \ ['dDd', "s/D/\\=substitute(submatch(0), '.', '\\\<C-V>\<C-M>', '')/",
583 \ ["d\<C-V>", 'd']],
584 \ ['eEe', "s/E/\\=substitute(submatch(0), '.', '\\\\\<C-V>\<C-M>', '')/",
585 \ ["e\\\<C-V>", 'e']],
586 \ ['fFf', "s/F/\\=substitute(submatch(0), '.', '\\r', '')/",
587 \ ['f', 'f']],
588 \ ['gGg', 's/G/\=substitute(submatch(0), ".", "\<C-V>\<C-J>", "")/',
589 \ ["g\<C-V>", 'g']],
590 \ ['hHh', 's/H/\=substitute(submatch(0), ".", "\\\<C-V>\<C-J>", "")/',
591 \ ["h\<C-V>", 'h']],
592 \ ['iIi', 's/I/\=substitute(submatch(0), ".", "\\\\\<C-V>\<C-J>", "")/',
593 \ ["i\\\<C-V>", 'i']],
594 \ ['jJj', "s/J/\\=substitute(submatch(0), '.', '\\n', '')/",
595 \ ['j', 'j']],
596 \ ['kKk', "s/K/\\=substitute(submatch(0), '.', '\\r', '')/",
597 \ ['k', 'k']],
598 \ ['lLl', "s/L/\\=substitute(submatch(0), '.', '\\n', '')/",
599 \ ['l', 'l']],
600 \ ]
601 call Run_SubCmd_Tests(tests)
602endfunc
603
604func Test_sub_cmd_5()
605 set magic&
606 set cpo&
607
608 " List entry format: [input, cmd, output]
609 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']],
610 \ ['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']]"]],
611 \ ]
612 call Run_SubCmd_Tests(tests)
613endfunc
614
615" Test for *:s%* on :substitute.
616func Test_sub_cmd_6()
617 set magic&
618 set cpo+=/
619
620 " List entry format: [input, cmd, output]
621 let tests = [ ['A', 's/A/a/', ['a']],
622 \ ['B', 's/B/%/', ['a']],
623 \ ]
624 call Run_SubCmd_Tests(tests)
625
626 set cpo-=/
627 let tests = [ ['C', 's/C/c/', ['c']],
628 \ ['D', 's/D/%/', ['%']],
629 \ ]
630 call Run_SubCmd_Tests(tests)
631
632 set cpo&
633endfunc
634
635" Test for :s replacing \n with line break.
636func Test_sub_cmd_7()
637 set magic&
638 set cpo&
639
640 " List entry format: [input, cmd, output]
641 let tests = [ ["A\<C-V>\<C-M>A", 's/A./\=submatch(0)/', ['A', 'A']],
642 \ ["B\<C-V>\<C-J>B", 's/B./\=submatch(0)/', ['B', 'B']],
643 \ ["C\<C-V>\<C-J>C", 's/C./\=strtrans(string(submatch(0, 1)))/', [strtrans("['C\<C-J>']C")]],
644 \ ["D\<C-V>\<C-J>\nD", 's/D.\nD/\=strtrans(string(submatch(0, 1)))/', [strtrans("['D\<C-J>', 'D']")]],
645 \ ["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']")]],
646 \ ]
647 call Run_SubCmd_Tests(tests)
648
649 exe "normal oQ\nQ\<Esc>k"
Bram Moolenaare2e40752020-09-04 21:18:46 +0200650 call assert_fails('s/Q[^\n]Q/\=submatch(0)."foobar"/', 'E486:')
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200651 enew!
652endfunc
653
654func TitleString()
655 let check = 'foo' =~ 'bar'
656 return ""
657endfunc
658
659func Test_sub_cmd_8()
660 set titlestring=%{TitleString()}
661
662 enew!
663 call append(0, ['', 'test_one', 'test_two'])
664 call cursor(1,1)
665 /^test_one/s/.*/\="foo\nbar"/
666 call assert_equal('foo', getline(2))
667 call assert_equal('bar', getline(3))
668 call feedkeys(':/^test_two/s/.*/\="foo\nbar"/c', "t")
669 call feedkeys("\<CR>y", "xt")
670 call assert_equal('foo', getline(4))
671 call assert_equal('bar', getline(5))
672
673 enew!
674 set titlestring&
675endfunc
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100676
Bram Moolenaar80341bc2019-05-20 20:34:51 +0200677func Test_sub_cmd_9()
678 new
679 let input = ['1 aaa', '2 aaa', '3 aaa']
680 call setline(1, input)
681 func Foo()
682 return submatch(0)
683 endfunc
684 %s/aaa/\=Foo()/gn
685 call assert_equal(input, getline(1, '$'))
686 call assert_equal(1, &modifiable)
687
688 delfunc Foo
689 bw!
690endfunc
691
Bram Moolenaara04f4572022-09-13 13:45:26 +0100692func Test_sub_highlight_zero_match()
693 CheckRunVimInTerminal
694
695 let lines =<< trim END
696 call setline(1, ['one', 'two', 'three'])
697 END
698 call writefile(lines, 'XscriptSubHighlight', 'D')
699 let buf = RunVimInTerminal('-S XscriptSubHighlight', #{rows: 8, cols: 60})
700 call term_sendkeys(buf, ":%s/^/ /c\<CR>")
701 call VerifyScreenDump(buf, 'Test_sub_highlight_zer_match_1', {})
702
703 call term_sendkeys(buf, "\<Esc>")
704 call StopVimInTerminal(buf)
705endfunc
706
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100707func Test_nocatch_sub_failure_handling()
708 " normal error results in all replacements
Bram Moolenaar80341bc2019-05-20 20:34:51 +0200709 func Foo()
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100710 foobar
711 endfunc
712 new
713 call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
zeertzjq3269efd2022-06-12 11:13:05 +0100714 " need silent! to avoid a delay when entering Insert mode
715 silent! %s/aaa/\=Foo()/g
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100716 call assert_equal(['1 0', '2 0', '3 0'], getline(1, 3))
717
zeertzjq3269efd2022-06-12 11:13:05 +0100718 " Throw without try-catch causes abort after the first line.
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100719 " We cannot test this, since it would stop executing the test script.
720
721 " try/catch does not result in any changes
722 func! Foo()
723 throw 'error'
724 endfunc
725 call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
726 let error_caught = 0
727 try
728 %s/aaa/\=Foo()/g
729 catch
730 let error_caught = 1
731 endtry
732 call assert_equal(1, error_caught)
733 call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3))
734
Bram Moolenaar6349e942019-05-18 13:41:22 +0200735 " Same, but using "n" flag so that "sandbox" gets set
736 call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
737 let error_caught = 0
738 try
739 %s/aaa/\=Foo()/gn
740 catch
741 let error_caught = 1
742 endtry
743 call assert_equal(1, error_caught)
744 call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3))
745
Bram Moolenaar80341bc2019-05-20 20:34:51 +0200746 delfunc Foo
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100747 bwipe!
748endfunc
Bram Moolenaarc6b37db2019-04-27 18:00:34 +0200749
750" Test ":s/pat/sub/" with different ~s in sub.
751func Test_replace_with_tilde()
752 new
753 " Set the last replace string to empty
754 s/^$//
755 call append(0, ['- Bug in "vPPPP" on this text:'])
756 normal gg
757 s/u/~u~/
758 call assert_equal('- Bug in "vPPPP" on this text:', getline(1))
759 s/i/~u~/
760 call assert_equal('- Bug uuun "vPPPP" on this text:', getline(1))
761 s/o/~~~/
762 call assert_equal('- Bug uuun "vPPPP" uuuuuuuuun this text:', getline(1))
763 close!
764endfunc
765
766func Test_replace_keeppatterns()
767 new
768 a
769foobar
770
771substitute foo asdf
772
773one two
774.
775
776 normal gg
777 /^substitute
778 s/foo/bar/
779 call assert_equal('foo', @/)
780 call assert_equal('substitute bar asdf', getline('.'))
781
782 /^substitute
783 keeppatterns s/asdf/xyz/
784 call assert_equal('^substitute', @/)
785 call assert_equal('substitute bar xyz', getline('.'))
786
787 exe "normal /bar /e\<CR>"
788 call assert_equal(15, col('.'))
789 normal -
790 keeppatterns /xyz
791 call assert_equal('bar ', @/)
792 call assert_equal('substitute bar xyz', getline('.'))
793 exe "normal 0dn"
794 call assert_equal('xyz', getline('.'))
795
796 close!
797endfunc
Bram Moolenaarbb265962019-10-31 04:38:36 +0100798
799func Test_sub_beyond_end()
800 new
801 call setline(1, '#')
802 let @/ = '^#\n\zs'
803 s///e
804 call assert_equal('#', getline(1))
805 bwipe!
806endfunc
Bram Moolenaar5d98dc22020-01-29 21:57:34 +0100807
Bram Moolenaarea3db912020-02-02 15:32:13 +0100808" Test for repeating last substitution using :~ and :&r
809func Test_repeat_last_sub()
810 new
811 call setline(1, ['blue green yellow orange white'])
812 s/blue/red/
813 let @/ = 'yellow'
814 ~
815 let @/ = 'white'
816 :&r
817 let @/ = 'green'
818 s//gray
819 call assert_equal('red gray red orange red', getline(1))
820 close!
821endfunc
822
823" Test for Vi compatible substitution:
824" \/{string}/, \?{string}? and \&{string}&
825func Test_sub_vi_compatibility()
826 new
827 call setline(1, ['blue green yellow orange blue'])
828 let @/ = 'orange'
829 s\/white/
830 let @/ = 'blue'
831 s\?amber?
832 let @/ = 'white'
833 s\&green&
834 call assert_equal('amber green yellow white green', getline(1))
835 close!
Bram Moolenaar9fb7b422022-03-05 21:13:26 +0000836
837 call assert_fails('vim9cmd s\/white/', 'E1270:')
838 call assert_fails('vim9cmd s\?white?', 'E1270:')
839 call assert_fails('vim9cmd s\&white&', 'E1270:')
Bram Moolenaarea3db912020-02-02 15:32:13 +0100840endfunc
841
842" Test for substitute with the new text longer than the original text
843func Test_sub_expand_text()
844 new
845 call setline(1, 'abcabcabcabcabcabcabcabc')
846 s/b/\=repeat('B', 10)/g
847 call assert_equal(repeat('aBBBBBBBBBBc', 8), getline(1))
848 close!
849endfunc
850
Bram Moolenaar07ada5f2020-02-05 20:38:22 +0100851" Test for command failures when the last substitute pattern is not set.
852func Test_sub_with_no_last_pat()
Bram Moolenaar9f6277b2020-02-11 22:04:02 +0100853 let lines =<< trim [SCRIPT]
854 call assert_fails('~', 'E33:')
Bram Moolenaar9b7bf9e2020-07-11 22:14:59 +0200855 call assert_fails('s//abc/g', 'E35:')
856 call assert_fails('s\/bar', 'E35:')
857 call assert_fails('s\&bar&', 'E33:')
Bram Moolenaar9f6277b2020-02-11 22:04:02 +0100858 call writefile(v:errors, 'Xresult')
859 qall!
860 [SCRIPT]
861 call writefile(lines, 'Xscript')
862 if RunVim([], [], '--clean -S Xscript')
863 call assert_equal([], readfile('Xresult'))
864 endif
Bram Moolenaar07ada5f2020-02-05 20:38:22 +0100865
Bram Moolenaar9f6277b2020-02-11 22:04:02 +0100866 let lines =<< trim [SCRIPT]
867 set cpo+=/
868 call assert_fails('s/abc/%/', 'E33:')
869 call writefile(v:errors, 'Xresult')
870 qall!
871 [SCRIPT]
872 call writefile(lines, 'Xscript')
873 if RunVim([], [], '--clean -S Xscript')
874 call assert_equal([], readfile('Xresult'))
875 endif
876
877 call delete('Xscript')
878 call delete('Xresult')
Bram Moolenaar07ada5f2020-02-05 20:38:22 +0100879endfunc
880
Bram Moolenaarca68ae12020-03-30 19:32:53 +0200881func Test_substitute()
882 call assert_equal('a1a2a3a', substitute('123', '\zs', 'a', 'g'))
Bram Moolenaar004a6782020-04-11 17:09:31 +0200883 " Substitute with special keys
884 call assert_equal("a\<End>c", substitute('abc', "a.c", "a\<End>c", ''))
885endfunc
886
887func Test_substitute_expr()
888 let g:val = 'XXX'
889 call assert_equal('XXX', substitute('yyy', 'y*', '\=g:val', ''))
890 call assert_equal('XXX', substitute('yyy', 'y*', {-> g:val}, ''))
891 call assert_equal("-\u1b \uf2-", substitute("-%1b %f2-", '%\(\x\x\)',
892 \ '\=nr2char("0x" . submatch(1))', 'g'))
893 call assert_equal("-\u1b \uf2-", substitute("-%1b %f2-", '%\(\x\x\)',
894 \ {-> nr2char("0x" . submatch(1))}, 'g'))
895
896 call assert_equal('231', substitute('123', '\(.\)\(.\)\(.\)',
897 \ {-> submatch(2) . submatch(3) . submatch(1)}, ''))
898
899 func Recurse()
900 return substitute('yyy', 'y\(.\)y', {-> submatch(1)}, '')
901 endfunc
902 " recursive call works
903 call assert_equal('-y-x-', substitute('xxx', 'x\(.\)x', {-> '-' . Recurse() . '-' . submatch(1) . '-'}, ''))
904
905 call assert_fails("let s=submatch([])", 'E745:')
906 call assert_fails("let s=submatch(2, [])", 'E745:')
907endfunc
908
909func Test_invalid_submatch()
910 " This was causing invalid memory access in Vim-7.4.2232 and older
911 call assert_fails("call substitute('x', '.', {-> submatch(10)}, '')", 'E935:')
912 call assert_fails('eval submatch(-1)', 'E935:')
913 call assert_equal('', submatch(0))
914 call assert_equal('', submatch(1))
915 call assert_equal([], submatch(0, 1))
916 call assert_equal([], submatch(1, 1))
917endfunc
918
Bram Moolenaar8a0dcf42020-09-06 15:14:45 +0200919func Test_submatch_list_concatenate()
920 let pat = 'A\(.\)'
921 let Rep = {-> string([submatch(0, 1)] + [[submatch(1)]])}
922 call substitute('A1', pat, Rep, '')->assert_equal("[['A1'], ['1']]")
923endfunc
924
Bram Moolenaar004a6782020-04-11 17:09:31 +0200925func Test_substitute_expr_arg()
926 call assert_equal('123456789-123456789=', substitute('123456789',
927 \ '\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)',
928 \ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))
929
930 call assert_equal('123456-123456=789', substitute('123456789',
931 \ '\(.\)\(.\)\(.\)\(a*\)\(n*\)\(.\)\(.\)\(.\)\(x*\)',
932 \ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))
933
934 call assert_equal('123456789-123456789x=', substitute('123456789',
935 \ '\(.\)\(.\)\(.*\)',
936 \ {m -> m[0] . '-' . m[1] . m[2] . m[3] . 'x' . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))
937
938 call assert_fails("call substitute('xxx', '.', {m -> string(add(m, 'x'))}, '')", 'E742:')
939 call assert_fails("call substitute('xxx', '.', {m -> string(insert(m, 'x'))}, '')", 'E742:')
940 call assert_fails("call substitute('xxx', '.', {m -> string(extend(m, ['x']))}, '')", 'E742:')
941 call assert_fails("call substitute('xxx', '.', {m -> string(remove(m, 1))}, '')", 'E742:')
942endfunc
943
944" Test for using a function to supply the substitute string
945func Test_substitute_using_func()
946 func Xfunc()
947 return '1234'
948 endfunc
949 call assert_equal('a1234f', substitute('abcdef', 'b..e',
950 \ function("Xfunc"), ''))
951 delfunc Xfunc
952endfunc
953
954" Test for using submatch() with a multiline match
955func Test_substitute_multiline_submatch()
956 new
957 call setline(1, ['line1', 'line2', 'line3', 'line4'])
958 %s/^line1\(\_.\+\)line4$/\=submatch(1)/
959 call assert_equal(['', 'line2', 'line3', ''], getline(1, '$'))
960 close!
Bram Moolenaarca68ae12020-03-30 19:32:53 +0200961endfunc
962
Bram Moolenaardf365142021-05-03 20:01:45 +0200963func Test_substitute_skipped_range()
964 new
965 if 0
966 /1/5/2/2/\n
967 endif
968 call assert_equal([0, 1, 1, 0, 1], getcurpos())
969 bwipe!
970endfunc
971
Dominique Pellebfb2bb12021-08-14 21:11:51 +0200972" Test using the 'gdefault' option (when on, flag 'g' is default on).
973func Test_substitute_gdefault()
974 new
975
976 " First check without 'gdefault'
977 call setline(1, 'foo bar foo')
978 s/foo/FOO/
979 call assert_equal('FOO bar foo', getline(1))
980 call setline(1, 'foo bar foo')
981 s/foo/FOO/g
982 call assert_equal('FOO bar FOO', getline(1))
983 call setline(1, 'foo bar foo')
984 s/foo/FOO/gg
985 call assert_equal('FOO bar foo', getline(1))
986
987 " Then check with 'gdefault'
988 set gdefault
989 call setline(1, 'foo bar foo')
990 s/foo/FOO/
991 call assert_equal('FOO bar FOO', getline(1))
992 call setline(1, 'foo bar foo')
993 s/foo/FOO/g
994 call assert_equal('FOO bar foo', getline(1))
995 call setline(1, 'foo bar foo')
996 s/foo/FOO/gg
997 call assert_equal('FOO bar FOO', getline(1))
998
999 " Setting 'compatible' should reset 'gdefault'
1000 call assert_equal(1, &gdefault)
1001 set compatible
1002 call assert_equal(0, &gdefault)
1003 set nocompatible
1004 call assert_equal(0, &gdefault)
1005
1006 bw!
1007endfunc
1008
Bram Moolenaar37f47952022-01-29 14:21:51 +00001009" This was using "old_sub" after it was freed.
1010func Test_using_old_sub()
1011 set compatible maxfuncdepth=10
1012 new
1013 call setline(1, 'some text.')
1014 func Repl()
1015 ~
1016 s/
1017 endfunc
Bram Moolenaar44ddf192022-06-21 22:15:25 +01001018 silent! s/\%')/\=Repl()
Bram Moolenaar37f47952022-01-29 14:21:51 +00001019
1020 delfunc Repl
1021 bwipe!
1022 set nocompatible
1023endfunc
1024
Bram Moolenaare2bd8602022-05-18 13:11:57 +01001025" This was switching windows in between computing the length and using it.
1026func Test_sub_change_window()
1027 silent! lfile
1028 sil! norm o0000000000000000000000000000000000000000000000000000
1029 func Repl()
1030 lopen
1031 endfunc
1032 silent! s/\%')/\=Repl()
1033 bwipe!
1034 bwipe!
1035 delfunc Repl
1036endfunc
1037
Bram Moolenaar338f1fc2022-05-26 15:56:23 +01001038" This was undoign a change in between computing the length and using it.
1039func Do_Test_sub_undo_change()
1040 new
1041 norm o0000000000000000000000000000000000000000000000000000
1042 silent! s/\%')/\=Repl()
1043 bwipe!
1044endfunc
1045
1046func Test_sub_undo_change()
1047 func Repl()
1048 silent! norm g-
1049 endfunc
1050 call Do_Test_sub_undo_change()
1051
1052 func! Repl()
1053 silent earlier
1054 endfunc
1055 call Do_Test_sub_undo_change()
1056
1057 delfunc Repl
1058endfunc
1059
Bram Moolenaar71223e22022-05-30 15:23:09 +01001060" This was opening a command line window from the expression
1061func Test_sub_open_cmdline_win()
1062 " the error only happens in a very specific setup, run a new Vim instance to
1063 " get a clean starting point.
1064 let lines =<< trim [SCRIPT]
Bram Moolenaarbe990422022-05-30 16:01:42 +01001065 set vb t_vb=
Bram Moolenaar71223e22022-05-30 15:23:09 +01001066 norm o0000000000000000000000000000000000000000000000000000
1067 func Replace()
1068 norm q/
1069 endfunc
1070 s/\%')/\=Replace()
1071 redir >Xresult
1072 messages
1073 redir END
1074 qall!
1075 [SCRIPT]
1076 call writefile(lines, 'Xscript')
1077 if RunVim([], [], '-u NONE -S Xscript')
Bram Moolenaarbe990422022-05-30 16:01:42 +01001078 call assert_match('E565: Not allowed to change text or change window',
1079 \ readfile('Xresult')->join('XX'))
Bram Moolenaar71223e22022-05-30 15:23:09 +01001080 endif
1081
1082 call delete('Xscript')
1083 call delete('Xresult')
1084endfunc
1085
Bram Moolenaard6211a52022-06-18 19:48:14 +01001086" This was editing a script file from the expression
1087func Test_sub_edit_scriptfile()
1088 new
1089 norm o0000000000000000000000000000000000000000000000000000
1090 func EditScript()
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001091 silent! scr! Xsedfile
Bram Moolenaard6211a52022-06-18 19:48:14 +01001092 endfunc
1093 s/\%')/\=EditScript()
1094
1095 delfunc EditScript
1096 bwipe!
1097endfunc
1098
Yegappan Lakshmanan5e877ba2022-03-25 21:19:26 +00001099" Test for the 2-letter and 3-letter :substitute commands
1100func Test_substitute_short_cmd()
1101 new
1102 call setline(1, ['one', 'one one one'])
1103 s/one/two
1104 call cursor(2, 1)
1105
1106 " :sc
1107 call feedkeys(":sc\<CR>y", 'xt')
1108 call assert_equal('two one one', getline(2))
1109
1110 " :scg
1111 call setline(2, 'one one one')
1112 call feedkeys(":scg\<CR>nyq", 'xt')
1113 call assert_equal('one two one', getline(2))
1114
1115 " :sci
1116 call setline(2, 'ONE One onE')
1117 call feedkeys(":sci\<CR>y", 'xt')
1118 call assert_equal('two One onE', getline(2))
1119
1120 " :scI
1121 set ignorecase
1122 call setline(2, 'ONE One one')
1123 call feedkeys(":scI\<CR>y", 'xt')
1124 call assert_equal('ONE One two', getline(2))
1125 set ignorecase&
1126
1127 " :scn
1128 call setline(2, 'one one one')
1129 let t = execute('scn')->split("\n")
1130 call assert_equal(['1 match on 1 line'], t)
1131 call assert_equal('one one one', getline(2))
1132
1133 " :scp
1134 call setline(2, "\tone one one")
1135 redir => output
1136 call feedkeys(":scp\<CR>y", 'xt')
1137 redir END
1138 call assert_equal(' two one one', output->split("\n")[-1])
1139 call assert_equal("\ttwo one one", getline(2))
1140
1141 " :scl
1142 call setline(2, "\tone one one")
1143 redir => output
1144 call feedkeys(":scl\<CR>y", 'xt')
1145 redir END
1146 call assert_equal("^Itwo one one$", output->split("\n")[-1])
1147 call assert_equal("\ttwo one one", getline(2))
1148
1149 " :sgc
1150 call setline(2, 'one one one one one')
1151 call feedkeys(":sgc\<CR>nyyq", 'xt')
1152 call assert_equal('one two two one one', getline(2))
1153
1154 " :sg
1155 call setline(2, 'one one one')
1156 sg
1157 call assert_equal('two two two', getline(2))
1158
1159 " :sgi
1160 call setline(2, 'ONE One onE')
1161 sgi
1162 call assert_equal('two two two', getline(2))
1163
1164 " :sgI
1165 set ignorecase
1166 call setline(2, 'ONE One one')
1167 sgI
1168 call assert_equal('ONE One two', getline(2))
1169 set ignorecase&
1170
1171 " :sgn
1172 call setline(2, 'one one one')
1173 let t = execute('sgn')->split("\n")
1174 call assert_equal(['3 matches on 1 line'], t)
1175 call assert_equal('one one one', getline(2))
1176
1177 " :sgp
1178 call setline(2, "\tone one one")
1179 redir => output
1180 sgp
1181 redir END
1182 call assert_equal(' two two two', output->split("\n")[-1])
1183 call assert_equal("\ttwo two two", getline(2))
1184
1185 " :sgl
1186 call setline(2, "\tone one one")
1187 redir => output
1188 sgl
1189 redir END
1190 call assert_equal("^Itwo two two$", output->split("\n")[-1])
1191 call assert_equal("\ttwo two two", getline(2))
1192
1193 " :sgr
1194 call setline(2, "one one one")
1195 call cursor(2, 1)
1196 s/abc/xyz/e
1197 let @/ = 'one'
1198 sgr
1199 call assert_equal('xyz xyz xyz', getline(2))
1200
1201 " :sic
1202 call cursor(1, 1)
1203 s/one/two/e
1204 call setline(2, "ONE One one")
1205 call cursor(2, 1)
1206 call feedkeys(":sic\<CR>y", 'xt')
1207 call assert_equal('two One one', getline(2))
1208
1209 " :si
1210 call setline(2, "ONE One one")
1211 si
1212 call assert_equal('two One one', getline(2))
1213
1214 " :siI
1215 call setline(2, "ONE One one")
1216 siI
1217 call assert_equal('ONE One two', getline(2))
1218
1219 " :sin
1220 call setline(2, 'ONE One onE')
1221 let t = execute('sin')->split("\n")
1222 call assert_equal(['1 match on 1 line'], t)
1223 call assert_equal('ONE One onE', getline(2))
1224
1225 " :sip
1226 call setline(2, "\tONE One onE")
1227 redir => output
1228 sip
1229 redir END
1230 call assert_equal(' two One onE', output->split("\n")[-1])
1231 call assert_equal("\ttwo One onE", getline(2))
1232
1233 " :sir
1234 call setline(2, "ONE One onE")
1235 call cursor(2, 1)
1236 s/abc/xyz/e
1237 let @/ = 'one'
1238 sir
1239 call assert_equal('xyz One onE', getline(2))
1240
1241 " :sIc
1242 call cursor(1, 1)
1243 s/one/two/e
1244 call setline(2, "ONE One one")
1245 call cursor(2, 1)
1246 call feedkeys(":sIc\<CR>y", 'xt')
1247 call assert_equal('ONE One two', getline(2))
1248
1249 " :sIg
1250 call setline(2, "ONE one onE one")
1251 sIg
1252 call assert_equal('ONE two onE two', getline(2))
1253
1254 " :sIi
1255 call setline(2, "ONE One one")
1256 sIi
1257 call assert_equal('two One one', getline(2))
1258
1259 " :sI
1260 call setline(2, "ONE One one")
1261 sI
1262 call assert_equal('ONE One two', getline(2))
1263
1264 " :sIn
1265 call setline(2, 'ONE One one')
1266 let t = execute('sIn')->split("\n")
1267 call assert_equal(['1 match on 1 line'], t)
1268 call assert_equal('ONE One one', getline(2))
1269
1270 " :sIp
1271 call setline(2, "\tONE One one")
1272 redir => output
1273 sIp
1274 redir END
1275 call assert_equal(' ONE One two', output->split("\n")[-1])
1276 call assert_equal("\tONE One two", getline(2))
1277
1278 " :sIl
1279 call setline(2, "\tONE onE one")
1280 redir => output
1281 sIl
1282 redir END
1283 call assert_equal("^IONE onE two$", output->split("\n")[-1])
1284 call assert_equal("\tONE onE two", getline(2))
1285
1286 " :sIr
1287 call setline(2, "ONE one onE")
1288 call cursor(2, 1)
1289 s/abc/xyz/e
1290 let @/ = 'one'
1291 sIr
1292 call assert_equal('ONE xyz onE', getline(2))
1293
1294 " :src
1295 call setline(2, "ONE one one")
1296 call cursor(2, 1)
1297 s/abc/xyz/e
1298 let @/ = 'one'
1299 call feedkeys(":src\<CR>y", 'xt')
1300 call assert_equal('ONE xyz one', getline(2))
1301
1302 " :srg
1303 call setline(2, "one one one")
1304 call cursor(2, 1)
1305 s/abc/xyz/e
1306 let @/ = 'one'
1307 srg
1308 call assert_equal('xyz xyz xyz', getline(2))
1309
1310 " :sri
1311 call setline(2, "ONE one onE")
1312 call cursor(2, 1)
1313 s/abc/xyz/e
1314 let @/ = 'one'
1315 sri
1316 call assert_equal('xyz one onE', getline(2))
1317
1318 " :srI
1319 call setline(2, "ONE one onE")
1320 call cursor(2, 1)
1321 s/abc/xyz/e
1322 let @/ = 'one'
1323 srI
1324 call assert_equal('ONE xyz onE', getline(2))
1325
1326 " :srn
1327 call setline(2, "ONE one onE")
1328 call cursor(2, 1)
1329 s/abc/xyz/e
1330 let @/ = 'one'
1331 let t = execute('srn')->split("\n")
1332 call assert_equal(['1 match on 1 line'], t)
1333 call assert_equal('ONE one onE', getline(2))
1334
1335 " :srp
1336 call setline(2, "\tONE one onE")
1337 call cursor(2, 1)
1338 s/abc/xyz/e
1339 let @/ = 'one'
1340 redir => output
1341 srp
1342 redir END
1343 call assert_equal(' ONE xyz onE', output->split("\n")[-1])
1344 call assert_equal("\tONE xyz onE", getline(2))
1345
1346 " :srl
1347 call setline(2, "\tONE one onE")
1348 call cursor(2, 1)
1349 s/abc/xyz/e
1350 let @/ = 'one'
1351 redir => output
1352 srl
1353 redir END
1354 call assert_equal("^IONE xyz onE$", output->split("\n")[-1])
1355 call assert_equal("\tONE xyz onE", getline(2))
1356
1357 " :sr
1358 call setline(2, "ONE one onE")
1359 call cursor(2, 1)
1360 s/abc/xyz/e
1361 let @/ = 'one'
1362 sr
1363 call assert_equal('ONE xyz onE', getline(2))
1364
1365 " :sce
1366 s/abc/xyz/e
1367 call assert_fails("sc", 'E486:')
1368 sce
1369 " :sge
1370 call assert_fails("sg", 'E486:')
1371 sge
1372 " :sie
1373 call assert_fails("si", 'E486:')
1374 sie
1375 " :sIe
1376 call assert_fails("sI", 'E486:')
1377 sIe
1378
1379 bw!
1380endfunc
Bram Moolenaar37f47952022-01-29 14:21:51 +00001381
Bram Moolenaar44ddf192022-06-21 22:15:25 +01001382" This should be done last to reveal a memory leak when vim_regsub_both() is
1383" called to evaluate an expression but it is not used in a second call.
1384func Test_z_substitute_expr_leak()
1385 func SubExpr()
1386 ~n
1387 endfunc
1388 silent! s/\%')/\=SubExpr()
1389 delfunc SubExpr
1390endfunc
1391
Bram Moolenaar5d98dc22020-01-29 21:57:34 +01001392" vim: shiftwidth=2 sts=2 expandtab