Delphi coding hints and tips.

Keyboard Macro's in the Delphi IDE

Keyboard Macro's are the best kept sercert of the delphi IDE. A Macro is a 'recording' of a sequence of key presses within the editor which can be 'played' back as many time as required. Althought keyboard macro's are mentioned in the help documentation it does not tell you how useful they are when editing. Keyboard macro's allow you automate repeative source code editing, reducing keypresses and thus speeding up source coding tasks.

To create and use a keyboard macro:

  1. Press Ctrl+Shift+R to begin recording a macro. You will see in the editor status bar instead of 'Insert' or 'Overwrite' it now indicates a status of 'Recording'.

  2. Enter keystrokes, then press Ctrl+Shift+R to finish recording and save the macro.

  3. To play back the macro, press Ctrl+Shift+P.

Example.

Below is a piece of SQL which we wish to incuded in our source code as a string.

SELECT DISTINCT
  b.*
FROM
  bug b, bug_dist bd
WHERE
  b.bug_key = bd.bug_key AND
  b.bug_severity_code = "C"

First we cut and paste the SQL into our source code, for example here we have a function MySQL which returns a string with out SQL. The contents of the editor may look something like this:

function MySQL: String;
begin
  Result :=
SELECT DISTINCT
  b.*
FROM
  bug b, bug_dist bd
WHERE
  b.bug_key = bd.bug_key AND
  b.bug_severity_code = "C"
end;

Obviously we now have to put quotes around the SQL. Rather than do this repeativity task by hand we can use a keyboard macro.

Place the cursor in front of 'SELECT' and press the following key sequence:

Ctrl+Shift+R
Tab
Tab
'
End
'
Space
+
Home
Down
Ctrl+Shift+R
Ctrl+Shift+P
Ctrl+Shift+P
Ctrl+Shift+P
Ctrl+Shift+P
Ctrl+Shift+P
Ctrl+Shift+P 

Your source code should now look this:

function MySQL: String;
begin
  Result :=
    'SELECT DISTINCT' +
    '  b.*' +
    'FROM' +
    '  bug b, bug_dist bd' +
    'WHERE' +
    '  b.bug_key = bd.bug_key AND' +
    '  b.bug_severity_code = "C"' +
end;

All that remains now is to remove the last '+' and replace it with a ';'. As you can see here keyboard macro's saved us a lot of typing by 'recording' and 'playback' key presses.

Note: The trick in our key press sequence is the 'Down' key press. Thus when we 'playback' the key press it does its stuff and move down to the next line, ready for us to 'playback' again.