Formats R code based on tokenization
Esempio n. 1
0
        public void Formatter_StatementTest01() {
            RFormatter f = new RFormatter();
            string actual = f.Format("x<-2");
            string expected =
@"x <- 2";
            actual.Should().Be(expected);
        }
Esempio n. 2
0
        public void FormatRandom01() {
            RFormatter f = new RFormatter();
            string original = "a   b 1.  2 Inf\tNULL";

            string actual = f.Format(original);

            actual.Should().Be(@"a b 1. 2 Inf NULL");
        }
Esempio n. 3
0
        public void ConditionalTest04(string original, string expected) {
            RFormatOptions options = new RFormatOptions();
            options.BracesOnNewLine = true;

            RFormatter f = new RFormatter(options);
            string actual = f.Format(original);
            actual.Should().Be(expected);
        }
        public void FormatConditionalTest01() {
            RFormatter f = new RFormatter();
            string actual = f.Format("if(true){if(false){}}");
            string expected =
@"if (true) {
  if (false) { }
}";
            actual.Should().Be(expected);
        }
Esempio n. 5
0
 public void SimpleScopesTest01() {
     RFormatter f = new RFormatter();
     string actual = f.Format("{\n{}}");
     string expected =
     "{\n" +
     "  { }\n" +
     "}";
     actual.Should().Be(expected);
 }
Esempio n. 6
0
        public void ConditionalTest05() {
            RFormatOptions options = new RFormatOptions();
            options.BracesOnNewLine = true;

            RFormatter f = new RFormatter(options);
            string actual = f.Format("if(TRUE) { 1 } else if(FALSE) {2} else {3} x<-1");
            string expected = "if (TRUE) { 1 } else if (FALSE) { 2 } else { 3 }\nx <- 1";
            actual.Should().Be(expected);
        }
Esempio n. 7
0
        public override CommandResult Invoke(Guid group, int id, object inputArg, ref object outputArg) {
            string originalText = TargetBuffer.CurrentSnapshot.GetText();
            string formattedText = string.Empty;
            var formatter = new RFormatter(REditorSettings.FormatOptions);

            try {
                formattedText = formatter.Format(originalText);
            } catch (Exception ex) {
                Debug.Assert(false, "Formatter exception: ", ex.Message);
            }

            if (!string.IsNullOrEmpty(formattedText) && !string.Equals(formattedText, originalText, StringComparison.Ordinal)) {
                var selectionTracker = new RSelectionTracker(TextView, TargetBuffer, new TextRange(0, TargetBuffer.CurrentSnapshot.Length));
                selectionTracker.StartTracking(automaticTracking: false);

                try {
                    using (var massiveChange = new MassiveChange(TextView, TargetBuffer, EditorShell, Resources.FormatDocument)) {
                        IREditorDocument document = REditorDocument.TryFromTextBuffer(TargetBuffer);
                        if (document != null) {
                            document.EditorTree.Invalidate();
                        }

                        var caretPosition = TextView.Caret.Position.BufferPosition;
                        var viewPortLeft = TextView.ViewportLeft;

                        RTokenizer tokenizer = new RTokenizer();
                        string oldText = TargetBuffer.CurrentSnapshot.GetText();
                        IReadOnlyTextRangeCollection<RToken> oldTokens = tokenizer.Tokenize(oldText);
                        IReadOnlyTextRangeCollection<RToken> newTokens = tokenizer.Tokenize(formattedText);

#if DEBUG
                        //if (oldTokens.Count != newTokens.Count) {
                        //    for (int i = 0; i < Math.Min(oldTokens.Count, newTokens.Count); i++) {
                        //        if (oldTokens[i].TokenType != newTokens[i].TokenType) {
                        //            Debug.Assert(false, Invariant($"Token type difference at {i}"));
                        //            break;
                        //        } else if (oldTokens[i].Length != newTokens[i].Length) {
                        //            Debug.Assert(false, Invariant($"token length difference at {i}"));
                        //            break;
                        //        }
                        //    }
                        //}
#endif
                        IncrementalTextChangeApplication.ApplyChangeByTokens(
                            TargetBuffer,
                            new TextStream(oldText), new TextStream(formattedText),
                            oldTokens, newTokens,
                            TextRange.FromBounds(0, oldText.Length),
                            Resources.FormatDocument, selectionTracker, EditorShell);
                    }
                } finally {
                    selectionTracker.EndTracking();
                }
                return new CommandResult(CommandStatus.Supported, 0);
            }
            return CommandResult.NotSupported;
        }
        public void Formatter_FormatFunctionInlineScope02() {
            RFormatter f = new RFormatter();
            string actual = f.Format("x <- func({return(b)})");
            string expected =
@"x <- func({
  return(b)
})";
            actual.Should().Be(expected);
        }
        public void Formatter_FormatFunction() {
            RFormatter f = new RFormatter();
            string actual = f.Format("function(a,b) {return(a+b)}");
            string expected =
@"function(a, b) {
  return(a + b)
}";
            actual.Should().Be(expected);
        }
