As Jeff Atwood noted, we are typists first, programmers second [1]. Fast typing and editing may not be essential to be a good programmer, but it certainly helps. I noticed that I consciously and subconsciously use various tricks to get my intent across to the computer as fast as possible.
What tricks can be used to type and edit code faster?
I'm hoping to collect a nice list here that we can all learn from, so that we can be ever so slightly more productive. One trick per answer please!
This is not about typing speed in general. There are other questions [2] about that. It's also not about general answers like "learn your editor's shortcut keys". Think of this topic as micro-optimizations for specific cases. See my own answers for examples of what I mean.
(Are you coming here from TDPE2 [3]? You want to read Toughest Developer Puzzle Ever 2 [4].)
The single most useful (and potentially obvious, but who know?) tip that must have saved me hundred of hours over my programing time:
Use whole word caret movement shortcuts (control-left arrow/control-right arrow) to rapidly go the line location you are seeking. Use them in conjunction with shift for quick selecting of a couple of words.
Corollary: use beginning of line/end of line shortcuts.
Example: let's say you have the following line of code
ClassA toto = new ClassA("A nice string", 10, -300, MAX_VALUE );
Your caret is on the keyword 'new' and you want to change -300 to -299. What is the fastest way, assuming both hands are on the keyboard?
f-1<ctrl-A>
. f-
goes to the next "-" character. 1<Ctrl-A>
increments the number under the cursor by one. That is four keystrokes. - Dave Kirby
f-<ctrl-A>
. - Dave Kirby
:qa!
... ;) - Thomas
:qa!
camp as well regarding Vim. I think that all this "Vim does this in N keystrokes" stuff is not relevant. All kinds of software does all kinds of things, e.g. with ReSharper I can safely rename a class that's referenced in 1000 files with (3 + as many edits I make) keystrokes. What does that say? It would be better to just provide advice that can be used by everyone regardless of their specific choice of IDE or editor. - Jon
-
character, then finding and typing the keys on the keyboard. In the meantime, I've used the Ctrl key at the far corner of the keyboard and the arrow keys that are in their own block, to press twice as many keys without even looking at the keyboard in a quarter of the time. /rant - DisgruntledGoat
coming from a UNIX background I believe a program should specialise in what it is good at and try not to do everything.
- That is an argument against using vim to program. Use a tool specialized for that language - don't try to hammer a nail using a swiss army knife. - BlueRaja - Danny Pflughoeft
When pasting with the mouse, work backwards through the line.
Suppose you have a line like this:
foo(x, y, z);
and you want it to look like this:
foo(bar.x, bar.y, bar.z);
If you paste the bar.
with the mouse (either middle-click on *nix, or click and Ctrl + V), it's faster to start at the back. That way, the next location where you want to paste does not move, so you can go there faster.
For all bracketed constructs -- (), [], {}, "", /**/
, etc -- type the bracketing first and then fill it in. In particular, for /**/, type this on the number pad.
This also helps avoid confusing compilation errors from forgetting the end bracket.
/* */
on the numpad... why didn't I think of that? That's exactly the kind of thing that I was hoping for :) - Thomas
Learn Vim. It is available on virtually every platform, and you can do things from the keyboard that are unimaginable in most other editors. The learning curve is steep so expect your productivity to plummet for a couple of weeks, then soar as your muscle memory learns the Vim way of doing things.
See my comment to AD's answer [1] to this question for an example.
[1] http://stackoverflow.com/questions/2797806/what-tricks-can-be-used-to-type-and-edit-code-faster/2798110#2798110Learn and get comfortable with the beginning/end-of-line and beginning/end-of-file shortcut keys.
By environment, those are:
Environment │ BOL │ EOL │ BOF │ EOF ───────────────┼──────────┼──────────┼─────────────┼───────────── Windows (all) │ Home │ End │ Ctrl+Home │ Ctrl+End Linux (all) │ Home │ End │ Ctrl+Home │ Ctrl+End Mac (all) │ ⌘← │ ⌘→ │ ⌘↑ │ ⌘↓ ───────────────┼──────────┼──────────┼─────────────┼───────────── Emacs │ Ctrl+A │ Ctrl+E │ Meta+< │ Meta+> Vim │ 0 │ $ │ gg │ G
You can quickly highlight an entire line of code by pressing the EOL key, then holding ⇧ and pressing the BOL key (that's End, Shift+Home on Windows) and then use the up or down arrows to highlight multiple lines.
Keep line endings in mind while cutting and pasting.
Treat newlines as normal characters when cutting and pasting. When cutting and pasting one or more full lines, include the final newline, so you don't have to remove it in one place and re-add it in another.
dd
to take out entire lines, including the newline. Or you can use V
to enter "Visual Line" mode which lets you select only entire lines. - R. Martinho Fernandes
Shift+V
in vim goes to visual line mode. Although for single lines, you'd normally use dd
or yy
to cut or copy the line, respectively. (Yay, I'm learning vim!) - Thomas
Using IntelliSense [1] or the equivalent always helps speed up coding.
[1] http://en.wikipedia.org/wiki/IntelliSenseWhen one hand is on the mouse, use Enter on the numpad.
When my left hand is on the left side of the keyboard, and my right hand is on the mouse, I sometimes hit numpad Enter with the thumb of my right hand. This only works if you use the mouse with your right hand and have a relatively low keyboard (mine's a Logitech UltraX).
Use Das Keyboard Ultimate [1].
It will help you look more at your screen and less at your keyboard.
[1] http://www.daskeyboard.com/I spend significantly more time tracing, testing, debugging, reading, and thinking about my code than I spend typing it. I could increase my typing speed 100x and don't think I would get a significant boost in productivity.
++
operator. - mikerobi
The single piece of software that saves me a lot of time is the multi clipboard manager (like ClipX [1]). It allows you to copy several parts of a source file at once without switching back and forth between files, and furthermore it keeps the clipboard history so, if you accidentally overwrote the latest clipboard entry, you can easily recover it.
[1] http://en.wikipedia.org/wiki/ClipXLearn to use regular expressions in your editor/IDE.
For example, earlier today, I was annoyed by a file that had excess whitespace at the end of the majority of its lines. Replace \s+$
with an empty string took care of it.
When pasting with the keyboard, work forwards through the line.
Suppose you have a line like this:
foo(x, y, z);
and you want it to look like this:
foo(bar.x, bar.y, bar.z);
If you paste the bar.
with the keyboard, then navigate with the arrow keys to
the next location, it's faster to start at the front. For example:
foo(bar.x, y, z);
foo(bar.x, bar.y, z); // and so forth
Otherwise, you have the newly pasted bar.
to navigate over..
Block Selection
Alt+Shift+Up
Alt+Shift+Down
Alt+Shift+Left
Alt+Shift+Right
This has saved me tons of time when making repetitive changes in long blocks of code (providing it's properly indented). It works with Visual Studio as well as with Notepad++.
Image source and more complete explanation [1].
[1] http://visualstudiotips.wordpress.com/2006/04/17/tip-select-block-text/My favourite is the shortcut to jump to the closing curly brace: Ctrl + ] in Visual Studio [1] and Ctrl + Shift + P in Eclipse [2]. I use this a lot.
[1] http://en.wikipedia.org/wiki/Microsoft_Visual_Studio]}
in Vim. - slacker
Switching to overwrite(replace) mode by pressing Insert button can speed things up sometimes quite a bit when you need to make replacements without changing a word length (usually in a vertical block of text). For example if you need to increase indexes by 1 here:
array[0] = ...
array[1] = ...
array[2] = ...
array[3] = ...
Switching to overwrite mode allows you to navigate to required position in every line by using down and left arrow keys, which is much faster than down and backspace as they are far apart. And if your editor remembers cursor position, then all you need is use a down key after each replacement.
4 Ctrl+A j
in vim, or something like that... :) - Thomas
Set up keyboard macros for your commonly used patterns.
In Visual Studio I use Ctrl + ALT as a base.
Ctrl + ALT + i - if () {} else {}
Ctrl + ALT + f - for (;;) {}
I omitted the line breaks above.
for
then press TAB
twice. - Callum Rogers
if () {} else {}
around whatever code goes in there. Of course, that might just be me. - Maulrus
Avoid mouse, learn shortcuts. What can be done with mouse usually can be done ten times faster using keyboard if you know your shortcuts.
Also think more and type less, and use an advanced editor that you know well.
Two exemples of precious features:
Navigate backward and forward between the places in code that you're editing.
A lot of time can be wasted scrolling and mouse-wheeling between several physically distant areas in the same project. In Visual Studio, hit Ctrl + - and you will jump back to the last place in the code that you made an edit. Ctrl + Shift + - will jump you forward again.
For bonus points, bind these shortcuts to the back and forward buttons on your mouse. Awesome.
Use incremental search and backward incremental search for navigation. It's like teleporting instead of walking - usually Ctrl + S or Ctrl + R (Emacs bindings) or Ctrl + I in Visual Studio [1] plus two to three keystrokes get you anywhere on the screen. Well, unless you're editing ASCII art or binary memory dumps :)
[1] http://en.wikipedia.org/wiki/Microsoft_Visual_StudioThe best musicians still practice, and the best typists would in theory, still practice.
Part of building speed and accuracy is simply "slow down and perfect it", which is amoung the biggest hurdle for music students to overcome (according to well know famous musicians/teachers, such as Andreas Segovia). In theory the same principles apply. It should be easier to perfect than an instrument, because typing is not a performance art (unless you are presenting). So when you make any mistake, you should stop and think and feel your whole body. The muscle tension in the fingers, the hands, spinal column position and curvature, etc.... Then focus on the tension and correct, by relaxing and slowly moving through the motions until it's smooth and you are totally relaxed except for the absolute minimal muscle tension required to move the finger to where you want it to go. This builds muscle memory, and you have to unlearn all the bad habits, by slowing down, and eliminating all wasted motion.
Learn to use either hand to type Shift, Meta/Alt, and Ctrl.
(One reason I don't use a Mac is that the Mac requires four modifier keys, and I can't find a reliable keyboard that has all four on each side.)
It's a shame that the DVORAK keyboard layout [1] hasn't really caught on.
QWERTY was allegedly designed with the intention of capping typing speeds so as to prevent mechanical breakage of the good ol' typewriters.
[1] http://en.wikipedia.org/wiki/Dvorak_Simplified_KeyboardIf Visual Studio [1] is in context, then there are several third-party plugin/tools which enhance typing efficiency of developers.
One such, I use is CodeRush [2]. There are even videos available for the same.
[1] http://en.wikipedia.org/wiki/Microsoft_Visual_StudioEclipse (and other IDE's I'm sure) has templates (menu Java -> Editor -> Template) where you can add you own pattern blocks. For example
if (${name:var} == null) {
${name} = new ${type}(${arguments});
${cursor}
}
return ${name};
gives you a nice fill-in-the-blank block of code that can be tab\shift+tab navigated until you hit eneter (then it's just regular text).
Also, Ctrl + Space brings up autocomplete.
if([NAME] instanceof [TYPE]) { [TYPE] [NAME]_ = ([TYPE])[NAME]; }
into your editor. Where the [] are linked, replaceable text fields that can be navigated with tab (until you hit enter). - KitsuneYMG
Remember that in Visual Studio if you copy or cut with no text selected, it will copy or cut the whole line. Then when you paste back in with no text selected, the line will be inserted above the line the cursor is on.
This has saved me a lot of time, especially when reordering a few lines. It makes dealing with leading or trailing empty lines a lot easier as well.
If you have the fourth and fifth mouse programmable buttons (and depending on programming software), set macros to your mouse buttons:
This could save a lot of time. Think WoW [1], except really useful.
[1] http://en.wikipedia.org/wiki/World_of_WarcraftBuy and learn to use a Kinesis contoured keyboard [1]:
I bought my first one in 1995 and I own five of them. To learn it, you are best off using a typing-tutor program, but once you've learned you can switch back and forth easily.
[1] http://en.wikipedia.org/wiki/Kinesis_%28keyboard%29Zen Coding [1] is awesome. It's available for multiple IDEs, and it's great if you program HTML a lot, like me.
Get it here. [2]
It's also useful to press Ctrl + Space when using some IDEs, which will give you function parameter hints, etc.
[1] http://en.wikipedia.org/wiki/Zen_CodingEasy Line Copy: Move the cursor to a line and press Ctrl + C WITHOUT selecting the text of line.
Easy Line Cut/Delete: Move the cursor to a line and press Ctrl + X WITHOUT selecting the text of line.
Easy Property Creation: Type prop and press tab twice.
Depending on you IDE, you might have custom keyboard templates. which I find very productive.
For example, Delphi has live [1] templates [2] and Visual Studio has code snippets [3]. Both also have third party products that add even more functionality, such as Castalia [4], ModelMaker Code Explorer [5] for Delphi and CodeRush [6] (outstanding!) for Visual Studio. The only downside to these third party tools is trying to use a copy of the IDE that doesn't have them installed.
[1] http://delphi.wikia.com/wiki/Delphi_Live_TemplatesI use Emacs for my coding and there are couple of things that work for me.
If you use Emacs, do the tutorial (C-h t
) all the way to the end.
If you use another editor, do what it takes to use the "fast navigation commands".
Mac only: Use an editor that supports the native Cocoa text input system. Learn, modify and enhance the key bindings [1]. Remap the caps lock key to behave as ctrl.
All of this together amounts to a very comfortable way of navigating with the cursor sans arrow keys. By default, OS X implements a very minimal subset of Emacs commands. If you add in the word-centric commands (optionf moves one whole word forward, etc), you can reduce the number of trips to the mouse by quite a bit.
You can even implement complete and complicated snippets through the key bindings. For example, I have one like this:
/* This command will make Ctrl-< turn the previous word
* into an HTML/XML opening and closing tag pair. */
"^<" = ( "setMark:",
"moveWordBackward:",
"deleteToMark:",
"insertText:", "<",
"yank:",
"insertText:", ">",
"setMark:",
"insertText:", "</",
"yank:",
"insertText:", ">",
"swapWithMark:");
[1] http://www.hcs.harvard.edu/~jrus/Site/Cocoa%20Text%20System.htmlOther than that..... staff ? :)
[1] http://en.wikipedia.org/wiki/E_Text_EditorOn an English keyboard it may matter less, because programming languages has been invented using English keyboards. International keyboards have a different set or readily available symbols, usually different from the English ones, so many common symbols used in programming are hard to type on those keyboards.
For instance, { on standard Italian keyboard requires 1 key + 2 modifiers.
You will use the numbers much less than your most used symbols, so you should remap them to shift and use most used symbols to default.
Update:
Edit the keys using Ukelele [1].
xmodmap -pke >current.xmodmap
.xinitrc
: xmodmap current.xmodmap
Disclaimer: I might not remember correctly, and there might be visual editors I'm not aware of.
I'm sure it can be done, or at least it could be done a few years ago. I never tried, but you can figure it out.
[1] http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&item_id=ukeleleEclipse has a shortcut for looping over arrays and other containers. Type "fore" (short for "foreach") directly after an array declaration, and you get:
int[] myArray = new int[7];
for (int i : myArray) {
}
For other kinds of containers, it will generate an appropriately typed loop:
List<Integer> list;
for (Integer integer : list) {
}
But often I want to loop over a container that was declared elsewhere. I lose the benefit of automatic typing. So I create a variable, assign the container to it, use the shortcut, and immediately inline the variable.
x=l[ctrl-space][arrow keys as needed][enter];
produces x=list;
Quickfix (command-1) gives x the requisite type: List<Integer> x=list;
for[ctrl-space][enter]
produces
for (Integer integer : x) {
}
and permits me to tab directly to the x
, where I type command-option-i to inline, which deletes the List<Integer> x=list;
line, and leaves me with exactly what I wanted:
for (Integer integer : list) {
}
It sounds like a lot of work, but honestly it saves me time - and errors.
When entering large blocks of numbers for, e.g., initialization of arrays, don't use the numeric keypad, but instead move both hands to the number keys at the top of the keyboard. I was taught to do this when I worked in a data entry department at a bank in college, and I find it faster and more accurate.
Search for the word under cursor to uncover typos
A great feature in itself, but you can also use it to check for typos. For example, * and # in Vim [1] and in Eclipse [2] wait for a couple of seconds when the cursor is over a symbol.
[1] http://en.wikipedia.org/wiki/Vim_%28text_editor%29For me the most valuable has been AutoHotkey [1].
You can reprogram your whole keyboard, as I did since I use AZERTY
.. no more Alt + { to get "{", just type {
, same with (
[
#
@
, etc. Who needs ùµ$^² as default keys anyway ?? WTF?? :-)
You can program your own shortcuts, for example ALT-² inserts a new method at my machine
You can program hotstrings, like if you type hotfunc, it will type a whole function declaration
Program hotkeys to launch EXE files, create files, etc.
You can use it in every application, including Visual Studio, Notepad, or your emails
You can do anything you want, since you can program it yourself
It's free
In Notepad++ [1] there are two keyboard shortcuts that are perfect for programming:
Teach yourself to use the mouse with your less-good hand. Filling in dialogues goes a lot faster that way, particularly if the TAB navigation hasn't been programmed correctly.
I think you have to try and use as many macros as possible. Editors like Emacs [1] can be really helpful, but most text editors now support a bunch of macros that can keep your hands on the keyboard and free it from the evil mouse...
[1] http://en.wikipedia.org/wiki/EmacsGet an IDE or editor that does code completion, and learn to use it well with the keyboard shortcuts. Most decent ones will complete variable names. Some, for example
Xcode
[1], will fill in things like if
statements and switch
blocks for you.
Then, you just press a keyboard shortcut (command-/ in Xcode) to move to the next spot you need to fill in. This does two things: it types out the stuff for you, and it keeps you from having to remember the exact syntax or making a mistake in it (you will never forget to break;
a switch case if you do this).
Also, it doesn't work so well for programming, but for regular typing, use an editor that has good auto-completetion. The auto-completetion in Snow Leopard [2] has probably increased my effective typing speed by 150%. Maybe there is an awesome IDE out there that does this for comments.
[1] http://en.wikipedia.org/wiki/XcodeLearn an optimized keyboard layout like Neo [1].
The time it takes to learn pays off shortly after. All programming special characters are easily typeable without moving hands and fingers very far. Just press caps + some-key (caps + n = (
– n being j on a QWERT[YZ] keyboard :D confusing?). A numberblock and a cursor block including Home/End, PgUp/PgDn are integrated into the mainfield of the keyboard.
/**/
is on the homerow. {}()-*:/@?
also on the homerow.
Move hands less, type more.
[1] http://neo-layout.org/I'm all in favour of knowing Vim [1], because of its portability (which is the reason I learned it back in 1993). I still use it sometimes even though I mostly work in Visual Studio, having used various flavours of it since, well, 1993 (Visual C++ 1.0 FWIW).
However more generally, I would say my top tips are:
Find some site that can help you train your way of type. I don't know any other, but would be nice to see more of this on comments. This is an example to start [1]
[1] http://speedtest.10-fast-fingers.com/I find I can type Pascal faster than C/C++ because it contains far less obscure punctuation symbols - therefore requiring far less two-hand coordinated movements to type them.
On many non-US keyboard layouts you need three-key combinations to generate the various brackets {[]}
The keyboard is optimized (yes, optimized to avoid jamming typewriters by putting alternative characters on alternate hands) for text input, not complicated symbols.
If you can't use Pascal, Cobol or Python or another language with this word-based style you might be able to adopt something similar [1] as early Unix apps did.
[1] http://www.bsdlover.cn/study/UnixTree/V7/usr/src/cmd/sh/mac.h.htmlThis is Visual Studio-specific but it also works with Notepad++. Basically it's possible to use the keyboard to scroll the current window leaving the cursor in the same place by using Ctrl+Up or Ctrl+Down.
It's maybe not that useful however as once the cursor reaches the top or the bottom of the screen it will stay there. I use it periodically if I need to check something that I know is just beyond the current window boundary so I can scroll the window up or down without having the cursor move off the current line.
Learn to use incremental search for navigation.
Most modern text editors provide some sort of incremental search capability, for instance in Eclipse this is bound to Ctrl+J by default while in Emacs it is bound to Ctrl+S and in Visual Studio it is Ctrl+I. You can use this and its reverse version to jump to code at or near where you want to place your cursor rather than mousing or using simple arrow controls.
Challenge your coworker(s) to a contest. Pick some action you do often and give kudos, prizes, etc. to the person who comes up with the fewest keystrokes/button pushes to accomplish it. Examples:
In some versions of vi zz
will close the file and save it. This is one keystroke shorter than ':x' then the enter key.
Or:
In Windows you can copy a file's name in Windows Explorer by right clicking on the file, hitting rename, then hitting Ctrl + c to copy the highlighted file name from the rename input box.
drelihan mentioned the "go to matching brace" shortcuts in Visual Studio and Eclipse. In TextPad [1], it's Ctrl + M, or Ctrl + Shift + M to select the entire block.
[1] http://en.wikipedia.org/wiki/TextPadLearn or create a shortcut to take the selected text and perform a search for it. On most Mac editors, this is ⌘E ⌘G. This allows you to do a quick “find other occurrences of this symbol” to navigate around the relevant parts of your file.
In Vim, ctrl-{n,p} and Eclipse I think the default is meta-/.
It's powerful because it doesn't care if you're writing documentation (I cringe every time I see someone typing out a comment which contains, say, … call ISomeEnterpriseBusnessClass.fozzleTheWidgetWithTheWazzle…
), writing inside strings or writing code.
In Visual Studio (plus EnterpriseManager's editor), comment and uncomment using Ctrl + K + C and Ctrl + K + U. Nice thing, it works well with different languages.
In Visual Studio 2008, map a good pair of keystrokes to the Edit.GoToFindResults1NextLocation
and Edit.GoToFindResults1PrevLocation
actions. Saves a lot of time when changing something across multiple files in cases where 'Replace in files' is not an option.
(Ctrl + ;, Ctrl + N and Ctrl + ;, Ctrl + P are decent enough setting here)
Type and edit code faster? Master your tools! Whichever tool you are using, learn to use it at its fullest. The first thing is the editor, Vim [1] is amazing, Emacs [2] too. At least it is very important that you can expand its functionality with macros.
Also learn tools for browsing code like global and cscope [3]. If you cannot find what you want fast, you cannot edit fast.
Being more generic, learn some code spelunking [4] to move faster even when the code is totally alien to you.
[1] http://en.wikipedia.org/wiki/Vim_%28text_editor%29I switch back and forth between vi [1] and Visual Studio [2] a zillion times a day with the predictable result that I type vi commands at Visual Studio; and vice-versa.
This very helpful thread inspires me to find/make some vi keyboard macros that also work for Visual Studio. That would save me tons of time.
[1] http://en.wikipedia.org/wiki/ViAbuse your language's preprocessor.
#define J template<typename T>
#define LOOP(a, b) for(int i = 0; i < a; i++) { b; }
Saves so much time!
I assume growing an extra finger is out of the question?
Seriously though, I recommend extensive customization of the function keys on your keyboard and mouse.
Learn the hotkeys and shortcuts, all of them -- even the ones you're sure you'll never need to use...
You will someday, and you'll be prepared.