blob: 9bbe99763cae3e6269ce0459d3eb8e87f47c4c87 [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()
467 CheckFeature float
468
469 call assert_equal('number 1.23', substitute('number ', '$', { -> 1.23 }, ''))
470 vim9 assert_equal('number 1.23', substitute('number ', '$', () => 1.23, ''))
471endfunc
472
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200473" Tests for *sub-replace-special* and *sub-replace-expression* on :substitute.
474
475" Execute a list of :substitute command tests
476func Run_SubCmd_Tests(tests)
477 enew!
478 for t in a:tests
479 let start = line('.') + 1
480 let end = start + len(t[2]) - 1
481 exe "normal o" . t[0]
482 call cursor(start, 1)
483 exe t[1]
484 call assert_equal(t[2], getline(start, end), t[1])
485 endfor
486 enew!
487endfunc
488
489func Test_sub_cmd_1()
490 set magic
491 set cpo&
492
493 " List entry format: [input, cmd, output]
494 let tests = [['A', 's/A/&&/', ['AA']],
495 \ ['B', 's/B/\&/', ['&']],
496 \ ['C123456789', 's/C\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\0\9\8\7\6\5\4\3\2\1/', ['C123456789987654321']],
497 \ ['D', 's/D/d/', ['d']],
498 \ ['E', 's/E/~/', ['d']],
499 \ ['F', 's/F/\~/', ['~']],
500 \ ['G', 's/G/\ugg/', ['Gg']],
501 \ ['H', 's/H/\Uh\Eh/', ['Hh']],
502 \ ['I', 's/I/\lII/', ['iI']],
503 \ ['J', 's/J/\LJ\EJ/', ['jJ']],
504 \ ['K', 's/K/\Uk\ek/', ['Kk']],
505 \ ['lLl', "s/L/\<C-V>\<C-M>/", ["l\<C-V>", 'l']],
506 \ ['mMm', 's/M/\r/', ['m', 'm']],
507 \ ['nNn', "s/N/\\\<C-V>\<C-M>/", ["n\<C-V>", 'n']],
508 \ ['oOo', 's/O/\n/', ["o\no"]],
509 \ ['pPp', 's/P/\b/', ["p\<C-H>p"]],
510 \ ['qQq', 's/Q/\t/', ["q\tq"]],
511 \ ['rRr', 's/R/\\/', ['r\r']],
512 \ ['sSs', 's/S/\c/', ['scs']],
513 \ ['tTt', "s/T/\<C-V>\<C-J>/", ["t\<C-V>\<C-J>t"]],
514 \ ['U', 's/U/\L\uuUu\l\EU/', ['UuuU']],
zeertzjq3269efd2022-06-12 11:13:05 +0100515 \ ['V', 's/V/\U\lVvV\u\Ev/', ['vVVv']],
516 \ ['\', 's/\\/\\\\/', ['\\']]
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200517 \ ]
518 call Run_SubCmd_Tests(tests)
519endfunc
520
521func Test_sub_cmd_2()
522 set nomagic
523 set cpo&
524
525 " List entry format: [input, cmd, output]
526 let tests = [['A', 's/A/&&/', ['&&']],
527 \ ['B', 's/B/\&/', ['B']],
528 \ ['C123456789', 's/\mC\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\0\9\8\7\6\5\4\3\2\1/', ['C123456789987654321']],
529 \ ['D', 's/D/d/', ['d']],
530 \ ['E', 's/E/~/', ['~']],
531 \ ['F', 's/F/\~/', ['~']],
532 \ ['G', 's/G/\ugg/', ['Gg']],
533 \ ['H', 's/H/\Uh\Eh/', ['Hh']],
534 \ ['I', 's/I/\lII/', ['iI']],
535 \ ['J', 's/J/\LJ\EJ/', ['jJ']],
536 \ ['K', 's/K/\Uk\ek/', ['Kk']],
537 \ ['lLl', "s/L/\<C-V>\<C-M>/", ["l\<C-V>", 'l']],
538 \ ['mMm', 's/M/\r/', ['m', 'm']],
539 \ ['nNn', "s/N/\\\<C-V>\<C-M>/", ["n\<C-V>", 'n']],
540 \ ['oOo', 's/O/\n/', ["o\no"]],
541 \ ['pPp', 's/P/\b/', ["p\<C-H>p"]],
542 \ ['qQq', 's/Q/\t/', ["q\tq"]],
543 \ ['rRr', 's/R/\\/', ['r\r']],
544 \ ['sSs', 's/S/\c/', ['scs']],
545 \ ['tTt', "s/T/\<C-V>\<C-J>/", ["t\<C-V>\<C-J>t"]],
546 \ ['U', 's/U/\L\uuUu\l\EU/', ['UuuU']],
zeertzjq3269efd2022-06-12 11:13:05 +0100547 \ ['V', 's/V/\U\lVvV\u\Ev/', ['vVVv']],
548 \ ['\', 's/\\/\\\\/', ['\\']]
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200549 \ ]
550 call Run_SubCmd_Tests(tests)
551endfunc
552
553func Test_sub_cmd_3()
554 set nomagic
555 set cpo&
556
557 " List entry format: [input, cmd, output]
558 let tests = [['aAa', "s/A/\\='\\'/", ['a\a']],
559 \ ['bBb', "s/B/\\='\\\\'/", ['b\\b']],
560 \ ['cCc', "s/C/\\='\<C-V>\<C-M>'/", ["c\<C-V>", 'c']],
561 \ ['dDd', "s/D/\\='\\\<C-V>\<C-M>'/", ["d\\\<C-V>", 'd']],
562 \ ['eEe', "s/E/\\='\\\\\<C-V>\<C-M>'/", ["e\\\\\<C-V>", 'e']],
563 \ ['fFf', "s/F/\\='\r'/", ['f', 'f']],
564 \ ['gGg', "s/G/\\='\<C-V>\<C-J>'/", ["g\<C-V>", 'g']],
565 \ ['hHh', "s/H/\\='\\\<C-V>\<C-J>'/", ["h\\\<C-V>", 'h']],
566 \ ['iIi', "s/I/\\='\\\\\<C-V>\<C-J>'/", ["i\\\\\<C-V>", 'i']],
567 \ ['jJj', "s/J/\\='\n'/", ['j', 'j']],
568 \ ['kKk', 's/K/\="\r"/', ['k', 'k']],
569 \ ['lLl', 's/L/\="\n"/', ['l', 'l']]
570 \ ]
571 call Run_SubCmd_Tests(tests)
572endfunc
573
Bram Moolenaarf1699962019-08-31 17:48:19 +0200574" Test for submatch() on :substitute.
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200575func Test_sub_cmd_4()
576 set magic&
577 set cpo&
578
579 " List entry format: [input, cmd, output]
580 let tests = [ ['aAa', "s/A/\\=substitute(submatch(0), '.', '\\', '')/",
Bram Moolenaar1e115362019-01-09 23:01:02 +0100581 \ ['a\a']],
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200582 \ ['bBb', "s/B/\\=substitute(submatch(0), '.', '\\', '')/",
Bram Moolenaar1e115362019-01-09 23:01:02 +0100583 \ ['b\b']],
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200584 \ ['cCc', "s/C/\\=substitute(submatch(0), '.', '\<C-V>\<C-M>', '')/",
585 \ ["c\<C-V>", 'c']],
586 \ ['dDd', "s/D/\\=substitute(submatch(0), '.', '\\\<C-V>\<C-M>', '')/",
587 \ ["d\<C-V>", 'd']],
588 \ ['eEe', "s/E/\\=substitute(submatch(0), '.', '\\\\\<C-V>\<C-M>', '')/",
589 \ ["e\\\<C-V>", 'e']],
590 \ ['fFf', "s/F/\\=substitute(submatch(0), '.', '\\r', '')/",
591 \ ['f', 'f']],
592 \ ['gGg', 's/G/\=substitute(submatch(0), ".", "\<C-V>\<C-J>", "")/',
593 \ ["g\<C-V>", 'g']],
594 \ ['hHh', 's/H/\=substitute(submatch(0), ".", "\\\<C-V>\<C-J>", "")/',
595 \ ["h\<C-V>", 'h']],
596 \ ['iIi', 's/I/\=substitute(submatch(0), ".", "\\\\\<C-V>\<C-J>", "")/',
597 \ ["i\\\<C-V>", 'i']],
598 \ ['jJj', "s/J/\\=substitute(submatch(0), '.', '\\n', '')/",
599 \ ['j', 'j']],
600 \ ['kKk', "s/K/\\=substitute(submatch(0), '.', '\\r', '')/",
601 \ ['k', 'k']],
602 \ ['lLl', "s/L/\\=substitute(submatch(0), '.', '\\n', '')/",
603 \ ['l', 'l']],
604 \ ]
605 call Run_SubCmd_Tests(tests)
606endfunc
607
608func Test_sub_cmd_5()
609 set magic&
610 set cpo&
611
612 " List entry format: [input, cmd, output]
613 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']],
614 \ ['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']]"]],
615 \ ]
616 call Run_SubCmd_Tests(tests)
617endfunc
618
619" Test for *:s%* on :substitute.
620func Test_sub_cmd_6()
621 set magic&
622 set cpo+=/
623
624 " List entry format: [input, cmd, output]
625 let tests = [ ['A', 's/A/a/', ['a']],
626 \ ['B', 's/B/%/', ['a']],
627 \ ]
628 call Run_SubCmd_Tests(tests)
629
630 set cpo-=/
631 let tests = [ ['C', 's/C/c/', ['c']],
632 \ ['D', 's/D/%/', ['%']],
633 \ ]
634 call Run_SubCmd_Tests(tests)
635
636 set cpo&
637endfunc
638
639" Test for :s replacing \n with line break.
640func Test_sub_cmd_7()
641 set magic&
642 set cpo&
643
644 " List entry format: [input, cmd, output]
645 let tests = [ ["A\<C-V>\<C-M>A", 's/A./\=submatch(0)/', ['A', 'A']],
646 \ ["B\<C-V>\<C-J>B", 's/B./\=submatch(0)/', ['B', 'B']],
647 \ ["C\<C-V>\<C-J>C", 's/C./\=strtrans(string(submatch(0, 1)))/', [strtrans("['C\<C-J>']C")]],
648 \ ["D\<C-V>\<C-J>\nD", 's/D.\nD/\=strtrans(string(submatch(0, 1)))/', [strtrans("['D\<C-J>', 'D']")]],
649 \ ["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']")]],
650 \ ]
651 call Run_SubCmd_Tests(tests)
652
653 exe "normal oQ\nQ\<Esc>k"
Bram Moolenaare2e40752020-09-04 21:18:46 +0200654 call assert_fails('s/Q[^\n]Q/\=submatch(0)."foobar"/', 'E486:')
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200655 enew!
656endfunc
657
658func TitleString()
659 let check = 'foo' =~ 'bar'
660 return ""
661endfunc
662
663func Test_sub_cmd_8()
664 set titlestring=%{TitleString()}
665
666 enew!
667 call append(0, ['', 'test_one', 'test_two'])
668 call cursor(1,1)
669 /^test_one/s/.*/\="foo\nbar"/
670 call assert_equal('foo', getline(2))
671 call assert_equal('bar', getline(3))
672 call feedkeys(':/^test_two/s/.*/\="foo\nbar"/c', "t")
673 call feedkeys("\<CR>y", "xt")
674 call assert_equal('foo', getline(4))
675 call assert_equal('bar', getline(5))
676
677 enew!
678 set titlestring&
679endfunc
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100680
Bram Moolenaar80341bc2019-05-20 20:34:51 +0200681func Test_sub_cmd_9()
682 new
683 let input = ['1 aaa', '2 aaa', '3 aaa']
684 call setline(1, input)
685 func Foo()
686 return submatch(0)
687 endfunc
688 %s/aaa/\=Foo()/gn
689 call assert_equal(input, getline(1, '$'))
690 call assert_equal(1, &modifiable)
691
692 delfunc Foo
693 bw!
694endfunc
695
Bram Moolenaara04f4572022-09-13 13:45:26 +0100696func Test_sub_highlight_zero_match()
697 CheckRunVimInTerminal
698
699 let lines =<< trim END
700 call setline(1, ['one', 'two', 'three'])
701 END
702 call writefile(lines, 'XscriptSubHighlight', 'D')
703 let buf = RunVimInTerminal('-S XscriptSubHighlight', #{rows: 8, cols: 60})
704 call term_sendkeys(buf, ":%s/^/ /c\<CR>")
705 call VerifyScreenDump(buf, 'Test_sub_highlight_zer_match_1', {})
706
707 call term_sendkeys(buf, "\<Esc>")
708 call StopVimInTerminal(buf)
709endfunc
710
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100711func Test_nocatch_sub_failure_handling()
712 " normal error results in all replacements
Bram Moolenaar80341bc2019-05-20 20:34:51 +0200713 func Foo()
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100714 foobar
715 endfunc
716 new
717 call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
zeertzjq3269efd2022-06-12 11:13:05 +0100718 " need silent! to avoid a delay when entering Insert mode
719 silent! %s/aaa/\=Foo()/g
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100720 call assert_equal(['1 0', '2 0', '3 0'], getline(1, 3))
721
zeertzjq3269efd2022-06-12 11:13:05 +0100722 " Throw without try-catch causes abort after the first line.
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100723 " We cannot test this, since it would stop executing the test script.
724
725 " try/catch does not result in any changes
726 func! Foo()
727 throw 'error'
728 endfunc
729 call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
730 let error_caught = 0
731 try
732 %s/aaa/\=Foo()/g
733 catch
734 let error_caught = 1
735 endtry
736 call assert_equal(1, error_caught)
737 call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3))
738
Bram Moolenaar6349e942019-05-18 13:41:22 +0200739 " Same, but using "n" flag so that "sandbox" gets set
740 call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
741 let error_caught = 0
742 try
743 %s/aaa/\=Foo()/gn
744 catch
745 let error_caught = 1
746 endtry
747 call assert_equal(1, error_caught)
748 call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3))
749
Bram Moolenaar80341bc2019-05-20 20:34:51 +0200750 delfunc Foo
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100751 bwipe!
752endfunc
Bram Moolenaarc6b37db2019-04-27 18:00:34 +0200753
754" Test ":s/pat/sub/" with different ~s in sub.
755func Test_replace_with_tilde()
756 new
757 " Set the last replace string to empty
758 s/^$//
759 call append(0, ['- Bug in "vPPPP" on this text:'])
760 normal gg
761 s/u/~u~/
762 call assert_equal('- Bug in "vPPPP" on this text:', getline(1))
763 s/i/~u~/
764 call assert_equal('- Bug uuun "vPPPP" on this text:', getline(1))
765 s/o/~~~/
766 call assert_equal('- Bug uuun "vPPPP" uuuuuuuuun this text:', getline(1))
767 close!
768endfunc
769
770func Test_replace_keeppatterns()
771 new
772 a
773foobar
774
775substitute foo asdf
776
777one two
778.
779
780 normal gg
781 /^substitute
782 s/foo/bar/
783 call assert_equal('foo', @/)
784 call assert_equal('substitute bar asdf', getline('.'))
785
786 /^substitute
787 keeppatterns s/asdf/xyz/
788 call assert_equal('^substitute', @/)
789 call assert_equal('substitute bar xyz', getline('.'))
790
791 exe "normal /bar /e\<CR>"
792 call assert_equal(15, col('.'))
793 normal -
794 keeppatterns /xyz
795 call assert_equal('bar ', @/)
796 call assert_equal('substitute bar xyz', getline('.'))
797 exe "normal 0dn"
798 call assert_equal('xyz', getline('.'))
799
800 close!
801endfunc
Bram Moolenaarbb265962019-10-31 04:38:36 +0100802
803func Test_sub_beyond_end()
804 new
805 call setline(1, '#')
806 let @/ = '^#\n\zs'
807 s///e
808 call assert_equal('#', getline(1))
809 bwipe!
810endfunc
Bram Moolenaar5d98dc22020-01-29 21:57:34 +0100811
Bram Moolenaarea3db912020-02-02 15:32:13 +0100812" Test for repeating last substitution using :~ and :&r
813func Test_repeat_last_sub()
814 new
815 call setline(1, ['blue green yellow orange white'])
816 s/blue/red/
817 let @/ = 'yellow'
818 ~
819 let @/ = 'white'
820 :&r
821 let @/ = 'green'
822 s//gray
823 call assert_equal('red gray red orange red', getline(1))
824 close!
825endfunc
826
827" Test for Vi compatible substitution:
828" \/{string}/, \?{string}? and \&{string}&
829func Test_sub_vi_compatibility()
830 new
831 call setline(1, ['blue green yellow orange blue'])
832 let @/ = 'orange'
833 s\/white/
834 let @/ = 'blue'
835 s\?amber?
836 let @/ = 'white'
837 s\&green&
838 call assert_equal('amber green yellow white green', getline(1))
839 close!
Bram Moolenaar9fb7b422022-03-05 21:13:26 +0000840
841 call assert_fails('vim9cmd s\/white/', 'E1270:')
842 call assert_fails('vim9cmd s\?white?', 'E1270:')
843 call assert_fails('vim9cmd s\&white&', 'E1270:')
Bram Moolenaarea3db912020-02-02 15:32:13 +0100844endfunc
845
846" Test for substitute with the new text longer than the original text
847func Test_sub_expand_text()
848 new
849 call setline(1, 'abcabcabcabcabcabcabcabc')
850 s/b/\=repeat('B', 10)/g
851 call assert_equal(repeat('aBBBBBBBBBBc', 8), getline(1))
852 close!
853endfunc
854
Bram Moolenaar07ada5f2020-02-05 20:38:22 +0100855" Test for command failures when the last substitute pattern is not set.
856func Test_sub_with_no_last_pat()
Bram Moolenaar9f6277b2020-02-11 22:04:02 +0100857 let lines =<< trim [SCRIPT]
858 call assert_fails('~', 'E33:')
Bram Moolenaar9b7bf9e2020-07-11 22:14:59 +0200859 call assert_fails('s//abc/g', 'E35:')
860 call assert_fails('s\/bar', 'E35:')
861 call assert_fails('s\&bar&', 'E33:')
Bram Moolenaar9f6277b2020-02-11 22:04:02 +0100862 call writefile(v:errors, 'Xresult')
863 qall!
864 [SCRIPT]
865 call writefile(lines, 'Xscript')
866 if RunVim([], [], '--clean -S Xscript')
867 call assert_equal([], readfile('Xresult'))
868 endif
Bram Moolenaar07ada5f2020-02-05 20:38:22 +0100869
Bram Moolenaar9f6277b2020-02-11 22:04:02 +0100870 let lines =<< trim [SCRIPT]
871 set cpo+=/
872 call assert_fails('s/abc/%/', 'E33:')
873 call writefile(v:errors, 'Xresult')
874 qall!
875 [SCRIPT]
876 call writefile(lines, 'Xscript')
877 if RunVim([], [], '--clean -S Xscript')
878 call assert_equal([], readfile('Xresult'))
879 endif
880
881 call delete('Xscript')
882 call delete('Xresult')
Bram Moolenaar07ada5f2020-02-05 20:38:22 +0100883endfunc
884
Bram Moolenaarca68ae12020-03-30 19:32:53 +0200885func Test_substitute()
886 call assert_equal('a1a2a3a', substitute('123', '\zs', 'a', 'g'))
Bram Moolenaar004a6782020-04-11 17:09:31 +0200887 " Substitute with special keys
888 call assert_equal("a\<End>c", substitute('abc', "a.c", "a\<End>c", ''))
889endfunc
890
891func Test_substitute_expr()
892 let g:val = 'XXX'
893 call assert_equal('XXX', substitute('yyy', 'y*', '\=g:val', ''))
894 call assert_equal('XXX', substitute('yyy', 'y*', {-> g:val}, ''))
895 call assert_equal("-\u1b \uf2-", substitute("-%1b %f2-", '%\(\x\x\)',
896 \ '\=nr2char("0x" . submatch(1))', 'g'))
897 call assert_equal("-\u1b \uf2-", substitute("-%1b %f2-", '%\(\x\x\)',
898 \ {-> nr2char("0x" . submatch(1))}, 'g'))
899
900 call assert_equal('231', substitute('123', '\(.\)\(.\)\(.\)',
901 \ {-> submatch(2) . submatch(3) . submatch(1)}, ''))
902
903 func Recurse()
904 return substitute('yyy', 'y\(.\)y', {-> submatch(1)}, '')
905 endfunc
906 " recursive call works
907 call assert_equal('-y-x-', substitute('xxx', 'x\(.\)x', {-> '-' . Recurse() . '-' . submatch(1) . '-'}, ''))
908
909 call assert_fails("let s=submatch([])", 'E745:')
910 call assert_fails("let s=submatch(2, [])", 'E745:')
911endfunc
912
913func Test_invalid_submatch()
914 " This was causing invalid memory access in Vim-7.4.2232 and older
915 call assert_fails("call substitute('x', '.', {-> submatch(10)}, '')", 'E935:')
916 call assert_fails('eval submatch(-1)', 'E935:')
917 call assert_equal('', submatch(0))
918 call assert_equal('', submatch(1))
919 call assert_equal([], submatch(0, 1))
920 call assert_equal([], submatch(1, 1))
921endfunc
922
Bram Moolenaar8a0dcf42020-09-06 15:14:45 +0200923func Test_submatch_list_concatenate()
924 let pat = 'A\(.\)'
925 let Rep = {-> string([submatch(0, 1)] + [[submatch(1)]])}
926 call substitute('A1', pat, Rep, '')->assert_equal("[['A1'], ['1']]")
927endfunc
928
Bram Moolenaar004a6782020-04-11 17:09:31 +0200929func Test_substitute_expr_arg()
930 call assert_equal('123456789-123456789=', substitute('123456789',
931 \ '\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)',
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('123456-123456=789', substitute('123456789',
935 \ '\(.\)\(.\)\(.\)\(a*\)\(n*\)\(.\)\(.\)\(.\)\(x*\)',
936 \ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))
937
938 call assert_equal('123456789-123456789x=', substitute('123456789',
939 \ '\(.\)\(.\)\(.*\)',
940 \ {m -> m[0] . '-' . m[1] . m[2] . m[3] . 'x' . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))
941
942 call assert_fails("call substitute('xxx', '.', {m -> string(add(m, 'x'))}, '')", 'E742:')
943 call assert_fails("call substitute('xxx', '.', {m -> string(insert(m, 'x'))}, '')", 'E742:')
944 call assert_fails("call substitute('xxx', '.', {m -> string(extend(m, ['x']))}, '')", 'E742:')
945 call assert_fails("call substitute('xxx', '.', {m -> string(remove(m, 1))}, '')", 'E742:')
946endfunc
947
948" Test for using a function to supply the substitute string
949func Test_substitute_using_func()
950 func Xfunc()
951 return '1234'
952 endfunc
953 call assert_equal('a1234f', substitute('abcdef', 'b..e',
954 \ function("Xfunc"), ''))
955 delfunc Xfunc
956endfunc
957
958" Test for using submatch() with a multiline match
959func Test_substitute_multiline_submatch()
960 new
961 call setline(1, ['line1', 'line2', 'line3', 'line4'])
962 %s/^line1\(\_.\+\)line4$/\=submatch(1)/
963 call assert_equal(['', 'line2', 'line3', ''], getline(1, '$'))
964 close!
Bram Moolenaarca68ae12020-03-30 19:32:53 +0200965endfunc
966
Bram Moolenaardf365142021-05-03 20:01:45 +0200967func Test_substitute_skipped_range()
968 new
969 if 0
970 /1/5/2/2/\n
971 endif
972 call assert_equal([0, 1, 1, 0, 1], getcurpos())
973 bwipe!
974endfunc
975
Dominique Pellebfb2bb12021-08-14 21:11:51 +0200976" Test using the 'gdefault' option (when on, flag 'g' is default on).
977func Test_substitute_gdefault()
978 new
979
980 " First check without 'gdefault'
981 call setline(1, 'foo bar foo')
982 s/foo/FOO/
983 call assert_equal('FOO bar foo', getline(1))
984 call setline(1, 'foo bar foo')
985 s/foo/FOO/g
986 call assert_equal('FOO bar FOO', getline(1))
987 call setline(1, 'foo bar foo')
988 s/foo/FOO/gg
989 call assert_equal('FOO bar foo', getline(1))
990
991 " Then check with 'gdefault'
992 set gdefault
993 call setline(1, 'foo bar foo')
994 s/foo/FOO/
995 call assert_equal('FOO bar FOO', getline(1))
996 call setline(1, 'foo bar foo')
997 s/foo/FOO/g
998 call assert_equal('FOO bar foo', getline(1))
999 call setline(1, 'foo bar foo')
1000 s/foo/FOO/gg
1001 call assert_equal('FOO bar FOO', getline(1))
1002
1003 " Setting 'compatible' should reset 'gdefault'
1004 call assert_equal(1, &gdefault)
1005 set compatible
1006 call assert_equal(0, &gdefault)
1007 set nocompatible
1008 call assert_equal(0, &gdefault)
1009
1010 bw!
1011endfunc
1012
Bram Moolenaar37f47952022-01-29 14:21:51 +00001013" This was using "old_sub" after it was freed.
1014func Test_using_old_sub()
1015 set compatible maxfuncdepth=10
1016 new
1017 call setline(1, 'some text.')
1018 func Repl()
1019 ~
1020 s/
1021 endfunc
Bram Moolenaar44ddf192022-06-21 22:15:25 +01001022 silent! s/\%')/\=Repl()
Bram Moolenaar37f47952022-01-29 14:21:51 +00001023
1024 delfunc Repl
1025 bwipe!
1026 set nocompatible
1027endfunc
1028
Bram Moolenaare2bd8602022-05-18 13:11:57 +01001029" This was switching windows in between computing the length and using it.
1030func Test_sub_change_window()
1031 silent! lfile
1032 sil! norm o0000000000000000000000000000000000000000000000000000
1033 func Repl()
1034 lopen
1035 endfunc
1036 silent! s/\%')/\=Repl()
1037 bwipe!
1038 bwipe!
1039 delfunc Repl
1040endfunc
1041
Bram Moolenaar338f1fc2022-05-26 15:56:23 +01001042" This was undoign a change in between computing the length and using it.
1043func Do_Test_sub_undo_change()
1044 new
1045 norm o0000000000000000000000000000000000000000000000000000
1046 silent! s/\%')/\=Repl()
1047 bwipe!
1048endfunc
1049
1050func Test_sub_undo_change()
1051 func Repl()
1052 silent! norm g-
1053 endfunc
1054 call Do_Test_sub_undo_change()
1055
1056 func! Repl()
1057 silent earlier
1058 endfunc
1059 call Do_Test_sub_undo_change()
1060
1061 delfunc Repl
1062endfunc
1063
Bram Moolenaar71223e22022-05-30 15:23:09 +01001064" This was opening a command line window from the expression
1065func Test_sub_open_cmdline_win()
1066 " the error only happens in a very specific setup, run a new Vim instance to
1067 " get a clean starting point.
1068 let lines =<< trim [SCRIPT]
Bram Moolenaarbe990422022-05-30 16:01:42 +01001069 set vb t_vb=
Bram Moolenaar71223e22022-05-30 15:23:09 +01001070 norm o0000000000000000000000000000000000000000000000000000
1071 func Replace()
1072 norm q/
1073 endfunc
1074 s/\%')/\=Replace()
1075 redir >Xresult
1076 messages
1077 redir END
1078 qall!
1079 [SCRIPT]
1080 call writefile(lines, 'Xscript')
1081 if RunVim([], [], '-u NONE -S Xscript')
Bram Moolenaarbe990422022-05-30 16:01:42 +01001082 call assert_match('E565: Not allowed to change text or change window',
1083 \ readfile('Xresult')->join('XX'))
Bram Moolenaar71223e22022-05-30 15:23:09 +01001084 endif
1085
1086 call delete('Xscript')
1087 call delete('Xresult')
1088endfunc
1089
Bram Moolenaard6211a52022-06-18 19:48:14 +01001090" This was editing a script file from the expression
1091func Test_sub_edit_scriptfile()
1092 new
1093 norm o0000000000000000000000000000000000000000000000000000
1094 func EditScript()
Bram Moolenaarb18b4962022-09-02 21:55:50 +01001095 silent! scr! Xsedfile
Bram Moolenaard6211a52022-06-18 19:48:14 +01001096 endfunc
1097 s/\%')/\=EditScript()
1098
1099 delfunc EditScript
1100 bwipe!
1101endfunc
1102
Yegappan Lakshmanan5e877ba2022-03-25 21:19:26 +00001103" Test for the 2-letter and 3-letter :substitute commands
1104func Test_substitute_short_cmd()
1105 new
1106 call setline(1, ['one', 'one one one'])
1107 s/one/two
1108 call cursor(2, 1)
1109
1110 " :sc
1111 call feedkeys(":sc\<CR>y", 'xt')
1112 call assert_equal('two one one', getline(2))
1113
1114 " :scg
1115 call setline(2, 'one one one')
1116 call feedkeys(":scg\<CR>nyq", 'xt')
1117 call assert_equal('one two one', getline(2))
1118
1119 " :sci
1120 call setline(2, 'ONE One onE')
1121 call feedkeys(":sci\<CR>y", 'xt')
1122 call assert_equal('two One onE', getline(2))
1123
1124 " :scI
1125 set ignorecase
1126 call setline(2, 'ONE One one')
1127 call feedkeys(":scI\<CR>y", 'xt')
1128 call assert_equal('ONE One two', getline(2))
1129 set ignorecase&
1130
1131 " :scn
1132 call setline(2, 'one one one')
1133 let t = execute('scn')->split("\n")
1134 call assert_equal(['1 match on 1 line'], t)
1135 call assert_equal('one one one', getline(2))
1136
1137 " :scp
1138 call setline(2, "\tone one one")
1139 redir => output
1140 call feedkeys(":scp\<CR>y", 'xt')
1141 redir END
1142 call assert_equal(' two one one', output->split("\n")[-1])
1143 call assert_equal("\ttwo one one", getline(2))
1144
1145 " :scl
1146 call setline(2, "\tone one one")
1147 redir => output
1148 call feedkeys(":scl\<CR>y", 'xt')
1149 redir END
1150 call assert_equal("^Itwo one one$", output->split("\n")[-1])
1151 call assert_equal("\ttwo one one", getline(2))
1152
1153 " :sgc
1154 call setline(2, 'one one one one one')
1155 call feedkeys(":sgc\<CR>nyyq", 'xt')
1156 call assert_equal('one two two one one', getline(2))
1157
1158 " :sg
1159 call setline(2, 'one one one')
1160 sg
1161 call assert_equal('two two two', getline(2))
1162
1163 " :sgi
1164 call setline(2, 'ONE One onE')
1165 sgi
1166 call assert_equal('two two two', getline(2))
1167
1168 " :sgI
1169 set ignorecase
1170 call setline(2, 'ONE One one')
1171 sgI
1172 call assert_equal('ONE One two', getline(2))
1173 set ignorecase&
1174
1175 " :sgn
1176 call setline(2, 'one one one')
1177 let t = execute('sgn')->split("\n")
1178 call assert_equal(['3 matches on 1 line'], t)
1179 call assert_equal('one one one', getline(2))
1180
1181 " :sgp
1182 call setline(2, "\tone one one")
1183 redir => output
1184 sgp
1185 redir END
1186 call assert_equal(' two two two', output->split("\n")[-1])
1187 call assert_equal("\ttwo two two", getline(2))
1188
1189 " :sgl
1190 call setline(2, "\tone one one")
1191 redir => output
1192 sgl
1193 redir END
1194 call assert_equal("^Itwo two two$", output->split("\n")[-1])
1195 call assert_equal("\ttwo two two", getline(2))
1196
1197 " :sgr
1198 call setline(2, "one one one")
1199 call cursor(2, 1)
1200 s/abc/xyz/e
1201 let @/ = 'one'
1202 sgr
1203 call assert_equal('xyz xyz xyz', getline(2))
1204
1205 " :sic
1206 call cursor(1, 1)
1207 s/one/two/e
1208 call setline(2, "ONE One one")
1209 call cursor(2, 1)
1210 call feedkeys(":sic\<CR>y", 'xt')
1211 call assert_equal('two One one', getline(2))
1212
1213 " :si
1214 call setline(2, "ONE One one")
1215 si
1216 call assert_equal('two One one', getline(2))
1217
1218 " :siI
1219 call setline(2, "ONE One one")
1220 siI
1221 call assert_equal('ONE One two', getline(2))
1222
1223 " :sin
1224 call setline(2, 'ONE One onE')
1225 let t = execute('sin')->split("\n")
1226 call assert_equal(['1 match on 1 line'], t)
1227 call assert_equal('ONE One onE', getline(2))
1228
1229 " :sip
1230 call setline(2, "\tONE One onE")
1231 redir => output
1232 sip
1233 redir END
1234 call assert_equal(' two One onE', output->split("\n")[-1])
1235 call assert_equal("\ttwo One onE", getline(2))
1236
1237 " :sir
1238 call setline(2, "ONE One onE")
1239 call cursor(2, 1)
1240 s/abc/xyz/e
1241 let @/ = 'one'
1242 sir
1243 call assert_equal('xyz One onE', getline(2))
1244
1245 " :sIc
1246 call cursor(1, 1)
1247 s/one/two/e
1248 call setline(2, "ONE One one")
1249 call cursor(2, 1)
1250 call feedkeys(":sIc\<CR>y", 'xt')
1251 call assert_equal('ONE One two', getline(2))
1252
1253 " :sIg
1254 call setline(2, "ONE one onE one")
1255 sIg
1256 call assert_equal('ONE two onE two', getline(2))
1257
1258 " :sIi
1259 call setline(2, "ONE One one")
1260 sIi
1261 call assert_equal('two One one', getline(2))
1262
1263 " :sI
1264 call setline(2, "ONE One one")
1265 sI
1266 call assert_equal('ONE One two', getline(2))
1267
1268 " :sIn
1269 call setline(2, 'ONE One one')
1270 let t = execute('sIn')->split("\n")
1271 call assert_equal(['1 match on 1 line'], t)
1272 call assert_equal('ONE One one', getline(2))
1273
1274 " :sIp
1275 call setline(2, "\tONE One one")
1276 redir => output
1277 sIp
1278 redir END
1279 call assert_equal(' ONE One two', output->split("\n")[-1])
1280 call assert_equal("\tONE One two", getline(2))
1281
1282 " :sIl
1283 call setline(2, "\tONE onE one")
1284 redir => output
1285 sIl
1286 redir END
1287 call assert_equal("^IONE onE two$", output->split("\n")[-1])
1288 call assert_equal("\tONE onE two", getline(2))
1289
1290 " :sIr
1291 call setline(2, "ONE one onE")
1292 call cursor(2, 1)
1293 s/abc/xyz/e
1294 let @/ = 'one'
1295 sIr
1296 call assert_equal('ONE xyz onE', getline(2))
1297
1298 " :src
1299 call setline(2, "ONE one one")
1300 call cursor(2, 1)
1301 s/abc/xyz/e
1302 let @/ = 'one'
1303 call feedkeys(":src\<CR>y", 'xt')
1304 call assert_equal('ONE xyz one', getline(2))
1305
1306 " :srg
1307 call setline(2, "one one one")
1308 call cursor(2, 1)
1309 s/abc/xyz/e
1310 let @/ = 'one'
1311 srg
1312 call assert_equal('xyz xyz xyz', getline(2))
1313
1314 " :sri
1315 call setline(2, "ONE one onE")
1316 call cursor(2, 1)
1317 s/abc/xyz/e
1318 let @/ = 'one'
1319 sri
1320 call assert_equal('xyz one onE', getline(2))
1321
1322 " :srI
1323 call setline(2, "ONE one onE")
1324 call cursor(2, 1)
1325 s/abc/xyz/e
1326 let @/ = 'one'
1327 srI
1328 call assert_equal('ONE xyz onE', getline(2))
1329
1330 " :srn
1331 call setline(2, "ONE one onE")
1332 call cursor(2, 1)
1333 s/abc/xyz/e
1334 let @/ = 'one'
1335 let t = execute('srn')->split("\n")
1336 call assert_equal(['1 match on 1 line'], t)
1337 call assert_equal('ONE one onE', getline(2))
1338
1339 " :srp
1340 call setline(2, "\tONE one onE")
1341 call cursor(2, 1)
1342 s/abc/xyz/e
1343 let @/ = 'one'
1344 redir => output
1345 srp
1346 redir END
1347 call assert_equal(' ONE xyz onE', output->split("\n")[-1])
1348 call assert_equal("\tONE xyz onE", getline(2))
1349
1350 " :srl
1351 call setline(2, "\tONE one onE")
1352 call cursor(2, 1)
1353 s/abc/xyz/e
1354 let @/ = 'one'
1355 redir => output
1356 srl
1357 redir END
1358 call assert_equal("^IONE xyz onE$", output->split("\n")[-1])
1359 call assert_equal("\tONE xyz onE", getline(2))
1360
1361 " :sr
1362 call setline(2, "ONE one onE")
1363 call cursor(2, 1)
1364 s/abc/xyz/e
1365 let @/ = 'one'
1366 sr
1367 call assert_equal('ONE xyz onE', getline(2))
1368
1369 " :sce
1370 s/abc/xyz/e
1371 call assert_fails("sc", 'E486:')
1372 sce
1373 " :sge
1374 call assert_fails("sg", 'E486:')
1375 sge
1376 " :sie
1377 call assert_fails("si", 'E486:')
1378 sie
1379 " :sIe
1380 call assert_fails("sI", 'E486:')
1381 sIe
1382
1383 bw!
1384endfunc
Bram Moolenaar37f47952022-01-29 14:21:51 +00001385
Bram Moolenaar44ddf192022-06-21 22:15:25 +01001386" This should be done last to reveal a memory leak when vim_regsub_both() is
1387" called to evaluate an expression but it is not used in a second call.
1388func Test_z_substitute_expr_leak()
1389 func SubExpr()
1390 ~n
1391 endfunc
1392 silent! s/\%')/\=SubExpr()
1393 delfunc SubExpr
1394endfunc
1395
Bram Moolenaar5d98dc22020-01-29 21:57:34 +01001396" vim: shiftwidth=2 sts=2 expandtab