Exemple #1
0
        public static string CalculateIndent(TextReader code, int line, bool tabsToSpaces = false, int indentWidth = 4)
        {
            if (line < 2)
            {
                return(string.Empty);
            }

            var eng = new IndentEngine(DFormattingOptions.CreateDStandard(), tabsToSpaces, indentWidth);

            int       curLine = 1;
            const int lf      = (int)'\n';
            const int cr      = (int)'\r';
            int       c;

            while ((c = code.Read()) != -1)
            {
                if (c == lf || c == cr)
                {
                    if (c == cr && code.Peek() == lf)
                    {
                        code.Read();
                    }

                    if (++curLine > line)
                    {
                        break;
                    }
                }

                eng.Push((char)c);
            }

            return(eng.ThisLineIndent);
        }
Exemple #2
0
        static void formattingTests()
        {
            var policy = new DFormattingOptions();

            policy.TypeBlockBraces            = BraceStyle.NextLine;
            policy.MultiVariableDeclPlacement = NewLinePlacement.SameLine;

            var code = @"
class A
{

this()
{
}

private:

int* privPtr = 2134;

public
{
	int pubInt;
}

//SomeDoc
void                main
() in{}
out(v){}
body{

	int a = 123;
	a++

;

}
@safe int[] 
d 
=
34;
int a=12,b=23,c;



void foo(string[] args) {}
}";

            Console.WriteLine("## Formatting ##");

            var ast = D_Parser.Parser.DParser.ParseString(code) as DModule;

            var sw = new Stopwatch();

            sw.Start();
            code = Formatter.FormatCode(code, ast, null, policy);
            sw.Stop();
            Console.WriteLine(code);
            Console.WriteLine("Took {0}ms", sw.Elapsed.TotalMilliseconds);
        }
Exemple #3
0
        public static void Fmt(string code, string targetCode, DFormattingOptions policy)
        {
            var formatOutput = Formatter.FormatCode(code, null, new TextDocument {
                Text = code
            }, policy, TextEditorOptions.Default);

            Assert.AreEqual(targetCode, formatOutput.Trim());
        }
		public static void CorrectIndent(TextReader code, int startOffset, int endOffset, Action<int, int, string> documentReplace, DFormattingOptions options = null, ITextEditorOptions textStyle = null, bool formatLastLine = true)
		{
			textStyle = textStyle ?? TextEditorOptions.Default;
			
			var eng = new IndentEngine(options ?? DFormattingOptions.CreateDStandard(), textStyle.TabsToSpaces, textStyle.IndentSize, textStyle.KeepAlignmentSpaces);
			var replaceActions = new List<DFormattingVisitor.TextReplaceAction>();
			
			int originalIndent = 0;
			bool hadLineBreak = true;
			
			int n = 0;
			for (int i = 0; i <= endOffset && (n = code.Read()) != -1; i++)
			{
				if(n == '\r' || n == '\n')
				{
					if (i >= startOffset && !eng.LineBeganInsideString)
						replaceActions.Add(new DFormattingVisitor.TextReplaceAction(eng.Position - eng.LineOffset, originalIndent, eng.ThisLineIndent));
					
					hadLineBreak = true;
					originalIndent = 0;

					if (code.Peek() == '\n')
					{
						eng.Push((char)code.Read());
						i++;
					}
				}
				else if(hadLineBreak)
				{
					if(n == ' ' || n== '\t')
						originalIndent++;
					else
						hadLineBreak = false;

					// If there's code left, format the last line of the selection either
					if (i == endOffset && formatLastLine)
						endOffset++;
				}

				eng.Push((char)n);
			}

			// Also indent the last line if we're at the EOF.
			if (code.Peek() == -1 || (formatLastLine && n != '\r' && n != '\n'))
			{
				if(!eng.LineBeganInsideString)
					replaceActions.Add(new DFormattingVisitor.TextReplaceAction(eng.Position - eng.LineOffset, originalIndent, eng.ThisLineIndent));
			}
			
			// Perform replacements from the back of the document to the front - to ensure offset consistency
			for(int k = replaceActions.Count - 1; k>=0; k--)
			{
				var rep = replaceActions[k];
				if(rep.RemovalLength > 0 || rep.NewText.Length != 0)
					documentReplace(rep.Offset, rep.RemovalLength, rep.NewText);
			}
		}
