Skip to content

Instantly share code, notes, and snippets.

@haxpor
Created August 29, 2021 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haxpor/02ffa04192b4bea5fea8892d322c602e to your computer and use it in GitHub Desktop.
Save haxpor/02ffa04192b4bea5fea8892d322c602e to your computer and use it in GitHub Desktop.
Implementation to get the current function in the current scope as of cursor position is in (with caveat)
" show the function name for the current position the cursor is in
" cursor needs to be embraced into the context of function
" CAVEAT: not work yet with macros
" CAVEAT: cursor outside of functions but inside a namespace will return upper
" function scope, not the namespace scope
function! ShowFuncNameC_CPP()
let lnum = line(".")
let col = col(".")
let is_found = 0
echohl ModeMsg
" attempt to find the embracing context of function related scope
" for limited number of times
let attempt_count = 0
while attempt_count < 5
let attempt_count += 1
let begin_brace_line = search("^[^#/]*\{.*", 'bW')
let trimmed_begin_brace_line_txt = trim(getline(begin_brace_line))
" check for false positive
if trimmed_begin_brace_line_txt =~ ";"
" set current position to keep searching next time
call setpos(".", [0, begin_brace_line, col("."), 0])
continue
endif
" check if we need to go up one more line to get to the actual function
" name
if trimmed_begin_brace_line_txt == "{"
let begin_brace_line -= 1
endif
" updated trimmed begin brace line
let trimmed_begin_brace_line_txt = trim(getline(begin_brace_line))
" check if it's actually a function scope
if trimmed_begin_brace_line_txt =~ ".*\(.*\)"
" filter out non-relevant function related keywords e.g. conditional
" statement like if/else if
if trimmed_begin_brace_line_txt =~ "\\(switch\\|if\\|else if\\|while\\|for\\|do while)\\)"
" set current position to keep searching next time
call setpos(".", [0, begin_brace_line, col("."), 0])
else
echo trimmed_begin_brace_line_txt
let is_found = 1
break
endif
else
" set current position to keep searching next time
call setpos(".", [0, begin_brace_line, col("."), 0])
endif
" check if it is a namespace or class scope
if trimmed_begin_brace_line_txt =~ "^\\(namespace\\|class\\).*"
echo trimmed_begin_brace_line_txt
let is_found = 1
break
else
" set current position to keep searching next time
call setpos(".", [0, begin_brace_line, col("."), 0])
endif
endwhile
" clear the output not to clutter the statusline
if is_found == 0
echo ""
endif
echohl None
call search("\\%" . lnum . "l" . "\\%" . col . "c")
endfun
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment