1let g:_executable = 'glitch'
 2let g:_arguments = ''
 3let g:_envs = { 'DISPLAY': ':69', 'LOG_LEVEL': '3', 'DEBUG': '1' }
 4let g:_make = 'make -B'
 5
 6set makeprg=make
 7set errorformat=%f:%l:%c:\ %m
 8packadd termdebug
 9
10let g:termdebug_config = {}
11let g:termdebug_config['variables_window'] = v:true
12
13nnoremap <leader>x :call LocalRun()<CR>
14nnoremap <leader>c :call LocalMake()<CR>
15nnoremap <leader>m :call LocalDebugMain()<CR>
16nnoremap <leader>l :call LocalDebugLine()<CR>
17
18function! LocalRun() abort
19	let envs = join( map(items(g:_envs), { _, kv -> kv[0] . '=' . kv[1] }), ' ')
20	execute printf("term env %s ./%s %s", envs, g:_executable, g:_arguments)
21endfunction
22
23function! LocalDebugMain() abort
24	execute printf('Termdebug %s %s', g:_executable, g:_arguments)
25
26	for [k, v] in items(g:_envs)
27		call TermDebugSendCommand(printf('set env %s %s', k, v))
28	endfor
29
30	call TermDebugSendCommand('directory ' . getcwd())
31	call TermDebugSendCommand('break main')
32	call TermDebugSendCommand('run')
33endfunction
34
35function! LocalDebugLine() abort
36	execute printf('Termdebug %s %s', g:_executable, g:_arguments)
37
38	for [k, v] in items(g:_envs)
39		call TermDebugSendCommand(printf('set env %s %s', k, v))
40	endfor
41
42	call TermDebugSendCommand('directory ' . getcwd())
43	call TermDebugSendCommand(printf('break %s:%d', expand('%:p'), line('.')))
44	call TermDebugSendCommand('run')
45endfunction
46
47function! LocalMake() abort
48	let envs = join( map(items(g:_envs), { _, kv -> kv[0] . '=' . kv[1] }), ' ')
49	execute printf('silent !env %s %s', g:_make, envs)
50
51	" Filter non valid errors out of quicklist.
52	let qfl = getqflist()
53	let filtered = filter(copy(qfl), {_, entry -> entry.valid == 1})
54	call setqflist(filtered, 'r')
55
56	redraw!
57
58	if len(filtered) > 0
59		execute exists(':CtrlPQuickfix') ? 'CtrlPQuickfix' : 'copen'
60	else
61		cclose
62	endif
63endfunction