Esempio n. 10
0
        public void Formatter_FormatSimpleScopesTest01() {
            RFormatter f = new RFormatter();
            string actual = f.Format("{{}}");
            string expected =
@"{
  { }
}";
            actual.Should().Be(expected);
        }
        public void FormatConditionalTest02() {
            RFormatter f = new RFormatter();
            string actual = f.Format("if(a == a+((b+c)/x)){if(func(a,b, c+2, x=2, ...)){}}");
            string expected =
@"if (a == a + ((b + c) / x)) {
  if (func(a, b, c + 2, x = 2, ...)) { }
}";
            actual.Should().Be(expected);
        }
Esempio n. 12
0
        public void ConditionalTest03(string original, string expected) {
            RFormatOptions options = new RFormatOptions();
            options.BracesOnNewLine = true;
            options.IndentSize = 2;
            options.IndentType = IndentType.Tabs;
            options.TabSize = 2;

            RFormatter f = new RFormatter(options);
            string actual = f.Format(original);
            actual.Should().Be(expected);
        }
Esempio n. 13
0
        public void FormatFunctionAlignArguments() {
            RFormatOptions options = new RFormatOptions();
            options.IndentType = IndentType.Tabs;
            options.TabSize = 2;

            RFormatter f = new RFormatter(options);
            string original = "x <- function (x,  \n intercept=TRUE, tolerance =1e-07, \n    yname = NULL)\n";
            string actual = f.Format(original);
            string expected = "x <- function(x,\n intercept = TRUE, tolerance = 1e-07,\n\t\tyname = NULL)\n";

            actual.Should().Be(expected);
        }
Esempio n. 14
0
        internal async Task<string> GetFunctionCode(string functionName, CancellationToken cancellationToken = default(CancellationToken)) {
            var session = _workflow.RSession;
            string functionCode = null;
            try {
                functionCode = await session.GetFunctionCodeAsync(functionName, cancellationToken);
            } catch (RException) { } catch (RHostBrokerBinaryMissingException) { }

            if (!string.IsNullOrEmpty(functionCode)) {
                var formatter = new RFormatter(REditorSettings.FormatOptions);
                functionCode = formatter.Format(functionCode);
            }
            return functionCode;
        }
Esempio n. 15
0
        public void Formatter_FormatFunctionInlineIf01() {
            RFormatter f = new RFormatter();
            string actual = f.Format("x <- func(a,{if(TRUE) {x} else {y}})");
            string expected =
@"x <- func(a, {
  if (TRUE) {
    x
  } else {
    y
  }
})";
            actual.Should().Be(expected);
        }
Esempio n. 16
0
        public void FormatFunctionInlineIf02() {
            RFormatter f = new RFormatter();

            string original = "x <- func(a,\n   {\n      if(TRUE) \n        if(FALSE) {x <-1} else x<-2\nelse\n        if(z) x <-1 else {5}\n    })";
            string actual = f.Format(original);
            string expected =
"x <- func(a, {\n" +
"  if (TRUE)\n" +
"    if (FALSE) { x <- 1 } else x <- 2\n" +
"  else\n" +
"    if (z) x <- 1 else { 5 }\n" +
"})";

            actual.Should().Be(expected);
        }
