1

I have a little class/function detector in my .vimrc displaying, in my statusline, the python class/function my cursor currently is inside of. I am currently trying to adapt it for C++ source files, and am running into a pretty simple (?) regex (?) problem.

My function essentially works as follows:

  1. find the line number of the previous match of ::, but ignore std or cout:
let prev_class_line_number = search('\(std\)\@<!::\(cout\)\@!', 'bncW')
  1. From that line, return the \word before :::
let classname = matchstring(getline(prev_class_line_number), '\(\w\+\)::')

For example, within the following code block:

void MyClass::setSomething(int input) {
   // ...
}

my function returns "MyClass" (yay!).

I however run into issues with this type of code:

std::vector<int> MyClass::doSomethingElse(){
   // ...
}

where my function returns std instead of MyClass.

I spent a good amount of time getting my line-number-detection regexp to work (specifically, to not match std:: or ::cout), but I can't figure out how to get my second regexp to return 'MyClass'.

This looks like an incredibly simple problem and I'm sure I've been missing something. I searched into \zs/\ze, negative/positive lookahead/lookbehind, matchlist, but I haven't figured the right combination yet.

How do I extract the first word before a :: instance who is not std?

tl;dr: given the line std::foo bar::baz(), how can I return bar but not std?

1 Answer 1

1

The perfect solution is probably difficult to find in case of template class but for "simple" case maybe:

^\(\S\+\s\+\)\?\(\w\+\)::\(\~\?\w\+\)\ze(

The first bit: ^\(\S\+\s+\)? match the return type if any (assuming it doesn't contain a space. For constructor and destructor you may have no return type and that is why we make it optional (\?)

The second bit: \(\w\+\) match the class name.

The third bit: ::\(\~\?\w\+\)\ze( match the method name.

The \ze( force the expression to match till the first parenthesis.

3
  • 1
    Sorry my first version lack the \ze( that forces the expression to search the parenthesis and makes that you can match the return type as the first word \S\+ (for "simple" case) Oct 21, 2022 at 19:19
  • Oooooh but that's even better if I use that with matchlist because I get in ONE SINGLE regexp both the class and function !? Thanks !
    – Feffe
    Oct 21, 2022 at 19:25
  • You are Welcome :-). If the solution fit the need don't forget to validate it ;-) Oct 21, 2022 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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