Vim [m motion with c#

Viewed 2764

Vim provides very useful motion commands to jump to next start/end of a method: ]m, ]M, [m and ]m.

These works for Java or similar structured language. (as described in :help ]m and :help 29.3)

It seems to work considering the outermost pair of curly braces as class declaration and the next level of curly braces as method declarations.

These motion commands doesn't work when there is an outer pair of curly braces around class definition, which is somewhat common on languages as C#.

I was wondering if there is some trick to make those commands (alone and prefixed with operators, e.g., y[m, V]M) work on this code:

namespace ABC.DEF
{
    class A
    {
        protected string strID;
        public string PortID { get { return strID; } set { strID = value; } }

        protected MyType x;
        public MyType X
        {
            get { return x; }
            set { x = value; if ( x != null ) func1(); }
        }


        int func1()
        {
            return 1;
        }

        int func2(int flag)
        {
            if (flag == 0)
                return flag;


            if (flag > 3)
            {
                return flag;
            }
            return 2;
        }

        int func3()
        {
            return 3;
        }
    }
}
5 Answers

Andrew Radev gave an answer which idbrii turned into a plugin.

I have modified that plugin here: https://github.com/RobertCWebb/vim-jumpmethod/

I fixed various issues and added improved mappings for [[ and ]] as well

  • Fixed: failed to stop when function heading was split over multiple lines (this happens all the time for me)
  • Fixed: stopped at multi-line if-statements when it shouldn't
  • Fixed: failed to stop at template functions, like Func()
  • Fixed: failed to stop at functions with comments containing words like "if" or "for"
  • Fixed: failed to stop at functions with comment lines between the function name and the brace
  • Fixed previous position marker not being set, ie after using [m or ]m you should be able to use '' to go back to previous line
  • Also, when searching back, I made it scroll up a little so the function name is visible, even though the cursor still lands on the '{'
  • Added mappings for [[, ]], [] and ][ which stop at class, enum and property definitions in addition to functions. Their standard behaviour in vim is often useless for C#. [m and ]m still only stop at methods and functions

Regarding the latter, I found it's more useful to stop at class definitions and properties too.

Properties in C# can contain a get and a set method, but I decided it was probably sufficient to just stop once at the definition of the property itself.

For classes, I noticed that I would jump from a method in one function to a method in another, without even realising I was in a different class. That seems dangerous to me, so it's nice to stop at the class definition too. The [[ and ]] mappings will do this.

Related