1

I am trying to create an org-capture template which works with yankpad and yasnippets to such that if I am working with some c code like this:

example.c

static int somefunc(int a) {
   if (a ==5) {
       return 1;
   }
   else {

       return 0;
   }
}

I want to be able to, with a single org-capture, yank the entirety of the function and its signature into an org file like so:

example.org

#+NAME: example_proto
#+BEGIN_SRC C
int somefunc(int a);
#+END_SRC

#+NAME: example_func
#+BEGIN_SRC C
static int somefunc(int a) {
   if (a ==5) {
       return 1;
   }
   else {

       return 0;
   }
}
#+END_SRC

This requires the following:

  • Get the scope of the current function.
  • Get the prototype of the current function.
  • Pass these into an org-capture template.
  • Use yasnippets in the org-capture template.

The main piece I can't figure out is how to find out what function defines the current scope programmatically so that I can pass it as an argument to other elisp functions (to determine scope, callees, etc).

If someone can point me in the right direction that'd be much appreciated.

2
  • Please check the paragraph starting with "The main piece...": I edited it slightly in order for the sentence to parse correctly, but I'm not sure it still reflects what you meant. – NickD Oct 11 '20 at 4:10
  • Please change the question title to express the actual question, which I guess is somewhere in that paragraph that @NickD's comment refers to. – Drew Oct 11 '20 at 16:07
1

You'll end up doing it the same way most programming modes do syntax highlighting: by matching regular expressions against the buffer contents. You'll want to search backwards for the beginning of the function, and then search forwards from there to find the end of it.

Using LSP is a nice idea, but the protocol doesn't deal in the actual syntax of the document; it's all done by cursor position. When you want to jump to the definition of a symbol, for example, the editor sends the current cursor position and asks the server for the cursor position of the definition.

Edit: though because you're doing this for C, you can just reuse narrow-to-defun; it will at least find the boundaries of the function for you. Doesn't work for all languages, but it would work for most.

1
  • Hmm I was worried that might be the case. I guess I was hoping I'd be able to leverage some existing implementation rather than add one more (i.e. use a function that I'm running already like which-function or one of the LSP functions). With LSP once I find my function location how would I pass that instead of symbol-at-point? – Reginald Marr Oct 10 '20 at 20:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.