blob: 920473ddbca21e1e1f980417beddf1e847a6328d [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
zeertzjqabd58d82022-09-16 16:06:32 +0100445def SubReplacerVar9(text: string, ...args: list<list<string>>): string
446 return text .. args[0][0] .. text
447enddef
Bram Moolenaar4c054e92019-11-10 00:13:50 +0100448func SubReplacer20(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, submatches)
449 return a:t3 .. a:submatches[0] .. a:t11
450endfunc
Bram Moolenaarb0745b22019-11-09 22:28:11 +0100451
452func Test_substitute_partial()
zeertzjq48db5da2022-09-16 12:10:03 +0100453 call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacer', ['foo']), 'g'))
454 call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacerVar', ['foo']), 'g'))
zeertzjqabd58d82022-09-16 16:06:32 +0100455 call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacerVar9', ['foo']), 'g'))
Bram Moolenaar4c054e92019-11-10 00:13:50 +0100456
zeertzjq48db5da2022-09-16 12:10:03 +0100457 " 19 arguments plus one is just OK
458 let Replacer = function('SubReplacer20', repeat(['foo'], 19))
459 call assert_equal('1foo2foo3', substitute('123', '2', Replacer, 'g'))
Bram Moolenaar4c054e92019-11-10 00:13:50 +0100460
zeertzjq48db5da2022-09-16 12:10:03 +0100461 " 20 arguments plus one is too many
462 let Replacer = function('SubReplacer20', repeat(['foo'], 20))
463 call assert_fails("call substitute('123', '2', Replacer, 'g')", 'E118:')
Bram Moolenaarb0745b22019-11-09 22:28:11 +0100464endfunc
465
Bram Moolenaar7a2217b2021-06-06 12:33:49 +0200466func Test_substitute_float()
Bram Moolenaar7a2217b2021-06-06 12:33:49 +0200467 call assert_equal('number 1.23', substitute('number ', '$', { -> 1.23 }, ''))
468 vim9 assert_equal('number 1.23', substitute('number ', '$', () => 1.23, ''))
469endfunc
470
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200471" Tests for *sub-replace-special* and *sub-replace-expression* on :substitute.
472
473" Execute a list of :substitute command tests
474func Run_SubCmd_Tests(tests)
475 enew!
476 for t in a:tests
477 let start = line('.') + 1
478 let end = start + len(t[2]) - 1
479 exe "normal o" . t[0]
480 call cursor(start, 1)
481 exe t[1]
482 call assert_equal(t[2], getline(start, end), t[1])
483 endfor
484 enew!
485endfunc
486
487func Test_sub_cmd_1()
488 set magic
489 set cpo&
490
491 " List entry format: [input, cmd, output]
492 let tests = [['A', 's/A/&&/', ['AA']],
493 \ ['B', 's/B/\&/', ['&']],
494 \ ['C123456789', 's/C\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\0\9\8\7\6\5\4\3\2\1/', ['C123456789987654321']],
495 \ ['D', 's/D/d/', ['d']],
496 \ ['E', 's/E/~/', ['d']],
497 \ ['F', 's/F/\~/', ['~']],
498 \ ['G', 's/G/\ugg/', ['Gg']],
499 \ ['H', 's/H/\Uh\Eh/', ['Hh']],
500 \ ['I', 's/I/\lII/', ['iI']],
501 \ ['J', 's/J/\LJ\EJ/', ['jJ']],
502 \ ['K', 's/K/\Uk\ek/', ['Kk']],
503 \ ['lLl', "s/L/\<C-V>\<C-M>/", ["l\<C-V>", 'l']],
504 \ ['mMm', 's/M/\r/', ['m', 'm']],
505 \ ['nNn', "s/N/\\\<C-V>\<C-M>/", ["n\<C-V>", 'n']],
506 \ ['oOo', 's/O/\n/', ["o\no"]],
507 \ ['pPp', 's/P/\b/', ["p\<C-H>p"]],
508 \ ['qQq', 's/Q/\t/', ["q\tq"]],
509 \ ['rRr', 's/R/\\/', ['r\r']],
510 \ ['sSs', 's/S/\c/', ['scs']],
511 \ ['tTt', "s/T/\<C-V>\<C-J>/", ["t\<C-V>\<C-J>t"]],
512 \ ['U', 's/U/\L\uuUu\l\EU/', ['UuuU']],
zeertzjq3269efd2022-06-12 11:13:05 +0100513 \ ['V', 's/V/\U\lVvV\u\Ev/', ['vVVv']],
514 \ ['\', 's/\\/\\\\/', ['\\']]
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200515 \ ]
516 call Run_SubCmd_Tests(tests)
517endfunc
518
519func Test_sub_cmd_2()
520 set nomagic
521 set cpo&
522
523 " List entry format: [input, cmd, output]
524 let tests = [['A', 's/A/&&/', ['&&']],
525 \ ['B', 's/B/\&/', ['B']],
526 \ ['C123456789', 's/\mC\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\0\9\8\7\6\5\4\3\2\1/', ['C123456789987654321']],
527 \ ['D', 's/D/d/', ['d']],
528 \ ['E', 's/E/~/', ['~']],
529 \ ['F', 's/F/\~/', ['~']],
530 \ ['G', 's/G/\ugg/', ['Gg']],
531 \ ['H', 's/H/\Uh\Eh/', ['Hh']],
532 \ ['I', 's/I/\lII/', ['iI']],
533 \ ['J', 's/J/\LJ\EJ/', ['jJ']],
534 \ ['K', 's/K/\Uk\ek/', ['Kk']],
535 \ ['lLl', "s/L/\<C-V>\<C-M>/", ["l\<C-V>", 'l']],
536 \ ['mMm', 's/M/\r/', ['m', 'm']],
537 \ ['nNn', "s/N/\\\<C-V>\<C-M>/", ["n\<C-V>", 'n']],
538 \ ['oOo', 's/O/\n/', ["o\no"]],
539 \ ['pPp', 's/P/\b/', ["p\<C-H>p"]],
540 \ ['qQq', 's/Q/\t/', ["q\tq"]],
541 \ ['rRr', 's/R/\\/', ['r\r']],
542 \ ['sSs', 's/S/\c/', ['scs']],
543 \ ['tTt', "s/T/\<C-V>\<C-J>/", ["t\<C-V>\<C-J>t"]],
544 \ ['U', 's/U/\L\uuUu\l\EU/', ['UuuU']],
zeertzjq3269efd2022-06-12 11:13:05 +0100545 \ ['V', 's/V/\U\lVvV\u\Ev/', ['vVVv']],
546 \ ['\', 's/\\/\\\\/', ['\\']]
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200547 \ ]
548 call Run_SubCmd_Tests(tests)
549endfunc
550
551func Test_sub_cmd_3()
552 set nomagic
553 set cpo&
554
555 " List entry format: [input, cmd, output]
556 let tests = [['aAa', "s/A/\\='\\'/", ['a\a']],
557 \ ['bBb', "s/B/\\='\\\\'/", ['b\\b']],
558 \ ['cCc', "s/C/\\='\<C-V>\<C-M>'/", ["c\<C-V>", 'c']],
559 \ ['dDd', "s/D/\\='\\\<C-V>\<C-M>'/", ["d\\\<C-V>", 'd']],
560 \ ['eEe', "s/E/\\='\\\\\<C-V>\<C-M>'/", ["e\\\\\<C-V>", 'e']],
561 \ ['fFf', "s/F/\\='\r'/", ['f', 'f']],
562 \ ['gGg', "s/G/\\='\<C-V>\<C-J>'/", ["g\<C-V>", 'g']],
563 \ ['hHh', "s/H/\\='\\\<C-V>\<C-J>'/", ["h\\\<C-V>", 'h']],
564 \ ['iIi', "s/I/\\='\\\\\<C-V>\<C-J>'/", ["i\\\\\<C-V>", 'i']],
565 \ ['jJj', "s/J/\\='\n'/", ['j', 'j']],
566 \ ['kKk', 's/K/\="\r"/', ['k', 'k']],
567 \ ['lLl', 's/L/\="\n"/', ['l', 'l']]
568 \ ]
569 call Run_SubCmd_Tests(tests)
570endfunc
571
Bram Moolenaarf1699962019-08-31 17:48:19 +0200572" Test for submatch() on :substitute.
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200573func Test_sub_cmd_4()
574 set magic&
575 set cpo&
576
577 " List entry format: [input, cmd, output]
578 let tests = [ ['aAa', "s/A/\\=substitute(submatch(0), '.', '\\', '')/",
Bram Moolenaar1e115362019-01-09 23:01:02 +0100579 \ ['a\a']],
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200580 \ ['bBb', "s/B/\\=substitute(submatch(0), '.', '\\', '')/",
Bram Moolenaar1e115362019-01-09 23:01:02 +0100581 \ ['b\b']],
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200582 \ ['cCc', "s/C/\\=substitute(submatch(0), '.', '\<C-V>\<C-M>', '')/",
583 \ ["c\<C-V>", 'c']],
584 \ ['dDd', "s/D/\\=substitute(submatch(0), '.', '\\\<C-V>\<C-M>', '')/",
585 \ ["d\<C-V>", 'd']],
586 \ ['eEe', "s/E/\\=substitute(submatch(0), '.', '\\\\\<C-V>\<C-M>', '')/",
587 \ ["e\\\<C-V>", 'e']],
588 \ ['fFf', "s/F/\\=substitute(submatch(0), '.', '\\r', '')/",
589 \ ['f', 'f']],
590 \ ['gGg', 's/G/\=substitute(submatch(0), ".", "\<C-V>\<C-J>", "")/',
591 \ ["g\<C-V>", 'g']],
592 \ ['hHh', 's/H/\=substitute(submatch(0), ".", "\\\<C-V>\<C-J>", "")/',
593 \ ["h\<C-V>", 'h']],
594 \ ['iIi', 's/I/\=substitute(submatch(0), ".", "\\\\\<C-V>\<C-J>", "")/',
595 \ ["i\\\<C-V>", 'i']],
596 \ ['jJj', "s/J/\\=substitute(submatch(0), '.', '\\n', '')/",
597 \ ['j', 'j']],
598 \ ['kKk', "s/K/\\=substitute(submatch(0), '.', '\\r', '')/",
599 \ ['k', 'k']],
600 \ ['lLl', "s/L/\\=substitute(submatch(0), '.', '\\n', '')/",
601 \ ['l', 'l']],
602 \ ]
603 call Run_SubCmd_Tests(tests)
604endfunc
605
606func Test_sub_cmd_5()
607 set magic&
608 set cpo&
609
610 " List entry format: [input, cmd, output]
611 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']],
612 \ ['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']]"]],
613 \ ]
614 call Run_SubCmd_Tests(tests)
615endfunc
616
617" Test for *:s%* on :substitute.
618func Test_sub_cmd_6()
619 set magic&
620 set cpo+=/
621
622 " List entry format: [input, cmd, output]
623 let tests = [ ['A', 's/A/a/', ['a']],
624 \ ['B', 's/B/%/', ['a']],
625 \ ]
626 call Run_SubCmd_Tests(tests)
627
628 set cpo-=/
629 let tests = [ ['C', 's/C/c/', ['c']],
630 \ ['D', 's/D/%/', ['%']],
631 \ ]
632 call Run_SubCmd_Tests(tests)
633
634 set cpo&
635endfunc
636
637" Test for :s replacing \n with line break.
638func Test_sub_cmd_7()
639 set magic&
640 set cpo&
641
642 " List entry format: [input, cmd, output]
643 let tests = [ ["A\<C-V>\<C-M>A", 's/A./\=submatch(0)/', ['A', 'A']],
644 \ ["B\<C-V>\<C-J>B", 's/B./\=submatch(0)/', ['B', 'B']],
645 \ ["C\<C-V>\<C-J>C", 's/C./\=strtrans(string(submatch(0, 1)))/', [strtrans("['C\<C-J>']C")]],
646 \ ["D\<C-V>\<C-J>\nD", 's/D.\nD/\=strtrans(string(submatch(0, 1)))/', [strtrans("['D\<C-J>', 'D']")]],
647 \ ["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']")]],
648 \ ]
649 call Run_SubCmd_Tests(tests)
650
651 exe "normal oQ\nQ\<Esc>k"
Bram Moolenaare2e40752020-09-04 21:18:46 +0200652 call assert_fails('s/Q[^\n]Q/\=submatch(0)."foobar"/', 'E486:')
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200653 enew!
654endfunc
655
656func TitleString()
657 let check = 'foo' =~ 'bar'
658 return ""
659endfunc
660
661func Test_sub_cmd_8()
662 set titlestring=%{TitleString()}
663
664 enew!
665 call append(0, ['', 'test_one', 'test_two'])
666 call cursor(1,1)
667 /^test_one/s/.*/\="foo\nbar"/
668 call assert_equal('foo', getline(2))
669 call assert_equal('bar', getline(3))
670 call feedkeys(':/^test_two/s/.*/\="foo\nbar"/c', "t")
671 call feedkeys("\<CR>y", "xt")
672 call assert_equal('foo', getline(4))
673 call assert_equal('bar', getline(5))
674
675 enew!
676 set titlestring&
677endfunc
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100678
Bram Moolenaar80341bc2019-05-20 20:34:51 +0200679func Test_sub_cmd_9()
680 new
681 let input = ['1 aaa', '2 aaa', '3 aaa']
682 call setline(1, input)
683 func Foo()
684 return submatch(0)
685 endfunc
686 %s/aaa/\=Foo()/gn
687 call assert_equal(input, getline(1, '$'))
688 call assert_equal(1, &modifiable)
689
690 delfunc Foo
691 bw!
692endfunc
693
Bram Moolenaara04f4572022-09-13 13:45:26 +0100694func Test_sub_highlight_zero_match()
695 CheckRunVimInTerminal
696
697 let lines =<< trim END
698 call setline(1, ['one', 'two', 'three'])
699 END
700 call writefile(lines, 'XscriptSubHighlight', 'D')
701 let buf = RunVimInTerminal('-S XscriptSubHighlight', #{rows: 8, cols: 60})
702 call term_sendkeys(buf, ":%s/^/ /c\<CR>")
703 call VerifyScreenDump(buf, 'Test_sub_highlight_zer_match_1', {})
704
705 call term_sendkeys(buf, "\<Esc>")
706 call StopVimInTerminal(buf)
707endfunc
708
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100709func Test_nocatch_sub_failure_handling()
Bram Moolenaar94722c52023-01-28 19:19:03 +0000710 " normal error results in all replacements
Bram Moolenaar80341bc2019-05-20 20:34:51 +0200711 func Foo()
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100712 foobar
713 endfunc
714 new
715 call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
zeertzjq3269efd2022-06-12 11:13:05 +0100716 " need silent! to avoid a delay when entering Insert mode
717 silent! %s/aaa/\=Foo()/g
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100718 call assert_equal(['1 0', '2 0', '3 0'], getline(1, 3))
719
zeertzjq3269efd2022-06-12 11:13:05 +0100720 " Throw without try-catch causes abort after the first line.
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100721 " We cannot test this, since it would stop executing the test script.
722
723 " try/catch does not result in any changes
724 func! Foo()
725 throw 'error'
726 endfunc
727 call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
728 let error_caught = 0
729 try
730 %s/aaa/\=Foo()/g
731 catch
732 let error_caught = 1
733 endtry
734 call assert_equal(1, error_caught)
735 call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3))
736
Bram Moolenaar6349e942019-05-18 13:41:22 +0200737 " Same, but using "n" flag so that "sandbox" gets set
738 call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
739 let error_caught = 0
740 try
741 %s/aaa/\=Foo()/gn
742 catch
743 let error_caught = 1
744 endtry
745 call assert_equal(1, error_caught)
746 call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3))
747
Bram Moolenaar80341bc2019-05-20 20:34:51 +0200748 delfunc Foo
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100749 bwipe!
750endfunc
Bram Moolenaarc6b37db2019-04-27 18:00:34 +0200751
752" Test ":s/pat/sub/" with different ~s in sub.
753func Test_replace_with_tilde()
754 new
755 " Set the last replace string to empty
756 s/^$//
757 call append(0, ['- Bug in "vPPPP" on this text:'])
758 normal gg
759 s/u/~u~/
760 call assert_equal('- Bug in "vPPPP" on this text:', getline(1))
761 s/i/~u~/
762 call assert_equal('- Bug uuun "vPPPP" on this text:', getline(1))
763 s/o/~~~/
764 call assert_equal('- Bug uuun "vPPPP" uuuuuuuuun this text:', getline(1))
765 close!
766endfunc
767
768func Test_replace_keeppatterns()
769 new
770 a
771foobar
772
773substitute foo asdf
774
775one two
776.
777
778 normal gg
779 /^substitute
780 s/foo/bar/
781 call assert_equal('foo', @/)
782 call assert_equal('substitute bar asdf', getline('.'))
783
784 /^substitute
785 keeppatterns s/asdf/xyz/
786 call assert_equal('^substitute', @/)
787 call assert_equal('substitute bar xyz', getline('.'))
788
789 exe "normal /bar /e\<CR>"
790 call assert_equal(15, col('.'))
791 normal -
792 keeppatterns /xyz
793 call assert_equal('bar ', @/)
794 call assert_equal('substitute bar xyz', getline('.'))
795 exe "normal 0dn"
796 call assert_equal('xyz', getline('.'))
797
798 close!
799endfunc
Bram Moolenaarbb265962019-10-31 04:38:36 +0100800
801func Test_sub_beyond_end()
802 new
803 call setline(1, '#')
804 let @/ = '^#\n\zs'
805 s///e
806 call assert_equal('#', getline(1))
807 bwipe!
808endfunc
Bram Moolenaar5d98dc22020-01-29 21:57:34 +0100809
Bram Moolenaarea3db912020-02-02 15:32:13 +0100810" Test for repeating last substitution using :~ and :&r
811func Test_repeat_last_sub()
812 new
813 call setline(1, ['blue green yellow orange white'])
814 s/blue/red/
815 let @/ = 'yellow'
816 ~
817 let @/ = 'white'
818 :&r
819 let @/ = 'green'
820 s//gray
821 call assert_equal('red gray red orange red', getline(1))
822 close!
823endfunc
824
825" Test for Vi compatible substitution:
826" \/{string}/, \?{string}? and \&{string}&
827func Test_sub_vi_compatibility()
828 new
829 call setline(1, ['blue green yellow orange blue'])
830 let @/ = 'orange'
831 s\/white/
832 let @/ = 'blue'
833 s\?amber?
834 let @/ = 'white'
835 s\&green&
836 call assert_equal('amber green yellow white green', getline(1))
837 close!
Bram Moolenaar9fb7b422022-03-05 21:13:26 +0000838
839 call assert_fails('vim9cmd s\/white/', 'E1270:')
840 call assert_fails('vim9cmd s\?white?', 'E1270:')
841 call assert_fails('vim9cmd s\&white&', 'E1270:')
Bram Moolenaarea3db912020-02-02 15:32:13 +0100842endfunc
843
844" Test for substitute with the new text longer than the original text
845func Test_sub_expand_text()
846 new
847 call setline(1, 'abcabcabcabcabcabcabcabc')
848 s/b/\=repeat('B', 10)/g
849 call assert_equal(repeat('aBBBBBBBBBBc', 8), getline(1))
850 close!
851endfunc
852
Bram Moolenaar07ada5f2020-02-05 20:38:22 +0100853" Test for command failures when the last substitute pattern is not set.
854func Test_sub_with_no_last_pat()
Bram Moolenaar9f6277b2020-02-11 22:04:02 +0100855 let lines =<< trim [SCRIPT]
856 call assert_fails('~', 'E33:')
Bram Moolenaar9b7bf9e2020-07-11 22:14:59 +0200857 call assert_fails('s//abc/g', 'E35:')
858 call assert_fails('s\/bar', 'E35:')
859 call assert_fails('s\&bar&', 'E33:')
Bram Moolenaar9f6277b2020-02-11 22:04:02 +0100860 call writefile(v:errors, 'Xresult')
861 qall!
862 [SCRIPT]
Bram Moolenaar56564962022-10-10 22:39:42 +0100863 call writefile(lines, 'Xscript', 'D')
Bram Moolenaar9f6277b2020-02-11 22:04:02 +0100864 if RunVim([], [], '--clean -S Xscript')
865 call assert_equal([], readfile('Xresult'))
866 endif
Bram Moolenaar07ada5f2020-02-05 20:38:22 +0100867
Bram Moolenaar9f6277b2020-02-11 22:04:02 +0100868 let lines =<< trim [SCRIPT]
869 set cpo+=/
870 call assert_fails('s/abc/%/', 'E33:')
871 call writefile(v:errors, 'Xresult')
872 qall!
873 [SCRIPT]
874 call writefile(lines, 'Xscript')
875 if RunVim([], [], '--clean -S Xscript')
876 call assert_equal([], readfile('Xresult'))
877 endif
878
Bram Moolenaar9f6277b2020-02-11 22:04:02 +0100879 call delete('Xresult')
Bram Moolenaar07ada5f2020-02-05 20:38:22 +0100880endfunc
881
Bram Moolenaarca68ae12020-03-30 19:32:53 +0200882func Test_substitute()
883 call assert_equal('a1a2a3a', substitute('123', '\zs', 'a', 'g'))
Bram Moolenaar004a6782020-04-11 17:09:31 +0200884 " Substitute with special keys
885 call assert_equal("a\<End>c", substitute('abc', "a.c", "a\<End>c", ''))
886endfunc
887
888func Test_substitute_expr()
889 let g:val = 'XXX'
890 call assert_equal('XXX', substitute('yyy', 'y*', '\=g:val', ''))
891 call assert_equal('XXX', substitute('yyy', 'y*', {-> g:val}, ''))
892 call assert_equal("-\u1b \uf2-", substitute("-%1b %f2-", '%\(\x\x\)',
893 \ '\=nr2char("0x" . submatch(1))', 'g'))
894 call assert_equal("-\u1b \uf2-", substitute("-%1b %f2-", '%\(\x\x\)',
895 \ {-> nr2char("0x" . submatch(1))}, 'g'))
896
897 call assert_equal('231', substitute('123', '\(.\)\(.\)\(.\)',
898 \ {-> submatch(2) . submatch(3) . submatch(1)}, ''))
899
900 func Recurse()
901 return substitute('yyy', 'y\(.\)y', {-> submatch(1)}, '')
902 endfunc
903 " recursive call works
904 call assert_equal('-y-x-', substitute('xxx', 'x\(.\)x', {-> '-' . Recurse() . '-' . submatch(1) . '-'}, ''))
905
906 call assert_fails("let s=submatch([])", 'E745:')
907 call assert_fails("let s=submatch(2, [])", 'E745:')
908endfunc
909
910func Test_invalid_submatch()
911 " This was causing invalid memory access in Vim-7.4.2232 and older
912 call assert_fails("call substitute('x', '.', {-> submatch(10)}, '')", 'E935:')
913 call assert_fails('eval submatch(-1)', 'E935:')
914 call assert_equal('', submatch(0))
915 call assert_equal('', submatch(1))
916 call assert_equal([], submatch(0, 1))
917 call assert_equal([], submatch(1, 1))
918endfunc
919
Bram Moolenaar8a0dcf42020-09-06 15:14:45 +0200920func Test_submatch_list_concatenate()
921 let pat = 'A\(.\)'
922 let Rep = {-> string([submatch(0, 1)] + [[submatch(1)]])}
923 call substitute('A1', pat, Rep, '')->assert_equal("[['A1'], ['1']]")
924endfunc
925
Bram Moolenaar004a6782020-04-11 17:09:31 +0200926func Test_substitute_expr_arg()
927 call assert_equal('123456789-123456789=', substitute('123456789',
928 \ '\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)',
929 \ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))
930
931 call assert_equal('123456-123456=789', substitute('123456789',
932 \ '\(.\)\(.\)\(.\)\(a*\)\(n*\)\(.\)\(.\)\(.\)\(x*\)',
933 \ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))
934
935 call assert_equal('123456789-123456789x=', substitute('123456789',
936 \ '\(.\)\(.\)\(.*\)',
937 \ {m -> m[0] . '-' . m[1] . m[2] . m[3] . 'x' . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))
938
939 call assert_fails("call substitute('xxx', '.', {m -> string(add(m, 'x'))}, '')", 'E742:')
940 call assert_fails("call substitute('xxx', '.', {m -> string(insert(m, 'x'))}, '')", 'E742:')
941 call assert_fails("call substitute('xxx', '.', {m -> string(extend(m, ['x']))}, '')", 'E742:')
942 call assert_fails("call substitute('xxx', '.', {m -> string(remove(m, 1))}, '')", 'E742:')
943endfunc
944
945" Test for using a function to supply the substitute string
946func Test_substitute_using_func()
947 func Xfunc()
948 return '1234'
949 endfunc
950 call assert_equal('a1234f', substitute('abcdef', 'b..e',
951 \ function("Xfunc"), ''))
952 delfunc Xfunc
953endfunc
954
955" Test for using submatch() with a multiline match
956func Test_substitute_multiline_submatch()
957 new
958 call setline(1, ['line1', 'line2', 'line3', 'line4'])
959 %s/^line1\(\_.\+\)line4$/\=submatch(1)/
960 call assert_equal(['', 'line2', 'line3', ''], getline(1, '$'))
961 close!
Bram Moolenaarca68ae12020-03-30 19:32:53 +0200962endfunc
963
Bram Moolenaardf365142021-05-03 20:01:45 +0200964func Test_substitute_skipped_range()
965 new
966 if 0
967 /1/5/2/2/\n
968 endif
969 call assert_equal([0, 1, 1, 0, 1], getcurpos())
970 bwipe!
971endfunc
972
Dominique Pellebfb2bb12021-08-14 21:11:51 +0200973" Test using the 'gdefault' option (when on, flag 'g' is default on).
974func Test_substitute_gdefault()
975 new
976
977 " First check without 'gdefault'
978 call setline(1, 'foo bar foo')
979 s/foo/FOO/
980 call assert_equal('FOO bar foo', getline(1))
981 call setline(1, 'foo bar foo')
982 s/foo/FOO/g
983 call assert_equal('FOO bar FOO', getline(1))
984 call setline(1, 'foo bar foo')
985 s/foo/FOO/gg
986 call assert_equal('FOO bar foo', getline(1))
987
988 " Then check with 'gdefault'
989 set gdefault
990 call setline(1, 'foo bar foo')
991 s/foo/FOO/
992 call assert_equal('FOO bar FOO', getline(1))
993 call setline(1, 'foo bar foo')
994 s/foo/FOO/g
995 call assert_equal('FOO bar foo', getline(1))
996 call setline(1, 'foo bar foo')
997 s/foo/FOO/gg
998 call assert_equal('FOO bar FOO', getline(1))
999
1000 " Setting 'compatible' should reset 'gdefault'
1001 call assert_equal(1, &gdefault)
1002 set compatible
1003 call assert_equal(0, &gdefault)
1004 set nocompatible
1005 call assert_equal(0, &gdefault)
1006
1007 bw!
1008endfunc
1009
Bram Moolenaar37f47952022-01-29 14:21:51 +00001010" This was using "old_sub" after it was freed.
1011func Test_using_old_sub()
1012 set compatible maxfuncdepth=10
1013 new
1014 call setline(1, 'some text.')
1015 func Repl()
1016 ~
1017 s/
1018 endfunc
Bram Moolenaar44ddf192022-06-21 22:15:25 +01001019 silent! s/\%')/\=Repl()
Bram Moolenaar37f47952022-01-29 14:21:51 +00001020
1021 delfunc Repl
1022 bwipe!
1023 set nocompatible
1024endfunc
1025
Bram Moolenaare2bd8602022-05-18 13:11:57 +01001026" This was switching windows in between computing the length and using it.
1027func Test_sub_change_window()
1028 silent! lfile
1029 sil! norm o0000000000000000000000000000000000000000000000000000
1030 func Repl()
1031 lopen
1032 endfunc
1033 silent! s/\%')/\=Repl()
1034 bwipe!
1035 bwipe!
1036 delfunc Repl
1037endfunc
1038
Bram Moolenaar338f1fc2022-05-26 15:56:23 +01001039" This was undoign a change in between computing the length and using it.
1040func Do_Test_sub_undo_change()
1041 new
1042 norm o0000000000000000000000000000000000000000000000000000
1043 silent! s/\%')/\=Repl()
1044 bwipe!
1045endfunc
1046
1047func Test_sub_undo_change()
1048 func Repl()
1049 silent! norm g-
1050 endfunc
1051 call Do_Test_sub_undo_change()
1052
1053 func! Repl()
1054 silent earlier
1055 endfunc
1056 call Do_Test_sub_undo_change()
1057
1058 delfunc Repl
1059endfunc
1060
Bram Moolenaar71223e22022-05-30 15:23:09 +01001061" This was opening a command line window from the expression
1062func Test_sub_open_cmdline_win()
1063 " the error only happens in a very specific setup, run a new Vim instance to
1064 " get a clean starting point.
1065 let lines =<< trim [SCRIPT]
Bram Moolenaarbe990422022-05-30 16:01:42 +01001066 set vb t_vb=
Bram Moolenaar71223e22022-05-30 15:23:09 +01001067 norm o0000000000000000000000000000000000000000000000000000
1068 func Replace()
1069 norm q/
1070 endfunc
1071 s/\%')/\=Replace()
1072 redir >Xresult
1073 messages
1074 redir END
1075 qall!
1076 [SCRIPT]
Bram Moolenaar56564962022-10-10 22:39:42 +01001077 call writefile(lines, 'Xscript', 'D')
Bram Moolenaar71223e22022-05-30 15:23:09 +01001078 if RunVim([], [], '-u NONE -S Xscript')
Bram Moolenaarbe990422022-05-30 16:01:42 +01001079 call assert_match('E565: Not allowed to change text or change window',
1080 \ readfile('Xresult')->join('XX'))
Bram Moolenaar71223e22022-05-30 15:23:09 +01001081 endif
1082
Bram Moolenaar71223e22022-05-30 15:23:09 +01001083 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
Bram Moolenaarcc762a42022-11-25 13:03:31 +00001099" This was editing another file from the expression.
1100func Test_sub_expr_goto_other_file()
1101 call writefile([''], 'Xfileone', 'D')
1102 enew!
1103 call setline(1, ['a', 'b', 'c', 'd',
1104 \ 'Xfileone zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'])
1105
1106 func g:SplitGotoFile()
1107 exe "sil! norm 0\<C-W>gf"
1108 return ''
1109 endfunc
1110
1111 $
1112 s/\%')/\=g:SplitGotoFile()
1113
1114 delfunc g:SplitGotoFile
1115 bwipe!
1116endfunc
1117
Bram Moolenaar3ac1d972023-01-04 17:17:54 +00001118func Test_recursive_expr_substitute()
1119 " this was reading invalid memory
1120 let lines =<< trim END
1121 func Repl(g, n)
1122 s
1123 r%:s000
1124 endfunc
1125 next 0
1126 let caught = 0
1127 s/\%')/\=Repl(0, 0)
1128 qall!
1129 END
1130 call writefile(lines, 'XexprSubst', 'D')
1131 call RunVim([], [], '--clean -S XexprSubst')
1132endfunc
1133
Yegappan Lakshmanan5e877ba2022-03-25 21:19:26 +00001134" Test for the 2-letter and 3-letter :substitute commands
1135func Test_substitute_short_cmd()
1136 new
1137 call setline(1, ['one', 'one one one'])
1138 s/one/two
1139 call cursor(2, 1)
1140
1141 " :sc
1142 call feedkeys(":sc\<CR>y", 'xt')
1143 call assert_equal('two one one', getline(2))
1144
1145 " :scg
1146 call setline(2, 'one one one')
1147 call feedkeys(":scg\<CR>nyq", 'xt')
1148 call assert_equal('one two one', getline(2))
1149
1150 " :sci
1151 call setline(2, 'ONE One onE')
1152 call feedkeys(":sci\<CR>y", 'xt')
1153 call assert_equal('two One onE', getline(2))
1154
1155 " :scI
1156 set ignorecase
1157 call setline(2, 'ONE One one')
1158 call feedkeys(":scI\<CR>y", 'xt')
1159 call assert_equal('ONE One two', getline(2))
1160 set ignorecase&
1161
1162 " :scn
1163 call setline(2, 'one one one')
1164 let t = execute('scn')->split("\n")
1165 call assert_equal(['1 match on 1 line'], t)
1166 call assert_equal('one one one', getline(2))
1167
1168 " :scp
1169 call setline(2, "\tone one one")
1170 redir => output
1171 call feedkeys(":scp\<CR>y", 'xt')
1172 redir END
1173 call assert_equal(' two one one', output->split("\n")[-1])
1174 call assert_equal("\ttwo one one", getline(2))
1175
1176 " :scl
1177 call setline(2, "\tone one one")
1178 redir => output
1179 call feedkeys(":scl\<CR>y", 'xt')
1180 redir END
1181 call assert_equal("^Itwo one one$", output->split("\n")[-1])
1182 call assert_equal("\ttwo one one", getline(2))
1183
1184 " :sgc
1185 call setline(2, 'one one one one one')
1186 call feedkeys(":sgc\<CR>nyyq", 'xt')
1187 call assert_equal('one two two one one', getline(2))
1188
1189 " :sg
1190 call setline(2, 'one one one')
1191 sg
1192 call assert_equal('two two two', getline(2))
1193
1194 " :sgi
1195 call setline(2, 'ONE One onE')
1196 sgi
1197 call assert_equal('two two two', getline(2))
1198
1199 " :sgI
1200 set ignorecase
1201 call setline(2, 'ONE One one')
1202 sgI
1203 call assert_equal('ONE One two', getline(2))
1204 set ignorecase&
1205
1206 " :sgn
1207 call setline(2, 'one one one')
1208 let t = execute('sgn')->split("\n")
1209 call assert_equal(['3 matches on 1 line'], t)
1210 call assert_equal('one one one', getline(2))
1211
1212 " :sgp
1213 call setline(2, "\tone one one")
1214 redir => output
1215 sgp
1216 redir END
1217 call assert_equal(' two two two', output->split("\n")[-1])
1218 call assert_equal("\ttwo two two", getline(2))
1219
1220 " :sgl
1221 call setline(2, "\tone one one")
1222 redir => output
1223 sgl
1224 redir END
1225 call assert_equal("^Itwo two two$", output->split("\n")[-1])
1226 call assert_equal("\ttwo two two", getline(2))
1227
1228 " :sgr
1229 call setline(2, "one one one")
1230 call cursor(2, 1)
1231 s/abc/xyz/e
1232 let @/ = 'one'
1233 sgr
1234 call assert_equal('xyz xyz xyz', getline(2))
1235
1236 " :sic
1237 call cursor(1, 1)
1238 s/one/two/e
1239 call setline(2, "ONE One one")
1240 call cursor(2, 1)
1241 call feedkeys(":sic\<CR>y", 'xt')
1242 call assert_equal('two One one', getline(2))
1243
1244 " :si
1245 call setline(2, "ONE One one")
1246 si
1247 call assert_equal('two One one', getline(2))
1248
1249 " :siI
1250 call setline(2, "ONE One one")
1251 siI
1252 call assert_equal('ONE One two', getline(2))
1253
1254 " :sin
1255 call setline(2, 'ONE One onE')
1256 let t = execute('sin')->split("\n")
1257 call assert_equal(['1 match on 1 line'], t)
1258 call assert_equal('ONE One onE', getline(2))
1259
1260 " :sip
1261 call setline(2, "\tONE One onE")
1262 redir => output
1263 sip
1264 redir END
1265 call assert_equal(' two One onE', output->split("\n")[-1])
1266 call assert_equal("\ttwo One onE", getline(2))
1267
1268 " :sir
1269 call setline(2, "ONE One onE")
1270 call cursor(2, 1)
1271 s/abc/xyz/e
1272 let @/ = 'one'
1273 sir
1274 call assert_equal('xyz One onE', getline(2))
1275
1276 " :sIc
1277 call cursor(1, 1)
1278 s/one/two/e
1279 call setline(2, "ONE One one")
1280 call cursor(2, 1)
1281 call feedkeys(":sIc\<CR>y", 'xt')
1282 call assert_equal('ONE One two', getline(2))
1283
1284 " :sIg
1285 call setline(2, "ONE one onE one")
1286 sIg
1287 call assert_equal('ONE two onE two', getline(2))
1288
1289 " :sIi
1290 call setline(2, "ONE One one")
1291 sIi
1292 call assert_equal('two One one', getline(2))
1293
1294 " :sI
1295 call setline(2, "ONE One one")
1296 sI
1297 call assert_equal('ONE One two', getline(2))
1298
1299 " :sIn
1300 call setline(2, 'ONE One one')
1301 let t = execute('sIn')->split("\n")
1302 call assert_equal(['1 match on 1 line'], t)
1303 call assert_equal('ONE One one', getline(2))
1304
1305 " :sIp
1306 call setline(2, "\tONE One one")
1307 redir => output
1308 sIp
1309 redir END
1310 call assert_equal(' ONE One two', output->split("\n")[-1])
1311 call assert_equal("\tONE One two", getline(2))
1312
1313 " :sIl
1314 call setline(2, "\tONE onE one")
1315 redir => output
1316 sIl
1317 redir END
1318 call assert_equal("^IONE onE two$", output->split("\n")[-1])
1319 call assert_equal("\tONE onE two", getline(2))
1320
1321 " :sIr
1322 call setline(2, "ONE one onE")
1323 call cursor(2, 1)
1324 s/abc/xyz/e
1325 let @/ = 'one'
1326 sIr
1327 call assert_equal('ONE xyz onE', getline(2))
1328
1329 " :src
1330 call setline(2, "ONE one one")
1331 call cursor(2, 1)
1332 s/abc/xyz/e
1333 let @/ = 'one'
1334 call feedkeys(":src\<CR>y", 'xt')
1335 call assert_equal('ONE xyz one', getline(2))
1336
1337 " :srg
1338 call setline(2, "one one one")
1339 call cursor(2, 1)
1340 s/abc/xyz/e
1341 let @/ = 'one'
1342 srg
1343 call assert_equal('xyz xyz xyz', getline(2))
1344
1345 " :sri
1346 call setline(2, "ONE one onE")
1347 call cursor(2, 1)
1348 s/abc/xyz/e
1349 let @/ = 'one'
1350 sri
1351 call assert_equal('xyz one onE', getline(2))
1352
1353 " :srI
1354 call setline(2, "ONE one onE")
1355 call cursor(2, 1)
1356 s/abc/xyz/e
1357 let @/ = 'one'
1358 srI
1359 call assert_equal('ONE xyz onE', getline(2))
1360
1361 " :srn
1362 call setline(2, "ONE one onE")
1363 call cursor(2, 1)
1364 s/abc/xyz/e
1365 let @/ = 'one'
1366 let t = execute('srn')->split("\n")
1367 call assert_equal(['1 match on 1 line'], t)
1368 call assert_equal('ONE one onE', getline(2))
1369
1370 " :srp
1371 call setline(2, "\tONE one onE")
1372 call cursor(2, 1)
1373 s/abc/xyz/e
1374 let @/ = 'one'
1375 redir => output
1376 srp
1377 redir END
1378 call assert_equal(' ONE xyz onE', output->split("\n")[-1])
1379 call assert_equal("\tONE xyz onE", getline(2))
1380
1381 " :srl
1382 call setline(2, "\tONE one onE")
1383 call cursor(2, 1)
1384 s/abc/xyz/e
1385 let @/ = 'one'
1386 redir => output
1387 srl
1388 redir END
1389 call assert_equal("^IONE xyz onE$", output->split("\n")[-1])
1390 call assert_equal("\tONE xyz onE", getline(2))
1391
1392 " :sr
1393 call setline(2, "ONE one onE")
1394 call cursor(2, 1)
1395 s/abc/xyz/e
1396 let @/ = 'one'
1397 sr
1398 call assert_equal('ONE xyz onE', getline(2))
1399
1400 " :sce
1401 s/abc/xyz/e
1402 call assert_fails("sc", 'E486:')
1403 sce
1404 " :sge
1405 call assert_fails("sg", 'E486:')
1406 sge
1407 " :sie
1408 call assert_fails("si", 'E486:')
1409 sie
1410 " :sIe
1411 call assert_fails("sI", 'E486:')
1412 sIe
1413
1414 bw!
1415endfunc
Bram Moolenaar37f47952022-01-29 14:21:51 +00001416
Bram Moolenaarab9a2d82023-05-09 21:15:30 +01001417" Check handling expanding "~" resulting in extremely long text.
Bram Moolenaar916d6dd2023-05-09 21:45:47 +01001418" FIXME: disabled, it takes too long to run on CI
Bram Moolenaara4467c42023-05-09 22:07:11 +01001419"func Test_substitute_tilde_too_long()
1420" enew!
1421"
1422" s/.*/ixxx
1423" s//~~~~~~~~~AAAAAAA@(
1424"
1425" " Either fails with "out of memory" or "text too long".
1426" " This can take a long time.
1427" call assert_fails('sil! norm &&&&&&&&&', ['E1240:\|E342:'])
1428"
1429" bwipe!
1430"endfunc
Bram Moolenaarab9a2d82023-05-09 21:15:30 +01001431
Bram Moolenaar44ddf192022-06-21 22:15:25 +01001432" This should be done last to reveal a memory leak when vim_regsub_both() is
1433" called to evaluate an expression but it is not used in a second call.
1434func Test_z_substitute_expr_leak()
1435 func SubExpr()
1436 ~n
1437 endfunc
1438 silent! s/\%')/\=SubExpr()
1439 delfunc SubExpr
1440endfunc
1441
Christian Brabandt18d27092023-09-06 19:53:36 +02001442func Test_substitute_expr_switch_win()
1443 func R()
1444 wincmd x
1445 return 'XXXX'
1446 endfunc
1447 new Xfoobar
1448 let bufnr = bufnr('%')
1449 put ="abcdef"
1450 silent! s/\%')/\=R()
1451 call assert_fails(':%s/./\=R()/g', 'E565')
1452 delfunc R
1453 exe bufnr .. "bw!"
1454endfunc
1455
Bram Moolenaar5d98dc22020-01-29 21:57:34 +01001456" vim: shiftwidth=2 sts=2 expandtab