How we do Indenting

One of the more interesting things about writing an IDE from scratch because you end up at points where you can see how other people did things and making perhaps the same decisions as them, perhaps different ones.  For example I’m just looking at indentation and bracketing in the text editor for Friendlier.

When you type in a closing brace in C++ or Java for example I would expect the formatting to work out that we’ve stepped down a level of indentation and adjust the text accordingly.  Hence you are expecting to see a closing brace and then you can write it out with a command which might look a bit like this:

insertTextCommand(fileBuffer, someText, positionOfTheText)

 And when the someText happens to be ‘}’ what can we do?  Well we can change insertTextCommand to do something clever with the FileBuffer at the position of the text – or we can write another command that will do the formatting of the closing brace afterwards.  Of course it’s useful to have a reformatting command anyway so shall we just have a generic command for reformatting a file?  Probably not as formatting is target language specific (what may be a closing brace in one language isn’t the same as one in another) so perhaps we need a generic command which can be specialised per language we’re going to support somehow?

In Friendlier we already have a generic SyntaxManager class and specialise this to (for example) CppSyntaxManager.  This handles text indentation, keyword highlighting, text completion and other functions already.  We can pass this into our reformat command and it can work out what kind of text we’re reformatting:

reformatTextCommand(fileBuffer, syntaxManager, startPosition, endPosition)

So I can then run this command right after the insertTextCommand and it will reformat the text for me and best of all I leave my working insertTextCommand unsullied.  Additionally if I don’t like the formatting that’s been automatically applied I can undo just that one command.  Oddly enough this is exactly how Visual Studio appears to work too.  I wonder if they code this in a similar way?

Leave a Comment