public override void KeyDown (NSEvent theEvent)
{
NSRange range = new NSRange(0, 0);
string line = "";
int indentLevel = 0;
bool consumeKeystroke = false;
// Avoid processing if no Formatter has been attached
if (Formatter == null) return;
// Trap all errors
try {
// Get the code of current character
var c = theEvent.Characters [0];
var charCode = (int)theEvent.Characters [0];
// Preprocess based on character code
switch(charCode) {
case EnterKey:
// Get the tab indent level
range = Formatter.FindLineBoundries(TextStorage.Value, SelectedRange);
line = TextStorage.Value.Substring((int)range.Location, (int)range.Length);
indentLevel = CalculateIndentLevel(line);
break;
case TabKey:
// Is a range selected?
if (SelectedRange.Length > 0 ) {
// Increase tab indent over the entire selection
IndentText();
consumeKeystroke = true;
}
break;
case ShiftTabKey:
// Is a range selected?
if (SelectedRange.Length > 0 ) {
// Increase tab indent over the entire selection
OutdentText();
consumeKeystroke = true;
}
break;
default:
// Are we completing closures
if (CompleteClosures) {
if (WrapClosures && SelectedRange.Length > 0) {
// Yes, see if we are starting a closure
foreach(LanguageClosure closure in Formatter.Language.Closures) {
// Found?
if (closure.StartingCharacter == c) {
// Yes, get selected text
var location = SelectedRange.Location;
line = TextStorage.Value.Substring((int)SelectedRange.Location, (int)SelectedRange.Length);
var output = "";
output += closure.StartingCharacter;
output += line;
output += closure.EndingCharacter;
TextStorage.BeginEditing();
Replace(SelectedRange, output);
TextStorage.EndEditing();
if (SelectAfterWrap) {
SelectedRange = new NSRange(location, output.Length);
}
consumeKeystroke = true;
Formatter.HighlightSyntaxRegion(TextStorage.Value, SelectedRange);
}
}
} else {
// Yes, see if we are in a language defined closure
foreach(LanguageClosure closure in Formatter.Language.Closures) {
// Found?
if (closure.StartingCharacter == c) {
// Is this a valid location for a completion?
if (Formatter.TrailingCharacterIsWhitespaceOrTerminator(TextStorage.Value, SelectedRange)) {
// Yes, complete closure
consumeKeystroke = true;
var output = "";
output += closure.StartingCharacter;
output += closure.EndingCharacter;
TextStorage.BeginEditing();
InsertText(new NSString(output));
TextStorage.EndEditing();
SelectedRange = new NSRange(SelectedRange.Location - 1, 0);
}
}
}
}
}
break;
}
// Call base to handle event
if (!consumeKeystroke)
base.KeyDown (theEvent);
// Post process based on character code
switch(charCode) {
case EnterKey:
// Tab indent the new line to the same level
if (indentLevel >0) {
var indent = TabIndent(indentLevel);
TextStorage.BeginEditing();
InsertText(new NSString(indent));
TextStorage.EndEditing();
}
break;
}
} catch {
// Call base to process on any error
base.KeyDown (theEvent);
}
//Console.WriteLine ("Key: {0}", (int)theEvent.Characters[0]);
}