Esempio n. 17
0
        private static void FormatFileImplementation(CoreTestFilesFixture fixture, string name, RFormatOptions options) {
            string testFile = fixture.GetDestinationPath(name);
            string baselineFile = testFile + ".formatted";
            string text = fixture.LoadDestinationFile(name);

            RFormatter formatter = new RFormatter(options);

            string actual = formatter.Format(text);
            if (_regenerateBaselineFiles) {
                // Update this to your actual enlistment if you need to update baseline
                baselineFile = Path.Combine(fixture.SourcePath, @"Formatting\", Path.GetFileName(testFile)) + ".formatted";
                TestFiles.UpdateBaseline(baselineFile, actual);
            } else {
                TestFiles.CompareToBaseLine(baselineFile, actual);
            }
        }
        public void FormatConditionalTest03() {
            RFormatOptions options = new RFormatOptions();
            options.BracesOnNewLine = true;
            options.IndentSize = 2;
            options.IndentType = IndentType.Tabs;
            options.TabSize = 2;

            RFormatter f = new RFormatter(options);
            string actual = f.Format("if(a == a+((b+c)/x)){if(func(a,b, c+2, x=2, ...)){}}");
            string expected =
@"if (a == a + ((b + c) / x))
{
	if (func(a, b, c + 2, x = 2, ...)) { }
}";
            actual.Should().Be(expected);
        }
Esempio n. 19
0
        public static bool FormatRangeExact(ITextView textView, ITextBuffer textBuffer, ITextRange formatRange, RFormatOptions options, IEditorShell editorShell) {
            ITextSnapshot snapshot = textBuffer.CurrentSnapshot;
            Span spanToFormat = new Span(formatRange.Start, formatRange.Length);
            string spanText = snapshot.GetText(spanToFormat.Start, spanToFormat.Length);
            string trimmedSpanText = spanText.Trim();

            RFormatter formatter = new RFormatter(options);
            string formattedText = formatter.Format(trimmedSpanText);

            formattedText = formattedText.Trim(); // There may be inserted line breaks after {
            // Apply formatted text without indentation. We then will update the parse tree 
            // so we can calculate proper line indents from the AST via the smart indenter.
            if (!spanText.Equals(formattedText, StringComparison.Ordinal)) {
                // Extract existing indent before applying changes. Existing indent
                // may be used by the smart indenter for function argument lists.
                var startLine = snapshot.GetLineFromPosition(spanToFormat.Start);
                var originalIndentSizeInSpaces = IndentBuilder.TextIndentInSpaces(startLine.GetText(), options.IndentSize);

                var selectionTracker = new RSelectionTracker(textView, textBuffer, formatRange);
                RTokenizer tokenizer = new RTokenizer();
                IReadOnlyTextRangeCollection<RToken> oldTokens = tokenizer.Tokenize(spanText);
                IReadOnlyTextRangeCollection<RToken> newTokens = tokenizer.Tokenize(formattedText);

                IncrementalTextChangeApplication.ApplyChangeByTokens(
                    textBuffer,
                    new TextStream(spanText), new TextStream(formattedText),
                    oldTokens, newTokens,
                    formatRange,
                    Resources.AutoFormat, selectionTracker, editorShell,
                    () => {
                        var ast = UpdateAst(textBuffer);
                        // Apply indentation
                        IndentLines(textView, textBuffer, new TextRange(formatRange.Start, formattedText.Length), ast, options, originalIndentSizeInSpaces);
                    });

                return true;
            }

            return false;
        }
Esempio n. 20
0
        public static bool FormatRangeExact(ITextView textView, ITextBuffer textBuffer, ITextRange formatRange,
                                            AstRoot ast, RFormatOptions options, 
                                            int scopeStatementPosition, bool respectUserIndent = true) {
            ITextSnapshot snapshot = textBuffer.CurrentSnapshot;
            Span spanToFormat = new Span(formatRange.Start, formatRange.Length);
            string spanText = snapshot.GetText(spanToFormat.Start, spanToFormat.Length);
            string trimmedSpanText = spanText.Trim();

            if (trimmedSpanText == "}") {
                // Locate opening { and its statement
                var scopeNode = ast.GetNodeOfTypeFromPosition<IAstNodeWithScope>(spanToFormat.Start);
                if (scopeNode != null) {
                    scopeStatementPosition = scopeNode.Start;
                }
            }

            RFormatter formatter = new RFormatter(options);
            string formattedText = formatter.Format(trimmedSpanText);

            formattedText = formattedText.Trim(); // there may be inserted line breaks after {
            formattedText = IndentLines(textBuffer, spanToFormat.Start, ast, formattedText, options, scopeStatementPosition, respectUserIndent);

            if (!spanText.Equals(formattedText, StringComparison.Ordinal)) {
                var selectionTracker = new RSelectionTracker(textView, textBuffer);
                RTokenizer tokenizer = new RTokenizer();
                IReadOnlyTextRangeCollection<RToken> oldTokens = tokenizer.Tokenize(spanText);
                IReadOnlyTextRangeCollection<RToken> newTokens = tokenizer.Tokenize(formattedText);
                IncrementalTextChangeApplication.ApplyChangeByTokens(
                    textBuffer,
                    new TextStream(spanText), new TextStream(formattedText),
                    oldTokens, newTokens,
                    formatRange,
                    Resources.AutoFormat, selectionTracker);
                return true;
            }

            return false;
        }
        public void FormatNoCurlyRepeatTest01() {
            RFormatter f = new RFormatter();
            string actual = f.Format("repeat x<-2");
            string expected =
@"repeat
  x <- 2";
            actual.Should().Be(expected);
        }
Esempio n. 22
0
 public void PreserveBreaks(string original, string expected) {
     RFormatter f = new RFormatter();
     string actual = f.Format(original);
     actual.Should().Be(expected);
 }
Esempio n. 23
0
 public void Multiline(string original, string expected) {
     RFormatter f = new RFormatter();
     string actual = f.Format(original);
     actual.Should().Be(expected);
 }
Esempio n. 24
0
 public void EmptyFileTest() {
     RFormatter f = new RFormatter();
     string s = f.Format(string.Empty);
     s.Should().BeEmpty();
 }
        public void FormatForTest() {
            RFormatter f = new RFormatter();
            string original = @"for (i in 1:6) x[, i] = rowMeans(fmri[[i]])";

            string actual = f.Format(original);

            string expected =
@"for (i in 1:6)
  x[, i] = rowMeans(fmri[[i]])";

            actual.Should().Be(expected);
        }
        public void AlignComments() {
            RFormatter f = new RFormatter();
            string original =
@"
        # comment1
    if (intercept) 
	{
x<- 1

# comment2
x<-3
}
";
            string actual = f.Format(original);
            string expected =
@"
# comment1
if (intercept) {
  x <- 1

  # comment2
  x <- 3
}
";
            actual.Should().Be(expected);
        }
        public void FormatConditionalAlignBraces02() {
            RFormatter f = new RFormatter();
            string original =
@"
    if (intercept) 
	{
        if(x>1)
x<- 1
else
if(x>2)
{
x<-3
}
    }
";
            string actual = f.Format(original);
            string expected =
@"
if (intercept) {
  if (x > 1)
    x <- 1
  else
    if (x > 2) {
      x <- 3
    }
}
";
            actual.Should().Be(expected);
        }
        public void PreserveEmptyLines() {
            RFormatter f = new RFormatter();
            string original =
@"
    if (intercept) 
	{
x<- 1

x<-3
}
";
            string actual = f.Format(original);
            string expected =
@"
if (intercept) {
  x <- 1

  x <- 3
}
";
            actual.Should().Be(expected);
        }
 public void Formatter_FormatUnary(string original, string expected) {
     RFormatter f = new RFormatter();
     string actual = f.Format(original);
     actual.Should().Be(expected);
 }
        public void FormatConditionalAlignBraces01() {
            RFormatter f = new RFormatter();
            string original =
@"
    if (intercept) 
	{
        x <- cbind(1, x)
    }
";
            string actual = f.Format(original);
            string expected =
@"
if (intercept) {
  x <- cbind(1, x)
}
";
            actual.Should().Be(expected);
        }