Keyboard macros

Keyboard macros

  • Comments 8

I'm sure you've all watched someone who doesn't know keyboard shortcuts struggling to edit a document. It can be frustrating how long even simple things take, and hard not to start shouting advice: ctrl+shift+right, ctrl+x, end, ctrl+v!

But I occasionally see even master programmers, the kind with indubitable nerd maestro credentials, doing laborious manual editing tasks. Often this is because they don't know about or think to use a keyboard macro.

Key macros are fundamentally simple. You tell the editor to start recording, then press some keys, after which it can play back this sequence of keystrokes as many times as you like. This may not sound useful for anything more complicated than typing the same text many times in a row (for which purpose copy & paste would be simpler), but when combined with the clipboard, it opens up a wonderful new world of editor automation.

With a bit of practice macros can become so instinctive that any time you see a repetitive task coming up you just hit the record button, do the task once, then play back however many times are required, all without breaking your regular code editing stride.

Let's say we have this enum:

    enum Animal 
    { 
        Cat, 
        Dog, 
        Camel, 
        Llama, 
        Shrew, 
    } 

And we want to create a helper function like so:

    string GetLocalizedAnimalName(Animal animal) 
    { 
        switch (animal) 
        { 
            case Animal.Cat: 
                return ResourceManager.GetLocalizedString("Animal_Cat");

            // likewise for each enum value
        } 
    }

We could copy & paste this first case statement, then go back and edit each enum name and string constant, but it would be faster and less error prone to use a key macro. First we copy the list of values from our enum definition, pasting them into the middle of our function:

    string GetLocalizedAnimalName(Animal animal) 
    { 
        switch (animal) 
        { 
        Cat, 
        Dog, 
        Camel, 
        Llama, 
        Shrew, 
        } 
    }

Now the magic part.  In Visual Studio, place the cursor on the fifth line (the one containing "Cat") and type:

ctrl+shift+R   (starts recording)
home
ctrl+shift+right arrow   (selects the indentation whitespace)
delete
end
backspace   (deletes the trailing comma, so the line now consists of the single string "Cat")
shift+home   (selects the line)
ctrl+x
tab tab tab tab
Type this string:  case Animal.
ctrl+v
colon
enter
Type this string:  return ResourceManager.GetLocalizedString("Animal_
ctrl+v
Type this string:  ");
enter
home
down arrow
ctrl+shift+r   (stop recording)
ctrl+shift+p   (play back macro)
ctrl+shift+p
ctrl+shift+p
ctrl+shift+p

 

Exercise for the reader: if Visual Studio did not have a built in "encapsulate field" refactoring function, how would you turn this code:

    public int Elf;
    public string Name;
    protected float LivesOfTheCat;

into a series of properties of the form:

    public int Elf
    {
        get { return elf; }
        set { elf = value; }
    }

    int elf;

?

  • This is a bit of a tease for VS Express users as the macro recorder is only available in the bigger VS editions.

    When there's a really arduous task consisting of many lines, I sometimes break out Notepad++ which has a macro recorder that almost perfectly imitates the one in Visual Studio. Launching Notepad++, copy-pasting the code and navigating to where I was in Notepad++ is not as easy as pressing Ctrl+Shift+R, of course, so this only becomes interesting if there's a least a screenful of code that needs to be transformed somehow ;-)

  • VS Express really doesn't include keyboard macros? Dang! That alone is enough reason I would want to invest in the full version :-)

    I mostly actually write code in FED (www.talula.demon.co.uk/fed) which of course fully supports macros.

  • Once you do that, you'll start moving up the the "Macros IDE" and creating some really interesting macros. I use that all the time: why make a full program when I can open the file in Visual Studio and write a VBA macro to parse it? It also works for some complex code replacements, especially since I can use regular expressions, store previous work, etc.

    Although I understand the point of this article and that this is just an example and such, I think that one should consider that something like this is unnecessary code.

    One could simply write:

       string GetLocalizedAnimalName(Animal animal)

       {  

           if (!Enum.IsDefined(typeof(Animal), animal)) throw new ArgumentException(/*args here*/); //Check for invalid values. Or you could just let GetLocalizedString throw "could not find resource Animal_8".

           return ResourceManager.GetLocalizedString("Animal_" + animal.ToString());

       }

    No massive switch statement to create via automation. Plus if I add to the enum I won't have to add to the switch statement. One does need to be aware of the costs associated with this compared to the switch statement, though. More garbage, string concatenation, etc, compared to the switch simply going off a number and having the string resources already built.

    Again, I know it was for illustrative purposes, I just wanted to illustrate a different way.

  • Shawn, you're a legend! I had been starting to feel that I was the ONLY person to LOVE Keyboard macros??? (have been using them ever since ye olde Delphi 3 days)

    They're awesome - I find uses for them most days. Plus you can edit their source after and save them as a permanent Macro, bind a shortcut key to it and voila!

    To date I've never managed to convince any colleagues to appreciate them too. I'm no salesman.

  • I use a Logitech G15 keyboard, which was a godsend for programs like VS Express that didn't offer complex forms of key-press macros.

    Very handy keyboard, can hit record, then the button to record it to, do all the keystrokes to perform an action, then record again to store it.

    So my solution to your last question is: Highlight Field -> Macro Bank 3 (M3 button) -> Macro Button 3 (G3 button). This is an action that does: Ctrl+C, types out the property filling in Ctrl+V for the backing field, G1 = protected, G2 = protected internal, G3 = public.

  • Awwww how i love Macros. I use OpenVMS for my day job, so the editor withim VMS (TPU) has an awesome command LEARN, which does exactly the name thing.

  • I use AUTOHOTKEY, and can highly recommend it!

    On a swedish keyboard the {} are really horribly placed, with my macro I work twice as fast.

  • Hi Sean,

    Just found myself having to type a bunch of repetitive code to satisfy good old code-analysis rules. Remembered this post and made macro, now the particular task (validating constructor arguments) is a simple keyboard chord away. Excellent tip.

Page 1 of 1 (8 items)
Leave a Comment
  • Please add 8 and 7 and type the answer here:
  • Post