Search code examples
delphicharcontrol-characters

What does this Delphi syntax do? "someAnsiChar := ^H;"


I am converting a really old component into Delphi 12 and have stumbled across syntax I don't recall seeing before. The code is a bit like this:

someBoolean := key in [^H, #32..#255];

I get that it's testing if key matches, or is within range, of the specified set of ANSI characters, but what exactly is ^H? Delphi seems happy to compile the line if I change H for A, B, C or 1. The line compiles under Delphi 12 and Delphi 7. I can't seem to find anything about this. It seems like a really old syntax, maybe from Pascal days. Can anyone shed some light on this please?

I've prepared this test code in Delphi 7:

procedure TForm1.Button1Click(Sender: TObject);
var
  c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15: AnsiChar;
begin
  c1 := ^A;
  c2 := ^B;
  c3 := ^C;
  c4 := ^D;
  c5 := ^E;
  c6 := ^F;
  c7 := ^G;
  c8 := ^H;
  c9 := ^Z;
  c10 := ^a;
  c11 := ^b;
  c12 := ^0;
  c13 := ^1;
  c14 := ^2;
  c15 := ^3;
  ShowMessage(
    IntToStr(Byte(c1)) + #13#10 +
    IntToStr(Byte(c2)) + #13#10 +
    IntToStr(Byte(c3)) + #13#10 +
    IntToStr(Byte(c4)) + #13#10 +
    IntToStr(Byte(c5)) + #13#10 +
    IntToStr(Byte(c6)) + #13#10 +
    IntToStr(Byte(c7)) + #13#10 +
    IntToStr(Byte(c8)) + #13#10 +
    IntToStr(Byte(c9)) + #13#10 +
    IntToStr(Byte(c10)) + #13#10 +
    IntToStr(Byte(c11)) + #13#10 +
    IntToStr(Byte(c12)) + #13#10 +
    IntToStr(Byte(c13)) + #13#10 +
    IntToStr(Byte(c14)) + #13#10 +
    IntToStr(Byte(c15)));
end;

The output is this:

1
2
3
4
5
6
7
8
26
1
2
112
113
114
115

So it looks like the characters in caps correspond to their position within the alphabet, but I can't tell what others correspond to. They don't match their corresponding values in the ASCII table.


Solution

  • The ^ represents the control key, and is a holdover from old Pascal (and before that, the ANSI terminal). The key would match Ctrl+H, which is a backspace. Essentially, the set [^H, #32..#255] includes the backspace and any ASCII character above #32 (a space).

    Some other common escape sequences in the ANSI terminal are:

    General ASCII Codes, taken from Github Gist

    Name decimal octal hex C-escape Ctrl-Key Description
    BEL 7 007 0x07 \a ^G Terminal bell
    BS 8 010 0x08 \b ^H Backspace
    HT 9 011 0x09 \t ^I Horizontal TAB
    LF 10 012 0x0A \n ^J Linefeed (newline)
    VT 11 013 0x0B \v ^K Vertical TAB
    FF 12 014 0x0C \f ^L Formfeed (also: New page NP)
    CR 13 015 0x0D \r ^M Carriage return
    ESC 27 033 0x1B \e* ^[ Escape character
    DEL 127 177 0x7F Delete character