@@ -302,4 +302,65 @@ function M.pick_file(opts)
302
302
end
303
303
304
304
305
+ --- Split args string into a table of arguments.
306
+ --- Works with single and double quoted strings. Escaped quotes are supported.
307
+ ---
308
+ --- <pre>
309
+ --- require("dap.utils").split_args("runserver --debug true --reason 'I\'m dumb'")
310
+ --- {runserver, --debug, true, I'm dumb}
311
+ --- </pre>
312
+ ---
313
+ --- <pre>
314
+ --- require("dap.utils").split_args('--comment "I\'m \"this\" close"')
315
+ --- {--comment, I'm "this" close}
316
+ --- </pre>
317
+ ---
318
+ --- Inspired by http://lua-users.org/wiki/LpegRecipes
319
+ --- @param args string
320
+ --- @return table
321
+ function M .split_args (args )
322
+ local lpeg = vim .lpeg
323
+
324
+ local P , S , C , Cc , Ct = lpeg .P , lpeg .S , lpeg .C , lpeg .Cc , lpeg .Ct
325
+
326
+ --- @param id string
327
+ --- @param patt vim.lpeg.Capture
328
+ --- @return vim.lpeg.Pattern
329
+ local function token (id , patt )
330
+ return Ct (Cc (id ) * C (patt ))
331
+ end
332
+
333
+ local single_quoted = P (" '" ) * ((1 - S (" '\r\n\f\\ " )) + (P (" \\ " ) * 1 )) ^ 0 * " '"
334
+ local double_quoted = P (' "' ) * ((1 - S (' "\r\n\f\\ ' )) + (P (" \\ " ) * 1 )) ^ 0 * ' "'
335
+
336
+ local whitespace = token (" whitespace" , S (" \r\n\f\t " ) ^ 1 )
337
+ local word = token (" word" , (1 - S (" ' \r\n\f\t\" " )) ^ 1 )
338
+ local string = token (" string" , single_quoted + double_quoted )
339
+
340
+ local pattern = Ct ((string + whitespace + word ) ^ 0 )
341
+
342
+ local t = {}
343
+ local tokens = lpeg .match (pattern , args )
344
+
345
+ -- somehow, this did not work out
346
+ if tokens == nil or type (tokens ) == " integer" then
347
+ return t
348
+ end
349
+
350
+ for _ , tok in ipairs (tokens ) do
351
+ if tok [1 ] ~= " whitespace" then
352
+ if tok [1 ] == " string" then
353
+ -- cut off quotes and replace escaped quotes
354
+ local v , _ = tok [2 ]:sub (2 , - 2 ):gsub (" \\ (['\" ])" , " %1" )
355
+ table.insert (t , v )
356
+ else
357
+ table.insert (t , tok [2 ])
358
+ end
359
+ end
360
+ end
361
+
362
+ return t
363
+ end
364
+
365
+
305
366
return M
0 commit comments