Skip to content

Instantly share code, notes, and snippets.

@dmwit
Created March 9, 2022 15:53
Show Gist options
  • Save dmwit/288b155e2db22946168d1da223995c8a to your computer and use it in GitHub Desktop.
Save dmwit/288b155e2db22946168d1da223995c8a to your computer and use it in GitHub Desktop.
quickly add/remove Debug.Trace to a module
" drop this in your ftplugin directory
nnoremap <silent> <buffer> <leader>db :call AddDebugImport()<cr>
inoremap <silent> <buffer> <leader>db <c-o>:call AddDebugImport()<cr>
nnoremap <silent> <buffer> <leader>de :call DeleteDebugImport()<cr>
inoremap <silent> <buffer> <leader>de <c-o>:call DeleteDebugImport()<cr>
" TODO: does not work well with literate Haskell or funky module indentations
function! AddDebugImport()
let s:orig_pos = winsaveview()
let s:dline = 0
" step 1: try to find a suitable place to add it
" current heuristic is to try these in order:
" * below the last import
" * below the module declaration
" * below the last language pragma
" * at the top of the file
try
keepjumps normal G$?\C\m^\s*import\>
catch /E486:/
try
" If the first line has the module declaration and nowrapscan is
" set, gg/module will not match. To fix this, we use \zs to start
" the match at the 'o' of module.
keepjumps normal gg/\C\m^\s*m\zsodule\>
/\C\m\<where\>
catch /E486:/
try
keepjumps normal G$?\c\m{-# language\>
catch /E486:/
keepjumps normal gg
let s:dline = -1
endtry
endtry
endtry
" step 2: add it
let s:import_pos = winsaveview()
if s:dline == -1
let s:lines = ["-- TODO: delete","import Debug.Trace",""]
else
let s:lines = ["", "-- TODO: delete","import Debug.Trace"]
endif
call append(line('.') + s:dline, s:lines)
" step 3: jump back to the original position, or three lines later if we
" inserted the import before where the cursor was before
call AdjustView(s:orig_pos, s:import_pos["lnum"] + s:dline, len(s:lines))
keepjumps call winrestview(s:orig_pos)
endfunction
function! DeleteDebugImport()
let s:orig_pos = winsaveview()
keeppatterns 1,$s/\m^-- TODO: delete\nimport Debug.Trace\n\s*\n//eI
keeppatterns 1,$s/\m^\s*\n-- TODO: delete\nimport Debug.Trace$//eI
" TODO: compute the updated position properly. seems hard
call winrestview(s:orig_pos)
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment