Ejemplo n.º 1
0
        public override void OnTheFlyFormat(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain,
                                            TextEditorData data, int startOffset, int endOffset)
        {
            var parser          = new CSharpParser();
            var compilationUnit = parser.ParseSnippet(data);

            if (compilationUnit == null)
            {
                Console.WriteLine("couldn't parse : " + data.Text);
                return;
            }

            if (parser.HasErrors)
            {
                return;
            }

            var policy  = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain);
            var adapter = new TextEditorDataAdapter(data);

            var formattingVisitor = new ICSharpCode.NRefactory.CSharp.AstFormattingVisitor(policy.CreateOptions(), adapter, new FormattingActionFactory(data))
            {
                HadErrors = parser.HasErrors
            };

            var changes = new List <ICSharpCode.NRefactory.CSharp.Refactoring.Action> ();

            changes.AddRange(formattingVisitor.Changes.
                             Where(c => (startOffset <= c.Offset && c.Offset < endOffset)));
            using (var undo = data.OpenUndoGroup()) {
                MDRefactoringContext.MdScript.RunActions(changes, null);
            }
        }
Ejemplo n.º 2
0
        public string FormatText(CSharpFormattingPolicy policy, TextStylePolicy textPolicy, string mimeType, string input, int startOffset, int endOffset)
        {
            var data = new TextEditorData();

            data.Document.SuppressHighlightUpdate = true;
            data.Document.MimeType = mimeType;
            data.Document.FileName = "toformat.cs";
            if (textPolicy != null)
            {
                data.Options.TabsToSpaces     = textPolicy.TabsToSpaces;
                data.Options.TabSize          = textPolicy.TabWidth;
                data.Options.DefaultEolMarker = textPolicy.GetEolMarker();
            }
            data.Options.OverrideDocumentEolMarker = true;
            data.Text = input;

//			System.Console.WriteLine ("-----");
//			System.Console.WriteLine (data.Text.Replace (" ", ".").Replace ("\t", "->"));
//			System.Console.WriteLine ("-----");

            var  parser          = new CSharpParser();
            var  compilationUnit = parser.Parse(data);
            bool hadErrors       = parser.HasErrors;

            if (hadErrors)
            {
//				foreach (var e in parser.ErrorReportPrinter.Errors)
//					Console.WriteLine (e.Message);
                return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset)));
            }
            var adapter           = new TextEditorDataAdapter(data);
            var formattingVisitor = new ICSharpCode.NRefactory.CSharp.AstFormattingVisitor(policy.CreateOptions(), adapter, new FormattingActionFactory(data))
            {
                HadErrors = hadErrors
            };

            compilationUnit.AcceptVisitor(formattingVisitor, null);


            var changes = new List <ICSharpCode.NRefactory.CSharp.Refactoring.Action> ();

            changes.AddRange(formattingVisitor.Changes.
                             Where(c => (startOffset <= c.Offset && c.Offset < endOffset)));

            MDRefactoringContext.MdScript.RunActions(changes, null);

            // check if the formatter has produced errors
            parser = new CSharpParser();
            parser.Parse(data);
            if (parser.HasErrors)
            {
                LoggingService.LogError("C# formatter produced source code errors. See console for output.");
                Console.WriteLine(data.Text);
                return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset)));
            }

            int end = endOffset;

            foreach (TextReplaceAction c in changes)
            {
                end -= c.RemovedChars;
                if (c.InsertedText != null)
                {
                    end += c.InsertedText.Length;
                }
            }

            /*			System.Console.WriteLine ("-----");
             *      System.Console.WriteLine (data.Text.Replace (" ", "^").Replace ("\t", "->"));
             *      System.Console.WriteLine ("-----");*/
            string result = data.GetTextBetween(startOffset, Math.Min(data.Length, end));

            data.Dispose();
            return(result);
        }
