2

Is it possible to print the function or class name in which a keyword occurs when using ack or ag? This is something I have highly desired for quite some time.

I think it would be quite tricky, as different programming languages have different ways of enclosing functions/classes.

Note that my goal right is for searching through C source code, however I would prefer a generic solution which covers more languages/syntax.

shivams
  • 923
  • 12
  • 27
  • 3
    A tool which does not know the underlying language grammar would not be able to do this, clearly ack/ag can't do this inherently – Inian Jun 06 '19 at 11:03
  • @Inian Are there any alternatives to `ack`/`ag` which have the grammar knowledge? – shivams Jun 06 '19 at 11:08
  • 1
    If `git -L` can do it as discussed [here](https://stackoverflow.com/questions/4781405/git-how-do-i-view-the-change-history-of-a-method-function) why can't ack? – mmigdol Jun 30 '20 at 18:11
  • 1
    @mmigdol Wow. That's amazing. Git continues to amaze me! You may want to mention this as an answer by explaining how this would solve our problem. – shivams Jul 01 '20 at 13:53

3 Answers3

4

Author of ack here. No, I don't know of any greplike tool that understands anything about the text files that it's searching. It's something that people ask for all the time, but I've never even thought about implementing it.

You said "I think it would be quite tricky, as different programming languages have different ways of enclosing functions/classes." You're exactly right. Also, consider things like comments

/* void foo() */

and literal strings

printf( "void foo()" );

that would cause problems for any search tool. Neither of those instances of the string void foo() is actually a function declaration.

Check out the More Tools page on beyondgrep.com. Something like cscope might help you.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
2

As commented by @Inian, it would be difficult to get a robust solution using ack, ag and grep as they are not aware of the grammar of the languages.

However, for my case of looking inside C source code files, I used ack with an OR condition to include lines which are starting with the function definitions. In my case, all my functions were either returning int or nothing. Hence, the following code printed out function definition lines alongwith the lines containing the KEYWORD:

ack 'KEYWORD|^void|^int'
shivams
  • 923
  • 12
  • 27
2

Although none of the programs you listed currently have this functionality, Git uses language-based regexps to implement git grep -L (search within a function name). This blog post describes how it works. The current list of regexps are in the git source tree here, and can be extended as described in the blog above.

Also, ctags provides a universal way to enumerate tags from files of multiple languages, but I haven't (yet) found a way to integrate this output with git grep -L yet.

mmigdol
  • 2,023
  • 1
  • 18
  • 20