blob: f3fd7ab1ce7779019df30cd93ac73dea0618c933 [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 Moolenaar9f6277b2020-02-11 22:04:02 +01005
Bram Moolenaar1e115362019-01-09 23:01:02 +01006func Test_multiline_subst()
Bram Moolenaarcd055da2016-09-02 19:50:48 +02007 enew!
8 call append(0, ["1 aa",
9 \ "bb",
10 \ "cc",
11 \ "2 dd",
12 \ "ee",
13 \ "3 ef",
14 \ "gh",
15 \ "4 ij",
16 \ "5 a8",
17 \ "8b c9",
18 \ "9d",
19 \ "6 e7",
20 \ "77f",
21 \ "xxxxx"])
22
23 1
24 " test if replacing a line break works with a back reference
25 /^1/,/^2/s/\n\(.\)/ \1/
26 " test if inserting a line break works with a back reference
27 /^3/,/^4/s/\(.\)$/\r\1/
28 " test if replacing a line break with another line break works
29 /^5/,/^6/s/\(\_d\{3}\)/x\1x/
30 call assert_equal('1 aa bb cc 2 dd ee', getline(1))
31 call assert_equal('3 e', getline(2))
32 call assert_equal('f', getline(3))
33 call assert_equal('g', getline(4))
34 call assert_equal('h', getline(5))
35 call assert_equal('4 i', getline(6))
36 call assert_equal('j', getline(7))
37 call assert_equal('5 ax8', getline(8))
38 call assert_equal('8xb cx9', getline(9))
39 call assert_equal('9xd', getline(10))
40 call assert_equal('6 ex7', getline(11))
41 call assert_equal('7x7f', getline(12))
42 call assert_equal('xxxxx', getline(13))
43 enew!
Bram Moolenaar1e115362019-01-09 23:01:02 +010044endfunc
Bram Moolenaar8c50d502017-02-17 18:28:24 +010045
Bram Moolenaar1e115362019-01-09 23:01:02 +010046func Test_substitute_variants()
Bram Moolenaar8c50d502017-02-17 18:28:24 +010047 " Validate that all the 2-/3-letter variants which embed the flags into the
48 " command name actually work.
49 enew!
50 let ln = 'Testing string'
51 let variants = [
52 \ { 'cmd': ':s/Test/test/c', 'exp': 'testing string', 'prompt': 'y' },
53 \ { 'cmd': ':s/foo/bar/ce', 'exp': ln },
54 \ { 'cmd': ':s/t/r/cg', 'exp': 'Tesring srring', 'prompt': 'a' },
55 \ { 'cmd': ':s/t/r/ci', 'exp': 'resting string', 'prompt': 'y' },
56 \ { 'cmd': ':s/t/r/cI', 'exp': 'Tesring string', 'prompt': 'y' },
Bram Moolenaarea3db912020-02-02 15:32:13 +010057 \ { 'cmd': ':s/t/r/c', 'exp': 'Testing string', 'prompt': 'n' },
Bram Moolenaar8c50d502017-02-17 18:28:24 +010058 \ { 'cmd': ':s/t/r/cn', 'exp': ln },
59 \ { 'cmd': ':s/t/r/cp', 'exp': 'Tesring string', 'prompt': 'y' },
60 \ { 'cmd': ':s/t/r/cl', 'exp': 'Tesring string', 'prompt': 'y' },
61 \ { 'cmd': ':s/t/r/gc', 'exp': 'Tesring srring', 'prompt': 'a' },
Bram Moolenaarea3db912020-02-02 15:32:13 +010062 \ { 'cmd': ':s/i/I/gc', 'exp': 'TestIng string', 'prompt': 'l' },
Bram Moolenaar8c50d502017-02-17 18:28:24 +010063 \ { 'cmd': ':s/foo/bar/ge', 'exp': ln },
64 \ { 'cmd': ':s/t/r/g', 'exp': 'Tesring srring' },
65 \ { 'cmd': ':s/t/r/gi', 'exp': 'resring srring' },
66 \ { 'cmd': ':s/t/r/gI', 'exp': 'Tesring srring' },
67 \ { 'cmd': ':s/t/r/gn', 'exp': ln },
68 \ { 'cmd': ':s/t/r/gp', 'exp': 'Tesring srring' },
69 \ { 'cmd': ':s/t/r/gl', 'exp': 'Tesring srring' },
70 \ { 'cmd': ':s//r/gr', 'exp': 'Testr strr' },
71 \ { 'cmd': ':s/t/r/ic', 'exp': 'resting string', 'prompt': 'y' },
72 \ { 'cmd': ':s/foo/bar/ie', 'exp': ln },
73 \ { 'cmd': ':s/t/r/i', 'exp': 'resting string' },
74 \ { 'cmd': ':s/t/r/iI', 'exp': 'Tesring string' },
75 \ { 'cmd': ':s/t/r/in', 'exp': ln },
76 \ { 'cmd': ':s/t/r/ip', 'exp': 'resting string' },
77 \ { 'cmd': ':s//r/ir', 'exp': 'Testr string' },
78 \ { 'cmd': ':s/t/r/Ic', 'exp': 'Tesring string', 'prompt': 'y' },
79 \ { 'cmd': ':s/foo/bar/Ie', 'exp': ln },
80 \ { 'cmd': ':s/t/r/Ig', 'exp': 'Tesring srring' },
81 \ { 'cmd': ':s/t/r/Ii', 'exp': 'resting string' },
82 \ { 'cmd': ':s/t/r/I', 'exp': 'Tesring string' },
83 \ { 'cmd': ':s/t/r/Ip', 'exp': 'Tesring string' },
84 \ { 'cmd': ':s/t/r/Il', 'exp': 'Tesring string' },
85 \ { 'cmd': ':s//r/Ir', 'exp': 'Testr string' },
86 \ { 'cmd': ':s//r/rc', 'exp': 'Testr string', 'prompt': 'y' },
87 \ { 'cmd': ':s//r/rg', 'exp': 'Testr strr' },
88 \ { 'cmd': ':s//r/ri', 'exp': 'Testr string' },
89 \ { 'cmd': ':s//r/rI', 'exp': 'Testr string' },
90 \ { 'cmd': ':s//r/rn', 'exp': 'Testing string' },
91 \ { 'cmd': ':s//r/rp', 'exp': 'Testr string' },
92 \ { 'cmd': ':s//r/rl', 'exp': 'Testr string' },
93 \ { 'cmd': ':s//r/r', 'exp': 'Testr string' },
Bram Moolenaarea3db912020-02-02 15:32:13 +010094 \ { 'cmd': ':s/i/I/gc', 'exp': 'Testing string', 'prompt': 'q' },
Bram Moolenaar8c50d502017-02-17 18:28:24 +010095 \]
96
97 for var in variants
98 for run in [1, 2]
99 let cmd = var.cmd
100 if run == 2 && cmd =~ "/.*/.*/."
101 " Change :s/from/to/{flags} to :s{flags}
102 let cmd = substitute(cmd, '/.*/', '', '')
103 endif
104 call setline(1, [ln])
105 let msg = printf('using "%s"', cmd)
106 let @/='ing'
107 let v:errmsg = ''
108 call feedkeys(cmd . "\<CR>" . get(var, 'prompt', ''), 'ntx')
109 " No error should exist (matters for testing e flag)
110 call assert_equal('', v:errmsg, msg)
111 call assert_equal(var.exp, getline('.'), msg)
112 endfor
113 endfor
Bram Moolenaar1e115362019-01-09 23:01:02 +0100114endfunc
Bram Moolenaarba748c82017-02-26 14:00:07 +0100115
Bram Moolenaar94747162019-02-10 21:55:26 +0100116" Test the l, p, # flags.
117func Test_substitute_flags_lp()
118 new
119 call setline(1, "abc\tdef\<C-h>ghi")
120
121 let a = execute('s/a/a/p')
122 call assert_equal("\nabc def^Hghi", a)
123
124 let a = execute('s/a/a/l')
125 call assert_equal("\nabc^Idef^Hghi$", a)
126
127 let a = execute('s/a/a/#')
128 call assert_equal("\n 1 abc def^Hghi", a)
129
130 let a = execute('s/a/a/p#')
131 call assert_equal("\n 1 abc def^Hghi", a)
132
133 let a = execute('s/a/a/l#')
134 call assert_equal("\n 1 abc^Idef^Hghi$", a)
135
136 let a = execute('s/a/a/')
137 call assert_equal("", a)
138
139 bwipe!
140endfunc
141
Bram Moolenaarba748c82017-02-26 14:00:07 +0100142func Test_substitute_repeat()
143 " This caused an invalid memory access.
144 split Xfile
145 s/^/x
146 call feedkeys("Qsc\<CR>y", 'tx')
147 bwipe!
148endfunc
Bram Moolenaar1a333bc2017-08-30 20:21:58 +0200149
Bram Moolenaard77aa4d2019-02-10 22:50:14 +0100150" Test %s/\n// which is implemented as a special case to use a
151" more efficient join rather than doing a regular substitution.
152func Test_substitute_join()
153 new
154
155 call setline(1, ["foo\tbar", "bar\<C-H>foo"])
156 let a = execute('%s/\n//')
157 call assert_equal("", a)
158 call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
159 call assert_equal('\n', histget("search", -1))
160
161 call setline(1, ["foo\tbar", "bar\<C-H>foo"])
162 let a = execute('%s/\n//g')
163 call assert_equal("", a)
164 call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
165 call assert_equal('\n', histget("search", -1))
166
167 call setline(1, ["foo\tbar", "bar\<C-H>foo"])
168 let a = execute('%s/\n//p')
169 call assert_equal("\nfoo barbar^Hfoo", a)
170 call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
171 call assert_equal('\n', histget("search", -1))
172
173 call setline(1, ["foo\tbar", "bar\<C-H>foo"])
174 let a = execute('%s/\n//l')
175 call assert_equal("\nfoo^Ibarbar^Hfoo$", a)
176 call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
177 call assert_equal('\n', histget("search", -1))
178
179 call setline(1, ["foo\tbar", "bar\<C-H>foo"])
180 let a = execute('%s/\n//#')
181 call assert_equal("\n 1 foo barbar^Hfoo", a)
182 call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$'))
183 call assert_equal('\n', histget("search", -1))
184
Bram Moolenaarea3db912020-02-02 15:32:13 +0100185 call setline(1, ['foo', 'bar', 'baz', 'qux'])
186 call execute('1,2s/\n//')
187 call assert_equal(['foobarbaz', 'qux'], getline(1, '$'))
188
Bram Moolenaard77aa4d2019-02-10 22:50:14 +0100189 bwipe!
190endfunc
191
192func Test_substitute_count()
193 new
194 call setline(1, ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo'])
195 2
196
197 s/foo/bar/3
198 call assert_equal(['foo foo', 'bar foo', 'bar foo', 'bar foo', 'foo foo'],
199 \ getline(1, '$'))
200
201 call assert_fails('s/foo/bar/0', 'E939:')
202
Bram Moolenaarea3db912020-02-02 15:32:13 +0100203 call setline(1, ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo'])
204 2,4s/foo/bar/ 10
205 call assert_equal(['foo foo', 'foo foo', 'foo foo', 'bar foo', 'bar foo'],
206 \ getline(1, '$'))
207
Bram Moolenaard77aa4d2019-02-10 22:50:14 +0100208 bwipe!
209endfunc
210
211" Test substitute 'n' flag (report number of matches, do not substitute).
212func Test_substitute_flag_n()
213 new
214 let lines = ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo']
215 call setline(1, lines)
216
217 call assert_equal("\n3 matches on 3 lines", execute('2,4s/foo/bar/n'))
218 call assert_equal("\n6 matches on 3 lines", execute('2,4s/foo/bar/gn'))
219
220 " c flag (confirm) should be ignored when using n flag.
221 call assert_equal("\n3 matches on 3 lines", execute('2,4s/foo/bar/nc'))
222
223 " No substitution should have been done.
224 call assert_equal(lines, getline(1, '$'))
225
Bram Moolenaarea3db912020-02-02 15:32:13 +0100226 %delete _
227 call setline(1, ['A', 'Bar', 'Baz'])
228 call assert_equal("\n1 match on 1 line", execute('s/\nB\@=//gn'))
229
Bram Moolenaard77aa4d2019-02-10 22:50:14 +0100230 bwipe!
231endfunc
232
233func Test_substitute_errors()
234 new
235 call setline(1, 'foobar')
236
237 call assert_fails('s/FOO/bar/', 'E486:')
238 call assert_fails('s/foo/bar/@', 'E488:')
Bram Moolenaar9b7bf9e2020-07-11 22:14:59 +0200239 call assert_fails('s/\(/bar/', 'E54:')
Bram Moolenaar5d98dc22020-01-29 21:57:34 +0100240 call assert_fails('s afooabara', 'E146:')
241 call assert_fails('s\\a', 'E10:')
Bram Moolenaard77aa4d2019-02-10 22:50:14 +0100242
243 setl nomodifiable
244 call assert_fails('s/foo/bar/', 'E21:')
245
Bram Moolenaar0e05de42020-03-25 22:23:46 +0100246 call assert_fails("let s=substitute([], 'a', 'A', 'g')", 'E730:')
247 call assert_fails("let s=substitute('abcda', [], 'A', 'g')", 'E730:')
248 call assert_fails("let s=substitute('abcda', 'a', [], 'g')", 'E730:')
249 call assert_fails("let s=substitute('abcda', 'a', 'A', [])", 'E730:')
Bram Moolenaar531be472020-09-23 22:38:05 +0200250 call assert_fails("let s=substitute('abc', '\\%(', 'A', 'g')", 'E53:')
Bram Moolenaar0e05de42020-03-25 22:23:46 +0100251
Bram Moolenaard77aa4d2019-02-10 22:50:14 +0100252 bwipe!
253endfunc
254
Bram Moolenaar1a333bc2017-08-30 20:21:58 +0200255" Test for *sub-replace-special* and *sub-replace-expression* on substitute().
256func Test_sub_replace_1()
257 " Run the tests with 'magic' on
258 set magic
259 set cpo&
260 call assert_equal('AA', substitute('A', 'A', '&&', ''))
261 call assert_equal('&', substitute('B', 'B', '\&', ''))
262 call assert_equal('C123456789987654321', substitute('C123456789', 'C\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)', '\0\9\8\7\6\5\4\3\2\1', ''))
263 call assert_equal('d', substitute('D', 'D', 'd', ''))
264 call assert_equal('~', substitute('E', 'E', '~', ''))
265 call assert_equal('~', substitute('F', 'F', '\~', ''))
266 call assert_equal('Gg', substitute('G', 'G', '\ugg', ''))
267 call assert_equal('Hh', substitute('H', 'H', '\Uh\Eh', ''))
268 call assert_equal('iI', substitute('I', 'I', '\lII', ''))
269 call assert_equal('jJ', substitute('J', 'J', '\LJ\EJ', ''))
270 call assert_equal('Kk', substitute('K', 'K', '\Uk\ek', ''))
271 call assert_equal("l\<C-V>\<C-M>l",
272 \ substitute('lLl', 'L', "\<C-V>\<C-M>", ''))
273 call assert_equal("m\<C-M>m", substitute('mMm', 'M', '\r', ''))
274 call assert_equal("n\<C-V>\<C-M>n",
275 \ substitute('nNn', 'N', "\\\<C-V>\<C-M>", ''))
276 call assert_equal("o\no", substitute('oOo', 'O', '\n', ''))
277 call assert_equal("p\<C-H>p", substitute('pPp', 'P', '\b', ''))
278 call assert_equal("q\tq", substitute('qQq', 'Q', '\t', ''))
279 call assert_equal('r\r', substitute('rRr', 'R', '\\', ''))
280 call assert_equal('scs', substitute('sSs', 'S', '\c', ''))
281 call assert_equal("u\nu", substitute('uUu', 'U', "\n", ''))
282 call assert_equal("v\<C-H>v", substitute('vVv', 'V', "\b", ''))
283 call assert_equal("w\\w", substitute('wWw', 'W', "\\", ''))
284 call assert_equal("x\<C-M>x", substitute('xXx', 'X', "\r", ''))
285 call assert_equal("YyyY", substitute('Y', 'Y', '\L\uyYy\l\EY', ''))
286 call assert_equal("zZZz", substitute('Z', 'Z', '\U\lZzZ\u\Ez', ''))
Bram Moolenaar004a6782020-04-11 17:09:31 +0200287 " \v or \V after $
288 call assert_equal('abxx', substitute('abcd', 'xy$\v|cd$', 'xx', ''))
289 call assert_equal('abxx', substitute('abcd', 'xy$\V\|cd\$', 'xx', ''))
Bram Moolenaar1a333bc2017-08-30 20:21:58 +0200290endfunc
291
292func Test_sub_replace_2()
293 " Run the tests with 'magic' off
294 set nomagic
295 set cpo&
296 call assert_equal('AA', substitute('A', 'A', '&&', ''))
297 call assert_equal('&', substitute('B', 'B', '\&', ''))
298 call assert_equal('C123456789987654321', substitute('C123456789', 'C\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)', '\0\9\8\7\6\5\4\3\2\1', ''))
299 call assert_equal('d', substitute('D', 'D', 'd', ''))
300 call assert_equal('~', substitute('E', 'E', '~', ''))
301 call assert_equal('~', substitute('F', 'F', '\~', ''))
302 call assert_equal('Gg', substitute('G', 'G', '\ugg', ''))
303 call assert_equal('Hh', substitute('H', 'H', '\Uh\Eh', ''))
304 call assert_equal('iI', substitute('I', 'I', '\lII', ''))
305 call assert_equal('jJ', substitute('J', 'J', '\LJ\EJ', ''))
306 call assert_equal('Kk', substitute('K', 'K', '\Uk\ek', ''))
307 call assert_equal("l\<C-V>\<C-M>l",
308 \ substitute('lLl', 'L', "\<C-V>\<C-M>", ''))
309 call assert_equal("m\<C-M>m", substitute('mMm', 'M', '\r', ''))
310 call assert_equal("n\<C-V>\<C-M>n",
311 \ substitute('nNn', 'N', "\\\<C-V>\<C-M>", ''))
312 call assert_equal("o\no", substitute('oOo', 'O', '\n', ''))
313 call assert_equal("p\<C-H>p", substitute('pPp', 'P', '\b', ''))
314 call assert_equal("q\tq", substitute('qQq', 'Q', '\t', ''))
315 call assert_equal('r\r', substitute('rRr', 'R', '\\', ''))
316 call assert_equal('scs', substitute('sSs', 'S', '\c', ''))
317 call assert_equal("t\<C-M>t", substitute('tTt', 'T', "\r", ''))
318 call assert_equal("u\nu", substitute('uUu', 'U', "\n", ''))
319 call assert_equal("v\<C-H>v", substitute('vVv', 'V', "\b", ''))
320 call assert_equal('w\w', substitute('wWw', 'W', "\\", ''))
321 call assert_equal('XxxX', substitute('X', 'X', '\L\uxXx\l\EX', ''))
322 call assert_equal('yYYy', substitute('Y', 'Y', '\U\lYyY\u\Ey', ''))
323endfunc
324
325func Test_sub_replace_3()
326 set magic&
327 set cpo&
328 call assert_equal('a\a', substitute('aAa', 'A', '\="\\"', ''))
329 call assert_equal('b\\b', substitute('bBb', 'B', '\="\\\\"', ''))
330 call assert_equal("c\rc", substitute('cCc', 'C', "\\=\"\r\"", ''))
331 call assert_equal("d\\\rd", substitute('dDd', 'D', "\\=\"\\\\\r\"", ''))
332 call assert_equal("e\\\\\re", substitute('eEe', 'E', "\\=\"\\\\\\\\\r\"", ''))
333 call assert_equal('f\rf', substitute('fFf', 'F', '\="\\r"', ''))
334 call assert_equal('j\nj', substitute('jJj', 'J', '\="\\n"', ''))
335 call assert_equal("k\<C-M>k", substitute('kKk', 'K', '\="\r"', ''))
336 call assert_equal("l\nl", substitute('lLl', 'L', '\="\n"', ''))
337endfunc
338
339" Test for submatch() on substitute().
340func Test_sub_replace_4()
341 set magic&
342 set cpo&
343 call assert_equal('a\a', substitute('aAa', 'A',
344 \ '\=substitute(submatch(0), ".", "\\", "")', ''))
345 call assert_equal('b\b', substitute('bBb', 'B',
346 \ '\=substitute(submatch(0), ".", "\\\\", "")', ''))
347 call assert_equal("c\<C-V>\<C-M>c", substitute('cCc', 'C', '\=substitute(submatch(0), ".", "\<C-V>\<C-M>", "")', ''))
348 call assert_equal("d\<C-V>\<C-M>d", substitute('dDd', 'D', '\=substitute(submatch(0), ".", "\\\<C-V>\<C-M>", "")', ''))
349 call assert_equal("e\\\<C-V>\<C-M>e", substitute('eEe', 'E', '\=substitute(submatch(0), ".", "\\\\\<C-V>\<C-M>", "")', ''))
350 call assert_equal("f\<C-M>f", substitute('fFf', 'F', '\=substitute(submatch(0), ".", "\\r", "")', ''))
351 call assert_equal("j\nj", substitute('jJj', 'J', '\=substitute(submatch(0), ".", "\\n", "")', ''))
352 call assert_equal("k\rk", substitute('kKk', 'K', '\=substitute(submatch(0), ".", "\r", "")', ''))
353 call assert_equal("l\nl", substitute('lLl', 'L', '\=substitute(submatch(0), ".", "\n", "")', ''))
354endfunc
355
356func Test_sub_replace_5()
357 set magic&
358 set cpo&
359 call assert_equal('A123456789987654321', substitute('A123456789',
360 \ 'A\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)',
361 \ '\=submatch(0) . submatch(9) . submatch(8) . ' .
362 \ 'submatch(7) . submatch(6) . submatch(5) . ' .
363 \ 'submatch(4) . submatch(3) . submatch(2) . submatch(1)',
364 \ ''))
365 call assert_equal("[['A123456789'], ['9'], ['8'], ['7'], ['6'], " .
366 \ "['5'], ['4'], ['3'], ['2'], ['1']]",
367 \ substitute('A123456789',
368 \ 'A\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)',
369 \ '\=string([submatch(0, 1), submatch(9, 1), ' .
Bram Moolenaarf6ed61e2019-09-07 19:05:09 +0200370 \ 'submatch(8, 1), 7->submatch(1), submatch(6, 1), ' .
Bram Moolenaar1a333bc2017-08-30 20:21:58 +0200371 \ 'submatch(5, 1), submatch(4, 1), submatch(3, 1), ' .
372 \ 'submatch(2, 1), submatch(1, 1)])',
373 \ ''))
374endfunc
375
376func Test_sub_replace_6()
377 set magic&
378 set cpo+=/
379 call assert_equal('a', substitute('A', 'A', 'a', ''))
380 call assert_equal('%', substitute('B', 'B', '%', ''))
381 set cpo-=/
382 call assert_equal('c', substitute('C', 'C', 'c', ''))
383 call assert_equal('%', substitute('D', 'D', '%', ''))
384endfunc
385
386func Test_sub_replace_7()
387 set magic&
388 set cpo&
389 call assert_equal('AA', substitute('AA', 'A.', '\=submatch(0)', ''))
390 call assert_equal("B\nB", substitute("B\nB", 'B.', '\=submatch(0)', ''))
391 call assert_equal("['B\n']B", substitute("B\nB", 'B.', '\=string(submatch(0, 1))', ''))
392 call assert_equal('-abab', substitute('-bb', '\zeb', 'a', 'g'))
393 call assert_equal('c-cbcbc', substitute('-bb', '\ze', 'c', 'g'))
394endfunc
395
396" Test for *:s%* on :substitute.
397func Test_sub_replace_8()
398 new
399 set magic&
400 set cpo&
401 $put =',,X'
402 s/\(^\|,\)\ze\(,\|X\)/\1N/g
403 call assert_equal('N,,NX', getline("$"))
404 $put =',,Y'
405 let cmd = ':s/\(^\|,\)\ze\(,\|Y\)/\1N/gc'
406 call feedkeys(cmd . "\<CR>a", "xt")
407 call assert_equal('N,,NY', getline("$"))
408 :$put =',,Z'
409 let cmd = ':s/\(^\|,\)\ze\(,\|Z\)/\1N/gc'
410 call feedkeys(cmd . "\<CR>yy", "xt")
411 call assert_equal('N,,NZ', getline("$"))
412 enew! | close
413endfunc
414
415func Test_sub_replace_9()
416 new
417 set magic&
418 set cpo&
419 $put ='xxx'
420 call feedkeys(":s/x/X/gc\<CR>yyq", "xt")
421 call assert_equal('XXx', getline("$"))
422 enew! | close
423endfunc
424
425func Test_sub_replace_10()
426 set magic&
427 set cpo&
428 call assert_equal('a1a2a3a', substitute('123', '\zs', 'a', 'g'))
429 call assert_equal('aaa', substitute('123', '\zs.', 'a', 'g'))
430 call assert_equal('1a2a3a', substitute('123', '.\zs', 'a', 'g'))
431 call assert_equal('a1a2a3a', substitute('123', '\ze', 'a', 'g'))
432 call assert_equal('a1a2a3', substitute('123', '\ze.', 'a', 'g'))
433 call assert_equal('aaa', substitute('123', '.\ze', 'a', 'g'))
434 call assert_equal('aa2a3a', substitute('123', '1\|\ze', 'a', 'g'))
435 call assert_equal('1aaa', substitute('123', '1\zs\|[23]', 'a', 'g'))
436endfunc
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200437
Bram Moolenaarb0745b22019-11-09 22:28:11 +0100438func SubReplacer(text, submatches)
439 return a:text .. a:submatches[0] .. a:text
440endfunc
Bram Moolenaar4c054e92019-11-10 00:13:50 +0100441func SubReplacer20(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, submatches)
442 return a:t3 .. a:submatches[0] .. a:t11
443endfunc
Bram Moolenaarb0745b22019-11-09 22:28:11 +0100444
445func Test_substitute_partial()
446 call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacer', ['foo']), 'g'))
Bram Moolenaar4c054e92019-11-10 00:13:50 +0100447
448 " 19 arguments plus one is just OK
449 let Replacer = function('SubReplacer20', repeat(['foo'], 19))
450 call assert_equal('1foo2foo3', substitute('123', '2', Replacer, 'g'))
451
452 " 20 arguments plus one is too many
453 let Replacer = function('SubReplacer20', repeat(['foo'], 20))
Bram Moolenaare2e40752020-09-04 21:18:46 +0200454 call assert_fails("call substitute('123', '2', Replacer, 'g')", 'E118:')
Bram Moolenaarb0745b22019-11-09 22:28:11 +0100455endfunc
456
Bram Moolenaar7a2217b2021-06-06 12:33:49 +0200457func Test_substitute_float()
458 CheckFeature float
459
460 call assert_equal('number 1.23', substitute('number ', '$', { -> 1.23 }, ''))
461 vim9 assert_equal('number 1.23', substitute('number ', '$', () => 1.23, ''))
462endfunc
463
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200464" Tests for *sub-replace-special* and *sub-replace-expression* on :substitute.
465
466" Execute a list of :substitute command tests
467func Run_SubCmd_Tests(tests)
468 enew!
469 for t in a:tests
470 let start = line('.') + 1
471 let end = start + len(t[2]) - 1
Bram Moolenaarbb265962019-10-31 04:38:36 +0100472 " TODO: why is there a one second delay the first time we get here?
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200473 exe "normal o" . t[0]
474 call cursor(start, 1)
475 exe t[1]
476 call assert_equal(t[2], getline(start, end), t[1])
477 endfor
478 enew!
479endfunc
480
481func Test_sub_cmd_1()
482 set magic
483 set cpo&
484
485 " List entry format: [input, cmd, output]
486 let tests = [['A', 's/A/&&/', ['AA']],
487 \ ['B', 's/B/\&/', ['&']],
488 \ ['C123456789', 's/C\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\0\9\8\7\6\5\4\3\2\1/', ['C123456789987654321']],
489 \ ['D', 's/D/d/', ['d']],
490 \ ['E', 's/E/~/', ['d']],
491 \ ['F', 's/F/\~/', ['~']],
492 \ ['G', 's/G/\ugg/', ['Gg']],
493 \ ['H', 's/H/\Uh\Eh/', ['Hh']],
494 \ ['I', 's/I/\lII/', ['iI']],
495 \ ['J', 's/J/\LJ\EJ/', ['jJ']],
496 \ ['K', 's/K/\Uk\ek/', ['Kk']],
497 \ ['lLl', "s/L/\<C-V>\<C-M>/", ["l\<C-V>", 'l']],
498 \ ['mMm', 's/M/\r/', ['m', 'm']],
499 \ ['nNn', "s/N/\\\<C-V>\<C-M>/", ["n\<C-V>", 'n']],
500 \ ['oOo', 's/O/\n/', ["o\no"]],
501 \ ['pPp', 's/P/\b/', ["p\<C-H>p"]],
502 \ ['qQq', 's/Q/\t/', ["q\tq"]],
503 \ ['rRr', 's/R/\\/', ['r\r']],
504 \ ['sSs', 's/S/\c/', ['scs']],
505 \ ['tTt', "s/T/\<C-V>\<C-J>/", ["t\<C-V>\<C-J>t"]],
506 \ ['U', 's/U/\L\uuUu\l\EU/', ['UuuU']],
507 \ ['V', 's/V/\U\lVvV\u\Ev/', ['vVVv']]
508 \ ]
509 call Run_SubCmd_Tests(tests)
510endfunc
511
512func Test_sub_cmd_2()
513 set nomagic
514 set cpo&
515
516 " List entry format: [input, cmd, output]
517 let tests = [['A', 's/A/&&/', ['&&']],
518 \ ['B', 's/B/\&/', ['B']],
519 \ ['C123456789', 's/\mC\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\0\9\8\7\6\5\4\3\2\1/', ['C123456789987654321']],
520 \ ['D', 's/D/d/', ['d']],
521 \ ['E', 's/E/~/', ['~']],
522 \ ['F', 's/F/\~/', ['~']],
523 \ ['G', 's/G/\ugg/', ['Gg']],
524 \ ['H', 's/H/\Uh\Eh/', ['Hh']],
525 \ ['I', 's/I/\lII/', ['iI']],
526 \ ['J', 's/J/\LJ\EJ/', ['jJ']],
527 \ ['K', 's/K/\Uk\ek/', ['Kk']],
528 \ ['lLl', "s/L/\<C-V>\<C-M>/", ["l\<C-V>", 'l']],
529 \ ['mMm', 's/M/\r/', ['m', 'm']],
530 \ ['nNn', "s/N/\\\<C-V>\<C-M>/", ["n\<C-V>", 'n']],
531 \ ['oOo', 's/O/\n/', ["o\no"]],
532 \ ['pPp', 's/P/\b/', ["p\<C-H>p"]],
533 \ ['qQq', 's/Q/\t/', ["q\tq"]],
534 \ ['rRr', 's/R/\\/', ['r\r']],
535 \ ['sSs', 's/S/\c/', ['scs']],
536 \ ['tTt', "s/T/\<C-V>\<C-J>/", ["t\<C-V>\<C-J>t"]],
537 \ ['U', 's/U/\L\uuUu\l\EU/', ['UuuU']],
538 \ ['V', 's/V/\U\lVvV\u\Ev/', ['vVVv']]
539 \ ]
540 call Run_SubCmd_Tests(tests)
541endfunc
542
543func Test_sub_cmd_3()
544 set nomagic
545 set cpo&
546
547 " List entry format: [input, cmd, output]
548 let tests = [['aAa', "s/A/\\='\\'/", ['a\a']],
549 \ ['bBb', "s/B/\\='\\\\'/", ['b\\b']],
550 \ ['cCc', "s/C/\\='\<C-V>\<C-M>'/", ["c\<C-V>", 'c']],
551 \ ['dDd', "s/D/\\='\\\<C-V>\<C-M>'/", ["d\\\<C-V>", 'd']],
552 \ ['eEe', "s/E/\\='\\\\\<C-V>\<C-M>'/", ["e\\\\\<C-V>", 'e']],
553 \ ['fFf', "s/F/\\='\r'/", ['f', 'f']],
554 \ ['gGg', "s/G/\\='\<C-V>\<C-J>'/", ["g\<C-V>", 'g']],
555 \ ['hHh', "s/H/\\='\\\<C-V>\<C-J>'/", ["h\\\<C-V>", 'h']],
556 \ ['iIi', "s/I/\\='\\\\\<C-V>\<C-J>'/", ["i\\\\\<C-V>", 'i']],
557 \ ['jJj', "s/J/\\='\n'/", ['j', 'j']],
558 \ ['kKk', 's/K/\="\r"/', ['k', 'k']],
559 \ ['lLl', 's/L/\="\n"/', ['l', 'l']]
560 \ ]
561 call Run_SubCmd_Tests(tests)
562endfunc
563
Bram Moolenaarf1699962019-08-31 17:48:19 +0200564" Test for submatch() on :substitute.
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200565func Test_sub_cmd_4()
566 set magic&
567 set cpo&
568
569 " List entry format: [input, cmd, output]
570 let tests = [ ['aAa', "s/A/\\=substitute(submatch(0), '.', '\\', '')/",
Bram Moolenaar1e115362019-01-09 23:01:02 +0100571 \ ['a\a']],
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200572 \ ['bBb', "s/B/\\=substitute(submatch(0), '.', '\\', '')/",
Bram Moolenaar1e115362019-01-09 23:01:02 +0100573 \ ['b\b']],
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200574 \ ['cCc', "s/C/\\=substitute(submatch(0), '.', '\<C-V>\<C-M>', '')/",
575 \ ["c\<C-V>", 'c']],
576 \ ['dDd', "s/D/\\=substitute(submatch(0), '.', '\\\<C-V>\<C-M>', '')/",
577 \ ["d\<C-V>", 'd']],
578 \ ['eEe', "s/E/\\=substitute(submatch(0), '.', '\\\\\<C-V>\<C-M>', '')/",
579 \ ["e\\\<C-V>", 'e']],
580 \ ['fFf', "s/F/\\=substitute(submatch(0), '.', '\\r', '')/",
581 \ ['f', 'f']],
582 \ ['gGg', 's/G/\=substitute(submatch(0), ".", "\<C-V>\<C-J>", "")/',
583 \ ["g\<C-V>", 'g']],
584 \ ['hHh', 's/H/\=substitute(submatch(0), ".", "\\\<C-V>\<C-J>", "")/',
585 \ ["h\<C-V>", 'h']],
586 \ ['iIi', 's/I/\=substitute(submatch(0), ".", "\\\\\<C-V>\<C-J>", "")/',
587 \ ["i\\\<C-V>", 'i']],
588 \ ['jJj', "s/J/\\=substitute(submatch(0), '.', '\\n', '')/",
589 \ ['j', 'j']],
590 \ ['kKk', "s/K/\\=substitute(submatch(0), '.', '\\r', '')/",
591 \ ['k', 'k']],
592 \ ['lLl', "s/L/\\=substitute(submatch(0), '.', '\\n', '')/",
593 \ ['l', 'l']],
594 \ ]
595 call Run_SubCmd_Tests(tests)
596endfunc
597
598func Test_sub_cmd_5()
599 set magic&
600 set cpo&
601
602 " List entry format: [input, cmd, output]
603 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']],
604 \ ['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']]"]],
605 \ ]
606 call Run_SubCmd_Tests(tests)
607endfunc
608
609" Test for *:s%* on :substitute.
610func Test_sub_cmd_6()
611 set magic&
612 set cpo+=/
613
614 " List entry format: [input, cmd, output]
615 let tests = [ ['A', 's/A/a/', ['a']],
616 \ ['B', 's/B/%/', ['a']],
617 \ ]
618 call Run_SubCmd_Tests(tests)
619
620 set cpo-=/
621 let tests = [ ['C', 's/C/c/', ['c']],
622 \ ['D', 's/D/%/', ['%']],
623 \ ]
624 call Run_SubCmd_Tests(tests)
625
626 set cpo&
627endfunc
628
629" Test for :s replacing \n with line break.
630func Test_sub_cmd_7()
631 set magic&
632 set cpo&
633
634 " List entry format: [input, cmd, output]
635 let tests = [ ["A\<C-V>\<C-M>A", 's/A./\=submatch(0)/', ['A', 'A']],
636 \ ["B\<C-V>\<C-J>B", 's/B./\=submatch(0)/', ['B', 'B']],
637 \ ["C\<C-V>\<C-J>C", 's/C./\=strtrans(string(submatch(0, 1)))/', [strtrans("['C\<C-J>']C")]],
638 \ ["D\<C-V>\<C-J>\nD", 's/D.\nD/\=strtrans(string(submatch(0, 1)))/', [strtrans("['D\<C-J>', 'D']")]],
639 \ ["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']")]],
640 \ ]
641 call Run_SubCmd_Tests(tests)
642
643 exe "normal oQ\nQ\<Esc>k"
Bram Moolenaare2e40752020-09-04 21:18:46 +0200644 call assert_fails('s/Q[^\n]Q/\=submatch(0)."foobar"/', 'E486:')
Bram Moolenaar15993ce2017-10-26 20:21:44 +0200645 enew!
646endfunc
647
648func TitleString()
649 let check = 'foo' =~ 'bar'
650 return ""
651endfunc
652
653func Test_sub_cmd_8()
654 set titlestring=%{TitleString()}
655
656 enew!
657 call append(0, ['', 'test_one', 'test_two'])
658 call cursor(1,1)
659 /^test_one/s/.*/\="foo\nbar"/
660 call assert_equal('foo', getline(2))
661 call assert_equal('bar', getline(3))
662 call feedkeys(':/^test_two/s/.*/\="foo\nbar"/c', "t")
663 call feedkeys("\<CR>y", "xt")
664 call assert_equal('foo', getline(4))
665 call assert_equal('bar', getline(5))
666
667 enew!
668 set titlestring&
669endfunc
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100670
Bram Moolenaar80341bc2019-05-20 20:34:51 +0200671func Test_sub_cmd_9()
672 new
673 let input = ['1 aaa', '2 aaa', '3 aaa']
674 call setline(1, input)
675 func Foo()
676 return submatch(0)
677 endfunc
678 %s/aaa/\=Foo()/gn
679 call assert_equal(input, getline(1, '$'))
680 call assert_equal(1, &modifiable)
681
682 delfunc Foo
683 bw!
684endfunc
685
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100686func Test_nocatch_sub_failure_handling()
687 " normal error results in all replacements
Bram Moolenaar80341bc2019-05-20 20:34:51 +0200688 func Foo()
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100689 foobar
690 endfunc
691 new
692 call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
693 %s/aaa/\=Foo()/g
694 call assert_equal(['1 0', '2 0', '3 0'], getline(1, 3))
695
696 " Trow without try-catch causes abort after the first line.
697 " We cannot test this, since it would stop executing the test script.
698
699 " try/catch does not result in any changes
700 func! Foo()
701 throw 'error'
702 endfunc
703 call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
704 let error_caught = 0
705 try
706 %s/aaa/\=Foo()/g
707 catch
708 let error_caught = 1
709 endtry
710 call assert_equal(1, error_caught)
711 call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3))
712
Bram Moolenaar6349e942019-05-18 13:41:22 +0200713 " Same, but using "n" flag so that "sandbox" gets set
714 call setline(1, ['1 aaa', '2 aaa', '3 aaa'])
715 let error_caught = 0
716 try
717 %s/aaa/\=Foo()/gn
718 catch
719 let error_caught = 1
720 endtry
721 call assert_equal(1, error_caught)
722 call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3))
723
Bram Moolenaar80341bc2019-05-20 20:34:51 +0200724 delfunc Foo
Bram Moolenaar0e97b942019-03-27 22:53:53 +0100725 bwipe!
726endfunc
Bram Moolenaarc6b37db2019-04-27 18:00:34 +0200727
728" Test ":s/pat/sub/" with different ~s in sub.
729func Test_replace_with_tilde()
730 new
731 " Set the last replace string to empty
732 s/^$//
733 call append(0, ['- Bug in "vPPPP" on this text:'])
734 normal gg
735 s/u/~u~/
736 call assert_equal('- Bug in "vPPPP" on this text:', getline(1))
737 s/i/~u~/
738 call assert_equal('- Bug uuun "vPPPP" on this text:', getline(1))
739 s/o/~~~/
740 call assert_equal('- Bug uuun "vPPPP" uuuuuuuuun this text:', getline(1))
741 close!
742endfunc
743
744func Test_replace_keeppatterns()
745 new
746 a
747foobar
748
749substitute foo asdf
750
751one two
752.
753
754 normal gg
755 /^substitute
756 s/foo/bar/
757 call assert_equal('foo', @/)
758 call assert_equal('substitute bar asdf', getline('.'))
759
760 /^substitute
761 keeppatterns s/asdf/xyz/
762 call assert_equal('^substitute', @/)
763 call assert_equal('substitute bar xyz', getline('.'))
764
765 exe "normal /bar /e\<CR>"
766 call assert_equal(15, col('.'))
767 normal -
768 keeppatterns /xyz
769 call assert_equal('bar ', @/)
770 call assert_equal('substitute bar xyz', getline('.'))
771 exe "normal 0dn"
772 call assert_equal('xyz', getline('.'))
773
774 close!
775endfunc
Bram Moolenaarbb265962019-10-31 04:38:36 +0100776
777func Test_sub_beyond_end()
778 new
779 call setline(1, '#')
780 let @/ = '^#\n\zs'
781 s///e
782 call assert_equal('#', getline(1))
783 bwipe!
784endfunc
Bram Moolenaar5d98dc22020-01-29 21:57:34 +0100785
Bram Moolenaarea3db912020-02-02 15:32:13 +0100786" Test for repeating last substitution using :~ and :&r
787func Test_repeat_last_sub()
788 new
789 call setline(1, ['blue green yellow orange white'])
790 s/blue/red/
791 let @/ = 'yellow'
792 ~
793 let @/ = 'white'
794 :&r
795 let @/ = 'green'
796 s//gray
797 call assert_equal('red gray red orange red', getline(1))
798 close!
799endfunc
800
801" Test for Vi compatible substitution:
802" \/{string}/, \?{string}? and \&{string}&
803func Test_sub_vi_compatibility()
804 new
805 call setline(1, ['blue green yellow orange blue'])
806 let @/ = 'orange'
807 s\/white/
808 let @/ = 'blue'
809 s\?amber?
810 let @/ = 'white'
811 s\&green&
812 call assert_equal('amber green yellow white green', getline(1))
813 close!
Bram Moolenaar9fb7b422022-03-05 21:13:26 +0000814
815 call assert_fails('vim9cmd s\/white/', 'E1270:')
816 call assert_fails('vim9cmd s\?white?', 'E1270:')
817 call assert_fails('vim9cmd s\&white&', 'E1270:')
Bram Moolenaarea3db912020-02-02 15:32:13 +0100818endfunc
819
820" Test for substitute with the new text longer than the original text
821func Test_sub_expand_text()
822 new
823 call setline(1, 'abcabcabcabcabcabcabcabc')
824 s/b/\=repeat('B', 10)/g
825 call assert_equal(repeat('aBBBBBBBBBBc', 8), getline(1))
826 close!
827endfunc
828
Bram Moolenaar07ada5f2020-02-05 20:38:22 +0100829" Test for command failures when the last substitute pattern is not set.
830func Test_sub_with_no_last_pat()
Bram Moolenaar9f6277b2020-02-11 22:04:02 +0100831 let lines =<< trim [SCRIPT]
832 call assert_fails('~', 'E33:')
Bram Moolenaar9b7bf9e2020-07-11 22:14:59 +0200833 call assert_fails('s//abc/g', 'E35:')
834 call assert_fails('s\/bar', 'E35:')
835 call assert_fails('s\&bar&', 'E33:')
Bram Moolenaar9f6277b2020-02-11 22:04:02 +0100836 call writefile(v:errors, 'Xresult')
837 qall!
838 [SCRIPT]
839 call writefile(lines, 'Xscript')
840 if RunVim([], [], '--clean -S Xscript')
841 call assert_equal([], readfile('Xresult'))
842 endif
Bram Moolenaar07ada5f2020-02-05 20:38:22 +0100843
Bram Moolenaar9f6277b2020-02-11 22:04:02 +0100844 let lines =<< trim [SCRIPT]
845 set cpo+=/
846 call assert_fails('s/abc/%/', 'E33:')
847 call writefile(v:errors, 'Xresult')
848 qall!
849 [SCRIPT]
850 call writefile(lines, 'Xscript')
851 if RunVim([], [], '--clean -S Xscript')
852 call assert_equal([], readfile('Xresult'))
853 endif
854
855 call delete('Xscript')
856 call delete('Xresult')
Bram Moolenaar07ada5f2020-02-05 20:38:22 +0100857endfunc
858
Bram Moolenaarca68ae12020-03-30 19:32:53 +0200859func Test_substitute()
860 call assert_equal('a1a2a3a', substitute('123', '\zs', 'a', 'g'))
Bram Moolenaar004a6782020-04-11 17:09:31 +0200861 " Substitute with special keys
862 call assert_equal("a\<End>c", substitute('abc', "a.c", "a\<End>c", ''))
863endfunc
864
865func Test_substitute_expr()
866 let g:val = 'XXX'
867 call assert_equal('XXX', substitute('yyy', 'y*', '\=g:val', ''))
868 call assert_equal('XXX', substitute('yyy', 'y*', {-> g:val}, ''))
869 call assert_equal("-\u1b \uf2-", substitute("-%1b %f2-", '%\(\x\x\)',
870 \ '\=nr2char("0x" . submatch(1))', 'g'))
871 call assert_equal("-\u1b \uf2-", substitute("-%1b %f2-", '%\(\x\x\)',
872 \ {-> nr2char("0x" . submatch(1))}, 'g'))
873
874 call assert_equal('231', substitute('123', '\(.\)\(.\)\(.\)',
875 \ {-> submatch(2) . submatch(3) . submatch(1)}, ''))
876
877 func Recurse()
878 return substitute('yyy', 'y\(.\)y', {-> submatch(1)}, '')
879 endfunc
880 " recursive call works
881 call assert_equal('-y-x-', substitute('xxx', 'x\(.\)x', {-> '-' . Recurse() . '-' . submatch(1) . '-'}, ''))
882
883 call assert_fails("let s=submatch([])", 'E745:')
884 call assert_fails("let s=submatch(2, [])", 'E745:')
885endfunc
886
887func Test_invalid_submatch()
888 " This was causing invalid memory access in Vim-7.4.2232 and older
889 call assert_fails("call substitute('x', '.', {-> submatch(10)}, '')", 'E935:')
890 call assert_fails('eval submatch(-1)', 'E935:')
891 call assert_equal('', submatch(0))
892 call assert_equal('', submatch(1))
893 call assert_equal([], submatch(0, 1))
894 call assert_equal([], submatch(1, 1))
895endfunc
896
Bram Moolenaar8a0dcf42020-09-06 15:14:45 +0200897func Test_submatch_list_concatenate()
898 let pat = 'A\(.\)'
899 let Rep = {-> string([submatch(0, 1)] + [[submatch(1)]])}
900 call substitute('A1', pat, Rep, '')->assert_equal("[['A1'], ['1']]")
901endfunc
902
Bram Moolenaar004a6782020-04-11 17:09:31 +0200903func Test_substitute_expr_arg()
904 call assert_equal('123456789-123456789=', substitute('123456789',
905 \ '\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)',
906 \ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))
907
908 call assert_equal('123456-123456=789', substitute('123456789',
909 \ '\(.\)\(.\)\(.\)\(a*\)\(n*\)\(.\)\(.\)\(.\)\(x*\)',
910 \ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))
911
912 call assert_equal('123456789-123456789x=', substitute('123456789',
913 \ '\(.\)\(.\)\(.*\)',
914 \ {m -> m[0] . '-' . m[1] . m[2] . m[3] . 'x' . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, ''))
915
916 call assert_fails("call substitute('xxx', '.', {m -> string(add(m, 'x'))}, '')", 'E742:')
917 call assert_fails("call substitute('xxx', '.', {m -> string(insert(m, 'x'))}, '')", 'E742:')
918 call assert_fails("call substitute('xxx', '.', {m -> string(extend(m, ['x']))}, '')", 'E742:')
919 call assert_fails("call substitute('xxx', '.', {m -> string(remove(m, 1))}, '')", 'E742:')
920endfunc
921
922" Test for using a function to supply the substitute string
923func Test_substitute_using_func()
924 func Xfunc()
925 return '1234'
926 endfunc
927 call assert_equal('a1234f', substitute('abcdef', 'b..e',
928 \ function("Xfunc"), ''))
929 delfunc Xfunc
930endfunc
931
932" Test for using submatch() with a multiline match
933func Test_substitute_multiline_submatch()
934 new
935 call setline(1, ['line1', 'line2', 'line3', 'line4'])
936 %s/^line1\(\_.\+\)line4$/\=submatch(1)/
937 call assert_equal(['', 'line2', 'line3', ''], getline(1, '$'))
938 close!
Bram Moolenaarca68ae12020-03-30 19:32:53 +0200939endfunc
940
Bram Moolenaardf365142021-05-03 20:01:45 +0200941func Test_substitute_skipped_range()
942 new
943 if 0
944 /1/5/2/2/\n
945 endif
946 call assert_equal([0, 1, 1, 0, 1], getcurpos())
947 bwipe!
948endfunc
949
Dominique Pellebfb2bb12021-08-14 21:11:51 +0200950" Test using the 'gdefault' option (when on, flag 'g' is default on).
951func Test_substitute_gdefault()
952 new
953
954 " First check without 'gdefault'
955 call setline(1, 'foo bar foo')
956 s/foo/FOO/
957 call assert_equal('FOO bar foo', getline(1))
958 call setline(1, 'foo bar foo')
959 s/foo/FOO/g
960 call assert_equal('FOO bar FOO', getline(1))
961 call setline(1, 'foo bar foo')
962 s/foo/FOO/gg
963 call assert_equal('FOO bar foo', getline(1))
964
965 " Then check with 'gdefault'
966 set gdefault
967 call setline(1, 'foo bar foo')
968 s/foo/FOO/
969 call assert_equal('FOO bar FOO', getline(1))
970 call setline(1, 'foo bar foo')
971 s/foo/FOO/g
972 call assert_equal('FOO bar foo', getline(1))
973 call setline(1, 'foo bar foo')
974 s/foo/FOO/gg
975 call assert_equal('FOO bar FOO', getline(1))
976
977 " Setting 'compatible' should reset 'gdefault'
978 call assert_equal(1, &gdefault)
979 set compatible
980 call assert_equal(0, &gdefault)
981 set nocompatible
982 call assert_equal(0, &gdefault)
983
984 bw!
985endfunc
986
Bram Moolenaar37f47952022-01-29 14:21:51 +0000987" This was using "old_sub" after it was freed.
988func Test_using_old_sub()
989 set compatible maxfuncdepth=10
990 new
991 call setline(1, 'some text.')
992 func Repl()
993 ~
994 s/
995 endfunc
996 silent! s/\%')/\=Repl()
997
998 delfunc Repl
999 bwipe!
1000 set nocompatible
1001endfunc
1002
Yegappan Lakshmanan5e877ba2022-03-25 21:19:26 +00001003" Test for the 2-letter and 3-letter :substitute commands
1004func Test_substitute_short_cmd()
1005 new
1006 call setline(1, ['one', 'one one one'])
1007 s/one/two
1008 call cursor(2, 1)
1009
1010 " :sc
1011 call feedkeys(":sc\<CR>y", 'xt')
1012 call assert_equal('two one one', getline(2))
1013
1014 " :scg
1015 call setline(2, 'one one one')
1016 call feedkeys(":scg\<CR>nyq", 'xt')
1017 call assert_equal('one two one', getline(2))
1018
1019 " :sci
1020 call setline(2, 'ONE One onE')
1021 call feedkeys(":sci\<CR>y", 'xt')
1022 call assert_equal('two One onE', getline(2))
1023
1024 " :scI
1025 set ignorecase
1026 call setline(2, 'ONE One one')
1027 call feedkeys(":scI\<CR>y", 'xt')
1028 call assert_equal('ONE One two', getline(2))
1029 set ignorecase&
1030
1031 " :scn
1032 call setline(2, 'one one one')
1033 let t = execute('scn')->split("\n")
1034 call assert_equal(['1 match on 1 line'], t)
1035 call assert_equal('one one one', getline(2))
1036
1037 " :scp
1038 call setline(2, "\tone one one")
1039 redir => output
1040 call feedkeys(":scp\<CR>y", 'xt')
1041 redir END
1042 call assert_equal(' two one one', output->split("\n")[-1])
1043 call assert_equal("\ttwo one one", getline(2))
1044
1045 " :scl
1046 call setline(2, "\tone one one")
1047 redir => output
1048 call feedkeys(":scl\<CR>y", 'xt')
1049 redir END
1050 call assert_equal("^Itwo one one$", output->split("\n")[-1])
1051 call assert_equal("\ttwo one one", getline(2))
1052
1053 " :sgc
1054 call setline(2, 'one one one one one')
1055 call feedkeys(":sgc\<CR>nyyq", 'xt')
1056 call assert_equal('one two two one one', getline(2))
1057
1058 " :sg
1059 call setline(2, 'one one one')
1060 sg
1061 call assert_equal('two two two', getline(2))
1062
1063 " :sgi
1064 call setline(2, 'ONE One onE')
1065 sgi
1066 call assert_equal('two two two', getline(2))
1067
1068 " :sgI
1069 set ignorecase
1070 call setline(2, 'ONE One one')
1071 sgI
1072 call assert_equal('ONE One two', getline(2))
1073 set ignorecase&
1074
1075 " :sgn
1076 call setline(2, 'one one one')
1077 let t = execute('sgn')->split("\n")
1078 call assert_equal(['3 matches on 1 line'], t)
1079 call assert_equal('one one one', getline(2))
1080
1081 " :sgp
1082 call setline(2, "\tone one one")
1083 redir => output
1084 sgp
1085 redir END
1086 call assert_equal(' two two two', output->split("\n")[-1])
1087 call assert_equal("\ttwo two two", getline(2))
1088
1089 " :sgl
1090 call setline(2, "\tone one one")
1091 redir => output
1092 sgl
1093 redir END
1094 call assert_equal("^Itwo two two$", output->split("\n")[-1])
1095 call assert_equal("\ttwo two two", getline(2))
1096
1097 " :sgr
1098 call setline(2, "one one one")
1099 call cursor(2, 1)
1100 s/abc/xyz/e
1101 let @/ = 'one'
1102 sgr
1103 call assert_equal('xyz xyz xyz', getline(2))
1104
1105 " :sic
1106 call cursor(1, 1)
1107 s/one/two/e
1108 call setline(2, "ONE One one")
1109 call cursor(2, 1)
1110 call feedkeys(":sic\<CR>y", 'xt')
1111 call assert_equal('two One one', getline(2))
1112
1113 " :si
1114 call setline(2, "ONE One one")
1115 si
1116 call assert_equal('two One one', getline(2))
1117
1118 " :siI
1119 call setline(2, "ONE One one")
1120 siI
1121 call assert_equal('ONE One two', getline(2))
1122
1123 " :sin
1124 call setline(2, 'ONE One onE')
1125 let t = execute('sin')->split("\n")
1126 call assert_equal(['1 match on 1 line'], t)
1127 call assert_equal('ONE One onE', getline(2))
1128
1129 " :sip
1130 call setline(2, "\tONE One onE")
1131 redir => output
1132 sip
1133 redir END
1134 call assert_equal(' two One onE', output->split("\n")[-1])
1135 call assert_equal("\ttwo One onE", getline(2))
1136
1137 " :sir
1138 call setline(2, "ONE One onE")
1139 call cursor(2, 1)
1140 s/abc/xyz/e
1141 let @/ = 'one'
1142 sir
1143 call assert_equal('xyz One onE', getline(2))
1144
1145 " :sIc
1146 call cursor(1, 1)
1147 s/one/two/e
1148 call setline(2, "ONE One one")
1149 call cursor(2, 1)
1150 call feedkeys(":sIc\<CR>y", 'xt')
1151 call assert_equal('ONE One two', getline(2))
1152
1153 " :sIg
1154 call setline(2, "ONE one onE one")
1155 sIg
1156 call assert_equal('ONE two onE two', getline(2))
1157
1158 " :sIi
1159 call setline(2, "ONE One one")
1160 sIi
1161 call assert_equal('two One one', getline(2))
1162
1163 " :sI
1164 call setline(2, "ONE One one")
1165 sI
1166 call assert_equal('ONE One two', getline(2))
1167
1168 " :sIn
1169 call setline(2, 'ONE One one')
1170 let t = execute('sIn')->split("\n")
1171 call assert_equal(['1 match on 1 line'], t)
1172 call assert_equal('ONE One one', getline(2))
1173
1174 " :sIp
1175 call setline(2, "\tONE One one")
1176 redir => output
1177 sIp
1178 redir END
1179 call assert_equal(' ONE One two', output->split("\n")[-1])
1180 call assert_equal("\tONE One two", getline(2))
1181
1182 " :sIl
1183 call setline(2, "\tONE onE one")
1184 redir => output
1185 sIl
1186 redir END
1187 call assert_equal("^IONE onE two$", output->split("\n")[-1])
1188 call assert_equal("\tONE onE two", getline(2))
1189
1190 " :sIr
1191 call setline(2, "ONE one onE")
1192 call cursor(2, 1)
1193 s/abc/xyz/e
1194 let @/ = 'one'
1195 sIr
1196 call assert_equal('ONE xyz onE', getline(2))
1197
1198 " :src
1199 call setline(2, "ONE one one")
1200 call cursor(2, 1)
1201 s/abc/xyz/e
1202 let @/ = 'one'
1203 call feedkeys(":src\<CR>y", 'xt')
1204 call assert_equal('ONE xyz one', getline(2))
1205
1206 " :srg
1207 call setline(2, "one one one")
1208 call cursor(2, 1)
1209 s/abc/xyz/e
1210 let @/ = 'one'
1211 srg
1212 call assert_equal('xyz xyz xyz', getline(2))
1213
1214 " :sri
1215 call setline(2, "ONE one onE")
1216 call cursor(2, 1)
1217 s/abc/xyz/e
1218 let @/ = 'one'
1219 sri
1220 call assert_equal('xyz one onE', getline(2))
1221
1222 " :srI
1223 call setline(2, "ONE one onE")
1224 call cursor(2, 1)
1225 s/abc/xyz/e
1226 let @/ = 'one'
1227 srI
1228 call assert_equal('ONE xyz onE', getline(2))
1229
1230 " :srn
1231 call setline(2, "ONE one onE")
1232 call cursor(2, 1)
1233 s/abc/xyz/e
1234 let @/ = 'one'
1235 let t = execute('srn')->split("\n")
1236 call assert_equal(['1 match on 1 line'], t)
1237 call assert_equal('ONE one onE', getline(2))
1238
1239 " :srp
1240 call setline(2, "\tONE one onE")
1241 call cursor(2, 1)
1242 s/abc/xyz/e
1243 let @/ = 'one'
1244 redir => output
1245 srp
1246 redir END
1247 call assert_equal(' ONE xyz onE', output->split("\n")[-1])
1248 call assert_equal("\tONE xyz onE", getline(2))
1249
1250 " :srl
1251 call setline(2, "\tONE one onE")
1252 call cursor(2, 1)
1253 s/abc/xyz/e
1254 let @/ = 'one'
1255 redir => output
1256 srl
1257 redir END
1258 call assert_equal("^IONE xyz onE$", output->split("\n")[-1])
1259 call assert_equal("\tONE xyz onE", getline(2))
1260
1261 " :sr
1262 call setline(2, "ONE one onE")
1263 call cursor(2, 1)
1264 s/abc/xyz/e
1265 let @/ = 'one'
1266 sr
1267 call assert_equal('ONE xyz onE', getline(2))
1268
1269 " :sce
1270 s/abc/xyz/e
1271 call assert_fails("sc", 'E486:')
1272 sce
1273 " :sge
1274 call assert_fails("sg", 'E486:')
1275 sge
1276 " :sie
1277 call assert_fails("si", 'E486:')
1278 sie
1279 " :sIe
1280 call assert_fails("sI", 'E486:')
1281 sIe
1282
1283 bw!
1284endfunc
Bram Moolenaar37f47952022-01-29 14:21:51 +00001285
Bram Moolenaar5d98dc22020-01-29 21:57:34 +01001286" vim: shiftwidth=2 sts=2 expandtab