Ejemplo n.º 3
0
		public string FormatText (CSharpFormattingPolicy policy, TextStylePolicy textPolicy, string mimeType, string input, int startOffset, int endOffset)
		{
			var data = new TextEditorData ();
			data.Document.SuppressHighlightUpdate = true;
			data.Document.MimeType = mimeType;
			data.Document.FileName = "toformat.cs";
			if (textPolicy != null) {
				data.Options.TabsToSpaces = textPolicy.TabsToSpaces;
				data.Options.TabSize = textPolicy.TabWidth;
				data.Options.DefaultEolMarker = textPolicy.GetEolMarker ();
			}
			data.Options.OverrideDocumentEolMarker = true;
			data.Text = input;

//			System.Console.WriteLine ("-----");
//			System.Console.WriteLine (data.Text.Replace (" ", ".").Replace ("\t", "->"));
//			System.Console.WriteLine ("-----");

			var parser = new CSharpParser ();
			var compilationUnit = parser.Parse (data);
			bool hadErrors = parser.HasErrors;
			
			if (hadErrors) {
//				foreach (var e in parser.ErrorReportPrinter.Errors)
//					Console.WriteLine (e.Message);
				return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset));
			}
			var adapter = new TextEditorDataAdapter (data);
			var formattingVisitor = new ICSharpCode.NRefactory.CSharp.AstFormattingVisitor (policy.CreateOptions (), adapter, new FormattingActionFactory (data)) {
				HadErrors = hadErrors
			};
			
			compilationUnit.AcceptVisitor (formattingVisitor, null);
			
			
			var changes = new List<ICSharpCode.NRefactory.CSharp.Refactoring.Action> ();

			changes.AddRange (formattingVisitor.Changes.
				Where (c => (startOffset <= c.Offset && c.Offset < endOffset)));
			
			MDRefactoringContext.MdScript.RunActions (changes, null);
			
			// check if the formatter has produced errors
			parser = new CSharpParser ();
			parser.Parse (data);
			if (parser.HasErrors) {
				LoggingService.LogError ("C# formatter produced source code errors. See console for output.");
				Console.WriteLine (data.Text);
				return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset));
			}
				
			int end = endOffset;
			foreach (TextReplaceAction c in changes) {
				end -= c.RemovedChars;
				if (c.InsertedText != null)
					end += c.InsertedText.Length;
			}
			
		/*			System.Console.WriteLine ("-----");
			System.Console.WriteLine (data.Text.Replace (" ", "^").Replace ("\t", "->"));
			System.Console.WriteLine ("-----");*/
			string result = data.GetTextBetween (startOffset, Math.Min (data.Length, end));
			data.Dispose ();
			return result;
		}
Ejemplo n.º 4
0
		public override void OnTheFlyFormat (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, 
			TextEditorData data, int startOffset, int endOffset)
		{
			var parser = new CSharpParser ();
			var compilationUnit = parser.ParseSnippet (data);
			if (compilationUnit == null) {
				Console.WriteLine ("couldn't parse : " + data.Text);
				return;
			}
			
			if (parser.HasErrors)
				return;
			
			var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
			var adapter = new TextEditorDataAdapter (data);
			
			var formattingVisitor = new ICSharpCode.NRefactory.CSharp.AstFormattingVisitor (policy.CreateOptions (), adapter, new FormattingActionFactory (data)) {
				HadErrors =  parser.HasErrors
			};
			
			var changes = new List<ICSharpCode.NRefactory.CSharp.Refactoring.Action> ();
			changes.AddRange (formattingVisitor.Changes.
				Where (c => (startOffset <= c.Offset && c.Offset < endOffset)));
			using (var undo = data.OpenUndoGroup ()) {
				MDRefactoringContext.MdScript.RunActions (changes, null);
			}
		}
