Skip to content

Slightly smarter input indentation #389

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 39 additions & 6 deletions CSharpRepl/CSharpReplPromptCallbacks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,47 @@ protected override async Task<KeyPress> TransformKeyPressAsync(string text, int
static int GetSmartIndentationLevel(string text, int caret)
{
int openBraces = 0;
var end = Math.Min(text.Length, caret);
for (int i = 0; i < end; i++)
bool inSingleLineComment = false;
bool inMultiLineComment = false;
bool inString = false;
bool inChar = false;
bool escape = false;

for (int i = 0; i < Math.Min(text.Length, caret); i++)
{
var c = text[i];
if (c == '{') ++openBraces;
if (c == '}') --openBraces;
char c = text[i];
char prev = i > 0 ? text[i - 1] : '\0';

if (inSingleLineComment)
{
if (c == '\n') inSingleLineComment = false;
}
else if (inMultiLineComment)
{
if (prev == '*' && c == '/') inMultiLineComment = false;
}
else if (inString)
{
if (!escape && c == '"') inString = false;
escape = c == '\\' && !escape;
}
else if (inChar)
{
if (!escape && c == '\'') inChar = false;
escape = c == '\\' && !escape;
}
else
{
if (prev == '/' && c == '/') inSingleLineComment = true;
else if (prev == '/' && c == '*') inMultiLineComment = true;
else if (c == '"') inString = true;
else if (c == '\'') inChar = true;
else if (c == '{') openBraces++;
else if (c == '}') openBraces--;
}
}
return openBraces;

return Math.Max(0, openBraces);
}

static KeyPress NewLineWithIndentation(int indentation) =>
Expand Down
Loading