Exemple #5
0
        public void Formatting()
        {
            var o = DFormattingOptions.CreateDStandard();

            bool isTargetCode = false;

            var rawCode = string.Empty;
            var sb      = new StringBuilder();
            var l       = new List <Tuple <string, string> >();

            using (var st = Assembly.GetExecutingAssembly().GetManifestResourceStream("formatterTests")){
                using (var r = new StreamReader(st))
                {
                    int n;
                    while ((n = r.Read()) != -1)
                    {
                        if ((n == ':' && r.Peek() == ':') || (n == '#' && r.Peek() == '#'))
                        {
                            r.ReadLine();

                            if (n == '#')
                            {
                                if (isTargetCode)
                                {
                                    l.Add(new Tuple <string, string>(rawCode, sb.ToString().Trim()));
                                    sb.Clear();
                                }
                                else
                                {
                                    rawCode = sb.ToString().Trim();
                                    sb.Clear();
                                }

                                isTargetCode = !isTargetCode;
                            }
                        }
                        else if (n == '\r' || n == '\n')
                        {
                            sb.Append((char)n);
                        }
                        else
                        {
                            sb.Append((char)n);
                            sb.AppendLine(r.ReadLine());
                        }
                    }
                }
            }

            foreach (var tup in l)
            {
                Fmt(tup.Item1, tup.Item2, o);
            }
        }
Exemple #6
0
        public IndentEngine(DFormattingOptions policy, bool tabsToSpaces = false, int indentWidth = 4, bool keepAlignmentSpaces = true)
        {
            if (policy == null)
            {
                throw new ArgumentNullException("policy");
            }

            this.Policy              = policy;
            this.tabsToSpaces        = tabsToSpaces;
            this.indentWidth         = indentWidth;
            this.keepAlignmentSpaces = keepAlignmentSpaces;
            stack   = new IndentStack(this);
            linebuf = new StringBuilder();
            Reset();
        }
Exemple #7
0
        public void FormatDocument(DFormattingOptions policy = null)
        {
            policy = policy ?? DFormattingOptions.CreateDStandard();

            var formatter = new DFormattingVisitor(policy, new DocAdapter(dEditor.Editor.Document), dEditor.SyntaxTree);

            formatter.WalkThroughAst();

            dEditor.Editor.Document.UndoStack.StartUndoGroup();
            try
            {
                formatter.ApplyChanges(dEditor.Editor.Document.Replace);
            }
            catch (Exception ex)
            {
                ErrorLogger.Log(ex, ErrorType.Error, ErrorOrigin.Parser);
            }
            dEditor.Editor.Document.UndoStack.EndUndoGroup();
        }
Exemple #8
0
        public static void CorrectIndent(TextReader code, int startOffset, int endOffset, Action <int, int, string> documentReplace, DFormattingOptions options = null, ITextEditorOptions textStyle = null, bool formatLastLine = true)
        {
            textStyle = textStyle ?? TextEditorOptions.Default;

            var eng            = new IndentEngine(options ?? DFormattingOptions.CreateDStandard(), textStyle.TabsToSpaces, textStyle.IndentSize, textStyle.KeepAlignmentSpaces);
            var replaceActions = new List <DFormattingVisitor.TextReplaceAction>();

            int  originalIndent = 0;
            bool hadLineBreak   = true;

            int n = 0;

            for (int i = 0; i <= endOffset && (n = code.Read()) != -1; i++)
            {
                if (n == '\r' || n == '\n')
                {
                    if (i >= startOffset && !eng.LineBeganInsideString)
                    {
                        replaceActions.Add(new DFormattingVisitor.TextReplaceAction(eng.Position - eng.LineOffset, originalIndent, eng.ThisLineIndent));
                    }

                    hadLineBreak   = true;
                    originalIndent = 0;

                    if (code.Peek() == '\n')
                    {
                        eng.Push((char)code.Read());
                        i++;
                    }
                }
                else if (hadLineBreak)
                {
                    if (n == ' ' || n == '\t')
                    {
                        originalIndent++;
                    }
                    else
                    {
                        hadLineBreak = false;
                    }

                    // If there's code left, format the last line of the selection either
                    if (i == endOffset && formatLastLine)
                    {
                        endOffset++;
                    }
                }

                eng.Push((char)n);
            }

            // Also indent the last line if we're at the EOF.
            if (code.Peek() == -1 || (formatLastLine && n != '\r' && n != '\n'))
            {
                if (!eng.LineBeganInsideString)
                {
                    replaceActions.Add(new DFormattingVisitor.TextReplaceAction(eng.Position - eng.LineOffset, originalIndent, eng.ThisLineIndent));
                }
            }

            // Perform replacements from the back of the document to the front - to ensure offset consistency
            for (int k = replaceActions.Count - 1; k >= 0; k--)
            {
                var rep = replaceActions[k];
                if (rep.RemovalLength > 0 || rep.NewText.Length != 0)
                {
                    documentReplace(rep.Offset, rep.RemovalLength, rep.NewText);
                }
            }
        }
Exemple #9
0
        public IndentEngine(DFormattingOptions policy, bool tabsToSpaces = false, int indentWidth = 4, bool keepAlignmentSpaces = true)
        {
            if (policy == null)
                throw new ArgumentNullException ("policy");

            this.Policy = policy;
            this.tabsToSpaces = tabsToSpaces;
            this.indentWidth = indentWidth;
            this.keepAlignmentSpaces = keepAlignmentSpaces;
            stack = new IndentStack (this);
            linebuf = new StringBuilder ();
            Reset ();
        }