Ejemplo n.º 5
0
        public static void Format(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, MonoDevelop.Ide.Gui.Document data, ProjectDom dom, DomLocation location, bool correctBlankLines, bool runAferCR /* = false*/)
        {
            if (data.ParsedDocument == null || data.ParsedDocument.CompilationUnit == null)
            {
                return;
            }
            var member = data.ParsedDocument.CompilationUnit.GetMemberAt(location.Line + (runAferCR ? -1 : 0), location.Column);

            if (member == null || member.Location.IsEmpty || member.BodyRegion.End.IsEmpty)
            {
                return;
            }

            StringBuilder sb = new StringBuilder();
            int           closingBrackets = 0;
            DomRegion     validRegion     = DomRegion.Empty;

            foreach (var u in data.ParsedDocument.CompilationUnit.Usings.Where(us => us.IsFromNamespace))
            {
                // the dom parser breaks A.B.C into 3 namespaces with the same region, this is filtered here
                if (u.ValidRegion == validRegion || !u.ValidRegion.Contains(location))
                {
                    continue;
                }
                // indicates a parser error on namespace level.
                if (u.Namespaces.FirstOrDefault() == "<invalid>")
                {
                    continue;
                }
                validRegion = u.ValidRegion;
                sb.Append("namespace Stub {");
                sb.Append(data.Editor.EolMarker);
                closingBrackets++;
            }

            var parent = member.DeclaringType;

            while (parent != null)
            {
                sb.Append("class Stub {");
                sb.Append(data.Editor.EolMarker);
                closingBrackets++;
                parent = parent.DeclaringType;
            }
            int memberStart = data.Editor.LocationToOffset(member.Location.Line, 1);
            int memberEnd   = data.Editor.LocationToOffset(member.BodyRegion.End.Line + (runAferCR ? 1 : 0), member.BodyRegion.End.Column);

            if (memberEnd < 0)
            {
                memberEnd = data.Editor.Length;
            }

            int startOffset = sb.Length;

            sb.Append(data.Editor.GetTextBetween(memberStart, memberEnd));

            int endOffset = sb.Length;

            sb.Append(data.Editor.EolMarker);
            sb.Append(new string ('}', closingBrackets));

            TextEditorData stubData = new TextEditorData()
            {
                Text = sb.ToString()
            };

            stubData.Document.FileName = data.FileName;
            var  parser          = new ICSharpCode.NRefactory.CSharp.CSharpParser();
            var  compilationUnit = parser.Parse(stubData);
            bool hadErrors       = parser.HasErrors;
            var  policy          = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain);
            var  adapter         = new TextEditorDataAdapter(stubData);

            var domSpacingVisitor = new AstFormattingVisitor(policy.CreateOptions(), adapter, new FormattingActionFactory(data.Editor))
            {
                HadErrors = hadErrors
            };

            compilationUnit.AcceptVisitor(domSpacingVisitor, null);

            var changes = new List <ICSharpCode.NRefactory.CSharp.Refactoring.Action> ();

            changes.AddRange(domSpacingVisitor.Changes.Cast <TextReplaceAction> ().Where(c => startOffset < c.Offset && c.Offset < endOffset));

            int           delta = memberStart - startOffset;
            HashSet <int> lines = new HashSet <int> ();

            foreach (TextReplaceAction change in changes)
            {
                change.Offset += delta;
                lines.Add(data.Editor.OffsetToLineNumber(change.Offset));
            }
            // be sensible in documents with parser errors - only correct up to the caret position.
            if (hadErrors || data.ParsedDocument.Errors.Any(e => e.ErrorType == ErrorType.Error))
            {
                var lastOffset = data.Editor.Caret.Offset;
                changes.RemoveAll(c => ((TextReplaceAction)c).Offset > lastOffset);
            }

            using (var undo = data.Editor.OpenUndoGroup()) {
                MDRefactoringContext.MdScript.RunActions(changes, null);

                foreach (int line in lines)
                {
                    data.Editor.Document.CommitLineUpdate(line);
                }
            }
            stubData.Dispose();
        }
