2

I want to display the C function to which current line belongs. I don't want to use any plugin because I work on multiple operating systems with different machine capabilities and configurations. I have tried most plugins and it doesn't work out for one reason or the other. I have to write something very basic and minimal and which works with extremely basic vim features.

Current Solution:

I have copied a vim function from colleague which essentially searches for a reg-ex, matching the start of a function name. It shows the name at the bottom screen for a few sec and goes away

fun! ShowFuncName()
        let lnum = line(".")
        let col = col(".")
        echohl ModeMsg
        echo getline(search("^[^ \t#/]\\{2}.*[^:]\s*$", 'bW'))
        echohl None
        call search("\\%" . lnum . "l" . "\\%" . col . "c")
    endfun

Problem

The problem is this thing doesn't work with labels. If there is a label present in a line between the function definition and current line, the script shows the label name instead of function name.

Otherwise the script works because it is a hard and fast rule in our codebase to always start function definition from column 1 and braces from the second line onwards.

Proposed Fix

Instead of search for regex, why not use the vim movement keys. That is do following:

  1. Store current line#, column#
  2. Jump back with movement keys '[[' to go to the function definition
  3. The line just above this will have C function. (this is stricly enforced in coding guidelines)
  4. print the line
  5. Jump to the line#, column# stored in step #1.

I don't know how to do the step 2. mentioned above.

thequark
  • 457

2 Answers2

5

I believe you want this

function! ShowFuncName()
    let cursor_pos = getpos('.')
    echohl ModeMsg
    normal! [[k
    echo getline('.')
    echohl None
    call setpos('.', cursor_pos)
endfunction

The normal command executes [[k in normal mode moving the cursor to the function definition. Then it prints the line the cursor is on.

The cursor position is restored to the position it was in originally using getpos() and setpos() functions.

FDinoff
  • 1,871
0

For anyone searching, another way could be using execute and norm:

function! MoveCursorDown()
    execute "norm j"
endfunction
wxz
  • 141