Ejemplo n.º 6
0
		public static void Format (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, MonoDevelop.Ide.Gui.Document data, ProjectDom dom, DomLocation location, bool correctBlankLines, bool runAferCR/* = false*/)
		{
			if (data.ParsedDocument == null || data.ParsedDocument.CompilationUnit == null)
				return;
			var member = data.ParsedDocument.CompilationUnit.GetMemberAt (location.Line + (runAferCR ? -1 : 0), location.Column);
			if (member == null || member.Location.IsEmpty || member.BodyRegion.End.IsEmpty)
				return;
			
			StringBuilder sb = new StringBuilder ();
			int closingBrackets = 0;
			DomRegion validRegion = DomRegion.Empty;
			foreach (var u in data.ParsedDocument.CompilationUnit.Usings.Where (us => us.IsFromNamespace)) {
				// the dom parser breaks A.B.C into 3 namespaces with the same region, this is filtered here
				if (u.ValidRegion == validRegion || !u.ValidRegion.Contains (location))
					continue;
				// indicates a parser error on namespace level.
				if (u.Namespaces.FirstOrDefault () == "<invalid>")
					continue;
				validRegion = u.ValidRegion;
				sb.Append ("namespace Stub {");
				closingBrackets++;
			}
			
			var parent = member.DeclaringType;
			while (parent != null) {
				sb.Append ("class Stub {");
				closingBrackets++;
				parent = parent.DeclaringType;
			}
			sb.AppendLine ();
			int startOffset = sb.Length;
			int memberStart = data.Editor.LocationToOffset (member.Location.Line, 1);
			int memberEnd = data.Editor.LocationToOffset (member.BodyRegion.End.Line + (runAferCR ? 1 : 0), member.BodyRegion.End.Column);
			if (memberEnd < 0)
				memberEnd = data.Editor.Length;
			sb.Append (data.Editor.GetTextBetween (memberStart, memberEnd));
			int endOffset = sb.Length;
			sb.AppendLine ();
			sb.Append (new string ('}', closingBrackets));
			TextEditorData stubData = new TextEditorData () { Text = sb.ToString () };
			stubData.Document.FileName = data.FileName;
			var parser = new ICSharpCode.NRefactory.CSharp.CSharpParser ();
			var compilationUnit = parser.Parse (stubData);
			bool hadErrors = parser.HasErrors;
			var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
			var adapter = new TextEditorDataAdapter (stubData);
			
			var domSpacingVisitor = new AstFormattingVisitor (policy.CreateOptions (), adapter, new FormattingActionFactory (data.Editor)) {
				HadErrors = hadErrors
			};
			compilationUnit.AcceptVisitor (domSpacingVisitor, null);
			
			var changes = new List<ICSharpCode.NRefactory.CSharp.Refactoring.Action> ();
			changes.AddRange (domSpacingVisitor.Changes.Cast<TextReplaceAction> ().Where (c => startOffset < c.Offset && c.Offset < endOffset));
			
			int delta = data.Editor.LocationToOffset (member.Location.Line, 1) - startOffset;
			HashSet<int > lines = new HashSet<int> ();
			foreach (TextReplaceAction change in changes) {
				change.Offset += delta;
				lines.Add (data.Editor.OffsetToLineNumber (change.Offset));
			}
			// be sensible in documents with parser errors - only correct up to the caret position.
			if (hadErrors || data.ParsedDocument.Errors.Any (e => e.ErrorType == ErrorType.Error)) {
				var lastOffset = data.Editor.Caret.Offset;
				changes.RemoveAll (c => ((TextReplaceAction)c).Offset > lastOffset);
			}
			
			using (var undo = data.Editor.OpenUndoGroup ()) {
				MDRefactoringContext.MdScript.RunActions (changes, null);
				
				foreach (int line in lines)
					data.Editor.Document.CommitLineUpdate (line);
			}
			stubData.Dispose ();
		}