Exemplo n.º 1
1
        /// <summary>
        /// Used for formatting the entire document
        /// </summary>
        public override string FormatText(PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, string input, int startOffset, int endOffset)
        {
            var policy = policyParent.Get<DFormattingPolicy> (mimeTypeChain);
            var textPolicy = policyParent.Get<TextStylePolicy> (mimeTypeChain);
            var data = new TextEditorData{ Text = input };

            if(IndentCorrectionOnly)
            {
                using(var s = data.OpenStream())
                    using(var r = new StreamReader(s))
                        D_Parser.Formatting.Indent.IndentEngineWrapper.CorrectIndent(r, startOffset, endOffset, data.Document.Replace, policy.Options, new TextStyleAdapter(textPolicy));
                return data.Text;
            }

            var ast = DParser.ParseString(input, false, true) as DModule;
            var formattingVisitor = new DFormattingVisitor(policy.Options, new DocAdapt(data.Document), ast, new TextStyleAdapter(textPolicy));

            // Only clip to a region if it's necessary
            if(startOffset > 0 || endOffset < input.Length-1)
            {
                formattingVisitor.CheckFormattingBoundaries = true;
                var dl = data.Document.OffsetToLocation(startOffset);
                formattingVisitor.FormattingStartLocation = new D_Parser.Dom.CodeLocation(dl.Column, dl.Line);
                dl = data.Document.OffsetToLocation(endOffset);
                formattingVisitor.FormattingEndLocation = new D_Parser.Dom.CodeLocation(dl.Column, dl.Line);
            }

            formattingVisitor.WalkThroughAst();

            formattingVisitor.ApplyChanges(data.Document.Replace);

            return data.Text;
        }
Exemplo n.º 2
1
		public override void CorrectIndenting (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, 
			TextEditorData data, int line)
		{
			DocumentLine lineSegment = data.Document.GetLine (line);
			if (lineSegment == null)
				return;

			try {
				var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
				var tracker = new CSharpIndentEngine (data.Document, data.CreateNRefactoryTextEditorOptions (),  policy.CreateOptions ());

				tracker.Update (lineSegment.Offset);
				for (int i = lineSegment.Offset; i < lineSegment.Offset + lineSegment.Length; i++) {
					tracker.Push (data.Document.GetCharAt (i));
				}

				string curIndent = lineSegment.GetIndentation (data.Document);

				int nlwsp = curIndent.Length;
				if (!tracker.LineBeganInsideMultiLineComment || (nlwsp < lineSegment.LengthIncludingDelimiter && data.Document.GetCharAt (lineSegment.Offset + nlwsp) == '*')) {
					// Possibly replace the indent
					string newIndent = tracker.ThisLineIndent;
					if (newIndent != curIndent) 
						data.Replace (lineSegment.Offset, nlwsp, newIndent);
				}
			} catch (Exception e) {
				LoggingService.LogError ("Error while indenting", e);
			}
		}
Exemplo n.º 3
0
        public override string FormatText(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, string input, int startOffset, int endOffset)
        {
            var policy     = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain);
            var textPolicy = policyParent.Get <TextStylePolicy> (mimeTypeChain);

            return(FormatText(policy, textPolicy, mimeTypeChain.First(), input, startOffset, endOffset));
        }
Exemplo n.º 4
0
        public string FormatText(PolicyContainer policyParent, string mimeType, string input)
        {
            XmlFormattingPolicy xmlPol = policyParent.Get <XmlFormattingPolicy> (mimeType);
            TextStylePolicy     txtPol = policyParent.Get <TextStylePolicy> (mimeType);

            return(FormatXml(txtPol, xmlPol, input));
        }
        T GetCurrentPolicy()
        {
            object pol = null;

            if (loaded)
            {
                pol = GetPolicy();
            }
            else if (hasCachedPolicy)
            {
                pol = cachedPolicy;
            }

            if (pol == null)
            {
                pol = policyContainer.Get <T> (mimeTypeScopes);
                if (pol == null && defaultPolicyContainer != null)
                {
                    return(defaultPolicyContainer.Get <T> (mimeTypeScopes));
                }

                // If the policy container being edited doesn't have this policy defined (and doesn't inherit it from anyhwere)
                // then try getting the policy from defaultPolicyContainer.
            }
            return((T)pol);
        }
Exemplo n.º 6
0
        public string FormatText(PolicyContainer policyParent, IEnumerable <string> mimeTypeInheritanceChain, string input)
        {
            var txtPol = policyParent.Get <TextStylePolicy> (mimeTypeInheritanceChain);
            var xmlPol = policyParent.Get <XmlFormattingPolicy> (mimeTypeInheritanceChain);

            return(FormatXml(txtPol, xmlPol, input));
        }
Exemplo n.º 7
0
		protected override void CorrectIndentingImplementation (PolicyContainer policyParent, TextEditor editor, int line)
		{
			var lineSegment = editor.GetLine (line);
			if (lineSegment == null)
				return;

			try {
				var policy = policyParent.Get<CSharpFormattingPolicy> (MimeType);
				var textpolicy = policyParent.Get<TextStylePolicy> (MimeType);
				var tracker = new CSharpIndentEngine (policy.CreateOptions (textpolicy));

				tracker.Update (IdeApp.Workbench.ActiveDocument.Editor, lineSegment.Offset);
				for (int i = lineSegment.Offset; i < lineSegment.Offset + lineSegment.Length; i++) {
					tracker.Push (editor.GetCharAt (i));
				}

				string curIndent = lineSegment.GetIndentation (editor);

				int nlwsp = curIndent.Length;
				if (!tracker.LineBeganInsideMultiLineComment || (nlwsp < lineSegment.LengthIncludingDelimiter && editor.GetCharAt (lineSegment.Offset + nlwsp) == '*')) {
					// Possibly replace the indent
					string newIndent = tracker.ThisLineIndent;
					if (newIndent != curIndent) 
						editor.ReplaceText (lineSegment.Offset, nlwsp, newIndent);
				}
			} catch (Exception e) {
				LoggingService.LogError ("Error while indenting", e);
			}
		}
Exemplo n.º 8
0
        public override void CorrectIndenting(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain,
                                              TextEditorData data, int line)
        {
            DocumentLine lineSegment = data.Document.GetLine(line);

            if (lineSegment == null)
            {
                return;
            }

            var policy     = policyParent.Get <PlayScriptFormattingPolicy> (mimeTypeChain);
            var textPolicy = policyParent.Get <TextStylePolicy> (mimeTypeChain);
            var tracker    = new DocumentStateTracker <CSharpIndentEngine> (new CSharpIndentEngine(policy, textPolicy), data);

            tracker.UpdateEngine(lineSegment.Offset);
            for (int i = lineSegment.Offset; i < lineSegment.Offset + lineSegment.Length; i++)
            {
                tracker.Engine.Push(data.Document.GetCharAt(i));
            }

            string curIndent = lineSegment.GetIndentation(data.Document);

            int nlwsp = curIndent.Length;

            if (!tracker.Engine.LineBeganInsideMultiLineComment || (nlwsp < lineSegment.LengthIncludingDelimiter && data.Document.GetCharAt(lineSegment.Offset + nlwsp) == '*'))
            {
                // Possibly replace the indent
                string newIndent = tracker.Engine.ThisLineIndent;
                if (newIndent != curIndent)
                {
                    data.Replace(lineSegment.Offset, nlwsp, newIndent);
                }
            }
            tracker.Dispose();
        }
Exemplo n.º 9
0
        protected override ITextSource FormatImplementation(PolicyContainer policyParent, string mimeType, ITextSource input, int startOffset, int length)
        {
            var policy     = policyParent.Get <CSharpFormattingPolicy> (mimeType);
            var textPolicy = policyParent.Get <TextStylePolicy> (mimeType);

            return(new StringTextSource(FormatText(policy, textPolicy, input.Text, startOffset, startOffset + length)));
        }
Exemplo n.º 10
0
		public override void CorrectIndenting (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, 
			TextEditorData data, int line)
		{
			DocumentLine lineSegment = data.Document.GetLine (line);
			if (lineSegment == null)
				return;

			var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
			var textPolicy = policyParent.Get<TextStylePolicy> (mimeTypeChain);
			var tracker = new DocumentStateTracker<CSharpIndentEngine> (new CSharpIndentEngine (policy, textPolicy), data);
			tracker.UpdateEngine (lineSegment.Offset);
			for (int i = lineSegment.Offset; i < lineSegment.Offset + lineSegment.Length; i++) {
				tracker.Engine.Push (data.Document.GetCharAt (i));
			}

			string curIndent = lineSegment.GetIndentation (data.Document);

			int nlwsp = curIndent.Length;
			if (!tracker.Engine.LineBeganInsideMultiLineComment || (nlwsp < lineSegment.LengthIncludingDelimiter && data.Document.GetCharAt (lineSegment.Offset + nlwsp) == '*')) {
				// Possibly replace the indent
				string newIndent = tracker.Engine.ThisLineIndent;
				if (newIndent != curIndent) 
					data.Replace (lineSegment.Offset, nlwsp, newIndent);
			}
			tracker.Dispose ();
		}
        public void UpdateStyleParent(Project styleParent, string mimeType)
        {
            if (policyContainer != null)
            {
                policyContainer.PolicyChanged -= HandlePolicyChanged;
            }

            if (string.IsNullOrEmpty(mimeType))
            {
                mimeType = "text/plain";
            }
            this.mimeTypes = DesktopService.GetMimeTypeInheritanceChain(mimeType);

            if (styleParent != null)
            {
                policyContainer = styleParent.Policies;
            }
            else
            {
                policyContainer = MonoDevelop.Projects.Policies.PolicyService.DefaultPolicies;
            }

            currentPolicy = policyContainer.Get <TextStylePolicy> (mimeTypes);
            policyContainer.PolicyChanged += HandlePolicyChanged;
        }
Exemplo n.º 12
0
        protected override ITextSource FormatImplementation(PolicyContainer policyParent, string mimeType, ITextSource input, int startOffset, int length)
        {
            var chain      = DesktopService.GetMimeTypeInheritanceChain(mimeType);
            var policy     = policyParent.Get <CSharpFormattingPolicy> (chain);
            var textPolicy = policyParent.Get <TextStylePolicy> (chain);

            return(new StringTextSource(FormatText(policy.CreateOptions(textPolicy), input.Text, startOffset, startOffset + length)));
        }
Exemplo n.º 13
0
		protected override Core.Text.ITextSource FormatImplementation (PolicyContainer policyParent, string mimeType, Core.Text.ITextSource input, int startOffset, int length)
		{
			if (policyParent == null)
				policyParent = PolicyService.DefaultPolicies;
			var txtPol = policyParent.Get<TextStylePolicy> (mimeType);
			var xmlPol = policyParent.Get<XmlFormattingPolicy> (mimeType);
			return new StringTextSource(FormatXml (txtPol, xmlPol, input.Text));
		}
Exemplo n.º 14
0
        public static string SaveFormattedXml(PolicyContainer policies, AddinDescription adesc)
        {
            XmlDocument doc = adesc.SaveToXml();

            TextStylePolicy     textPolicy = policies.Get <TextStylePolicy> (DesktopService.GetMimeTypeInheritanceChain("application/x-addin+xml"));
            XmlFormattingPolicy xmlPolicy  = policies.Get <XmlFormattingPolicy> (DesktopService.GetMimeTypeInheritanceChain("application/x-addin+xml"));

            return(XmlFormatter.FormatXml(textPolicy, xmlPolicy, doc.OuterXml));
        }
Exemplo n.º 15
0
        public override string FormatText(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain,
                                          string input, int startOffset, int endOffset)
        {
            var data = new TextEditorData();

            data.Document.SuppressHighlightUpdate = true;
            data.Document.MimeType = mimeTypeChain.First();
            data.Document.FileName = "toformat.cs";
            var textPolicy = policyParent.Get <TextStylePolicy> (mimeTypeChain);

            data.Options.TabsToSpaces = textPolicy.TabsToSpaces;
            data.Options.TabSize      = textPolicy.TabWidth;
            data.Options.OverrideDocumentEolMarker = true;
            data.Options.DefaultEolMarker          = textPolicy.GetEolMarker();
            data.Text = input;

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

            MonoDevelop.CSharp.Parser.CSharpParser parser = new MonoDevelop.CSharp.Parser.CSharpParser();
            var  compilationUnit = parser.Parse(data);
            bool hadErrors       = parser.ErrorReportPrinter.ErrorsCount + parser.ErrorReportPrinter.FatalCounter > 0;
            var  policy          = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain);

            var formattingVisitor = new AstFormattingVisitor(policy, data)
            {
                AutoAcceptChanges = false
            };

            compilationUnit.AcceptVisitor(formattingVisitor, null);

            var changes = new List <Change> ();

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

            RefactoringService.AcceptChanges(null, null, changes);
            int end = endOffset;

            foreach (TextReplaceChange 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);
        }
Exemplo n.º 16
0
        static async void Format(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, TextEditor editor, DocumentContext context, int startOffset, int endOffset, bool exact, bool formatLastStatementOnly = false, OptionSet optionSet = null)
        {
            TextSpan span;

            if (exact)
            {
                span = new TextSpan(startOffset, endOffset - startOffset);
            }
            else
            {
                span = new TextSpan(0, endOffset);
            }

            var analysisDocument = context.AnalysisDocument;

            if (analysisDocument == null)
            {
                return;
            }
            using (var undo = editor.OpenUndoGroup(/*OperationType.Format*/)) {
                try {
                    var syntaxTree = await analysisDocument.GetSyntaxTreeAsync();

                    var root = syntaxTree.GetRoot();
                    if (formatLastStatementOnly)
                    {
                        var token  = root.FindToken(endOffset);
                        var tokens = Microsoft.CodeAnalysis.CSharp.Utilities.FormattingRangeHelper.FindAppropriateRange(token);
                        if (tokens.HasValue)
                        {
                            span = new TextSpan(tokens.Value.Item1.SpanStart, editor.CaretOffset - tokens.Value.Item1.SpanStart);
                        }
                        else
                        {
                            var parent = token.Parent;
                            if (parent != null)
                            {
                                span = new TextSpan(parent.FullSpan.Start, editor.CaretOffset - parent.FullSpan.Start);
                            }
                        }
                    }

                    if (optionSet == null)
                    {
                        var policy     = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain);
                        var textPolicy = policyParent.Get <TextStylePolicy> (mimeTypeChain);
                        optionSet = policy.CreateOptions(textPolicy);
                    }
                    var rules   = Formatter.GetDefaultFormattingRules(analysisDocument);
                    var changes = Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(span), context.RoslynWorkspace, optionSet, rules, default(CancellationToken));
                    editor.ApplyTextChanges(changes);
                } catch (Exception e) {
                    LoggingService.LogError("Error in on the fly formatter", e);
                }
            }
        }
Exemplo n.º 17
0
        static void Format(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, TextEditor editor, DocumentContext context, int startOffset, int endOffset, bool exact, bool formatLastStatementOnly = false, OptionSet optionSet = null)
        {
            TextSpan span;

            if (exact)
            {
                span = new TextSpan(startOffset, endOffset - startOffset);
            }
            else
            {
                span = new TextSpan(0, endOffset);
            }

            var analysisDocument = context.AnalysisDocument;

            if (analysisDocument == null)
            {
                return;
            }
            using (var undo = editor.OpenUndoGroup(/*OperationType.Format*/)) {
                try {
                    var syntaxTree = analysisDocument.GetSyntaxTreeAsync().Result;

                    if (formatLastStatementOnly)
                    {
                        var root   = syntaxTree.GetRoot();
                        var token  = root.FindToken(endOffset);
                        var tokens = ICSharpCode.NRefactory6.CSharp.FormattingRangeHelper.FindAppropriateRange(token);
                        if (tokens.HasValue)
                        {
                            span = new TextSpan(tokens.Value.Item1.SpanStart, tokens.Value.Item2.Span.End - tokens.Value.Item1.SpanStart);
                        }
                        else
                        {
                            var parent = token.Parent;
                            if (parent != null)
                            {
                                span = parent.FullSpan;
                            }
                        }
                    }

                    if (optionSet == null)
                    {
                        var policy     = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain);
                        var textPolicy = policyParent.Get <TextStylePolicy> (mimeTypeChain);
                        optionSet = policy.CreateOptions(textPolicy);
                    }
                    var doc     = Formatter.FormatAsync(analysisDocument, span, optionSet).Result;
                    var newTree = doc.GetSyntaxTreeAsync().Result;
                    ApplyNewTree(editor, startOffset, exact, span, syntaxTree, newTree);
                } catch (Exception e) {
                    LoggingService.LogError("Error in on the fly formatter", e);
                }
            }
        }
Exemplo n.º 18
0
        protected override Core.Text.ITextSource FormatImplementation(PolicyContainer policyParent, string mimeType, Core.Text.ITextSource input, int startOffset, int length)
        {
            if (policyParent == null)
            {
                policyParent = PolicyService.DefaultPolicies;
            }
            var txtPol = policyParent.Get <TextStylePolicy> (mimeType);
            var xmlPol = policyParent.Get <XmlFormattingPolicy> (mimeType);

            return(new StringTextSource(FormatXml(txtPol, xmlPol, input.Text)));
        }
Exemplo n.º 19
0
        protected override async void CorrectIndentingImplementation(PolicyContainer policyParent, TextEditor editor, int line)
        {
            var lineSegment = editor.GetLine(line);

            if (lineSegment == null)
            {
                return;
            }

            try {
                Microsoft.CodeAnalysis.Options.OptionSet options = null;

                foreach (var doc in IdeApp.Workbench.Documents)
                {
                    if (doc.Editor == editor)
                    {
                        options = await doc.AnalysisDocument?.GetOptionsAsync();

                        break;
                    }
                }

                if (options == null)
                {
                    var policy     = policyParent.Get <CSharpFormattingPolicy> (MimeType);
                    var textpolicy = policyParent.Get <TextStylePolicy> (MimeType);
                    options = policy.CreateOptions(textpolicy);
                }

                var tracker = new CSharpIndentEngine(options);

                tracker.Update(IdeApp.Workbench.ActiveDocument.Editor, lineSegment.Offset);
                for (int i = lineSegment.Offset; i < lineSegment.Offset + lineSegment.Length; i++)
                {
                    tracker.Push(editor.GetCharAt(i));
                }

                string curIndent = lineSegment.GetIndentation(editor);

                int nlwsp = curIndent.Length;
                if (!tracker.LineBeganInsideMultiLineComment || (nlwsp < lineSegment.LengthIncludingDelimiter && editor.GetCharAt(lineSegment.Offset + nlwsp) == '*'))
                {
                    // Possibly replace the indent
                    string newIndent = tracker.ThisLineIndent;
                    if (newIndent != curIndent)
                    {
                        editor.ReplaceText(lineSegment.Offset, nlwsp, newIndent);
                    }
                }
            } catch (Exception e) {
                LoggingService.LogError("Error while indenting", e);
            }
        }
Exemplo n.º 20
0
		public string FormatText (PolicyContainer policyParent, string mimeType, string input)
		{
			TextStylePolicy policy;
			if (policyParent != null)
				policy = policyParent.Get <TextStylePolicy> (DesktopService.GetMimeTypeInheritanceChain (mimeType));
			else
				policy = PolicyService.GetDefaultPolicy <TextStylePolicy> (DesktopService.GetMimeTypeInheritanceChain (mimeType));
			
			XmlTextReader reader = new XmlTextReader (new StringReader (input));
			reader.WhitespaceHandling = WhitespaceHandling.None;
			
			StringWriter indentedXmlWriter = new StringWriter ();
			XmlWriterSettings settings = new XmlWriterSettings ();
			settings.Indent = true;
			if (policy.TabsToSpaces) {
				settings.IndentChars = new string (' ', policy.TabWidth);
			} else {
				settings.IndentChars = "\t";
			}
			settings.NewLineChars = policy.GetEolMarker ();
			
			try {
				XmlWriter xmlWriter = XmlTextWriter.Create (indentedXmlWriter, settings);
				xmlWriter.WriteNode (reader, false);
				xmlWriter.Flush ();
			} catch {
				// Ignore malfored xml
				return input;
			}

			return indentedXmlWriter.ToString ();
		}
Exemplo n.º 21
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);
            }
        }
Exemplo n.º 22
0
        static AstFormattingVisitor GetFormattingChanges(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, MonoDevelop.Ide.Gui.Document document, string input, DomRegion formattingRegion)
        {
            using (var stubData = TextEditorData.CreateImmutable(input)) {
                stubData.Document.FileName = document.FileName;
                var  parser          = document.HasProject ? new ICSharpCode.NRefactory.CSharp.CSharpParser(TypeSystemParser.GetCompilerArguments(document.Project)) : new ICSharpCode.NRefactory.CSharp.CSharpParser();
                var  compilationUnit = parser.Parse(stubData);
                bool hadErrors       = parser.HasErrors;
                if (hadErrors)
                {
                    using (var stubData2 = TextEditorData.CreateImmutable(input + "}")) {
                        compilationUnit = parser.Parse(stubData2);
                        hadErrors       = parser.HasErrors;
                    }
                }

                // try it out, if the behavior is better when working only with correct code.
                if (hadErrors)
                {
                    return(null);
                }

                var policy = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain);

                var formattingVisitor = new AstFormattingVisitor(policy.CreateOptions(), stubData.Document, document.Editor.CreateNRefactoryTextEditorOptions())
                {
                    HadErrors        = hadErrors,
                    FormattingRegion = formattingRegion
                };

                compilationUnit.AcceptVisitor(formattingVisitor);
                return(formattingVisitor);
            }
        }
Exemplo n.º 23
0
        public override void OnTheFlyFormat(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain,
                                            TextEditorData data, int startOffset, int endOffset)
        {
            var  parser            = new MonoDevelop.CSharp.Parser.CSharpParser();
            var  compilationUnit   = parser.Parse(data);
            bool hadErrors         = parser.ErrorReportPrinter.ErrorsCount + parser.ErrorReportPrinter.FatalCounter > 0;
            var  policy            = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain);
            var  domSpacingVisitor = new AstSpacingVisitor(policy, data)
            {
                AutoAcceptChanges = false,
            };

            compilationUnit.AcceptVisitor(domSpacingVisitor, null);

            var domIndentationVisitor = new AstIndentationVisitor(policy, data)
            {
                AutoAcceptChanges = false,
                HadErrors         = hadErrors
            };

            compilationUnit.AcceptVisitor(domIndentationVisitor, null);

            var changes = new List <Change> ();

            changes.AddRange(domSpacingVisitor.Changes.
                             Concat(domIndentationVisitor.Changes).
                             Where(c => c is TextReplaceChange && (startOffset <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset < endOffset)));

            RefactoringService.AcceptChanges(null, null, changes);
        }
Exemplo n.º 24
0
 T GetCurrentValue()
 {
     if (policyUndefined)
     {
         return(null);
     }
     return(policyContainer.Get <T> () ?? GetDefaultValue());
 }
Exemplo n.º 25
0
        static FormattingChanges GetFormattingChanges(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, MonoDevelop.Ide.Gui.Document document, string input, DomRegion formattingRegion, ref int formatStartOffset, ref int formatLength, bool formatLastStatementOnly)
        {
            using (var stubData = TextEditorData.CreateImmutable(input)) {
                stubData.Document.FileName = document.FileName;
                var  parser          = document.HasProject ? new CSharpParser(TypeSystemParser.GetCompilerArguments(document.Project)) : new CSharpParser();
                var  compilationUnit = parser.Parse(stubData);
                bool hadErrors       = parser.HasErrors;
                if (hadErrors)
                {
                    using (var stubData2 = TextEditorData.CreateImmutable(input + "}")) {
                        compilationUnit = parser.Parse(stubData2);
                        hadErrors       = parser.HasErrors;
                    }
                }
                // try it out, if the behavior is better when working only with correct code.
                if (hadErrors)
                {
                    return(null);
                }

                var policy = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain);

                var formattingVisitor = new ICSharpCode.NRefactory.CSharp.CSharpFormatter(policy.CreateOptions(), document.Editor.CreateNRefactoryTextEditorOptions());
                formattingVisitor.FormattingMode = FormattingMode.Intrusive;
                formattingVisitor.AddFormattingRegion(formattingRegion);


                var changes = formattingVisitor.AnalyzeFormatting(stubData.Document, compilationUnit);

                if (formatLastStatementOnly)
                {
                    AstNode node = compilationUnit.GetAdjacentNodeAt <Statement> (stubData.OffsetToLocation(formatStartOffset + formatLength - 1));
                    if (node != null)
                    {
                        while (node.Role == Roles.EmbeddedStatement || node.Role == IfElseStatement.TrueRole || node.Role == IfElseStatement.FalseRole)
                        {
                            node = node.Parent;
                        }
                        // include indentation if node starts in new line
                        var formatNode = node.GetPrevNode();
                        if (formatNode.Role != Roles.NewLine)
                        {
                            formatNode = node;
                        }
                        var start = stubData.LocationToOffset(formatNode.StartLocation);
                        if (start > formatStartOffset)
                        {
                            var end = stubData.LocationToOffset(node.EndLocation);
                            formatStartOffset = start;
                            formatLength      = end - start;
                        }
                    }
                }
                return(changes);
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Used for formatting the entire document
        /// </summary>
        public override string FormatText(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, string input, int startOffset, int endOffset)
        {
            var policy     = policyParent.Get <DFormattingPolicy> (mimeTypeChain);
            var textPolicy = policyParent.Get <TextStylePolicy> (mimeTypeChain);
            var data       = new TextEditorData {
                Text = input
            };

            if (IndentCorrectionOnly)
            {
                using (data.Document.OpenUndoGroup())
                    using (var s = data.OpenStream())
                        using (var r = new StreamReader(s))
                            D_Parser.Formatting.Indent.IndentEngineWrapper.CorrectIndent(r,
                                                                                         startOffset, endOffset,
                                                                                         data.Document.Replace, policy.Options,
                                                                                         new TextStyleAdapter(textPolicy)
                            {
                                KeepAlignmentSpaces = policy.KeepAlignmentSpaces
                            });
                return(data.Text);
            }

            var ast = DParser.ParseString(input, false, true);
            var formattingVisitor = new DFormattingVisitor(policy.Options, new DocAdapt(data.Document), ast, new TextStyleAdapter(textPolicy));

            // Only clip to a region if it's necessary
            if (startOffset > 0 || endOffset < input.Length - 1)
            {
                formattingVisitor.CheckFormattingBoundaries = true;
                var dl = data.Document.OffsetToLocation(startOffset);
                formattingVisitor.FormattingStartLocation = new CodeLocation(dl.Column, dl.Line);
                dl = data.Document.OffsetToLocation(endOffset);
                formattingVisitor.FormattingEndLocation = new CodeLocation(dl.Column, dl.Line);
            }

            formattingVisitor.WalkThroughAst();

            using (data.Document.OpenUndoGroup())
                formattingVisitor.ApplyChanges(data.Document.Replace);

            return(data.Text);
        }
        T GetCurrentPolicy()
        {
            object pol = null;

            if (loaded)
            {
                pol = GetPolicy();
            }
            else if (hasCachedPolicy)
            {
                pol = cachedPolicy;
            }

            if (pol == null)
            {
                pol = policyContainer.Get <T> (mimeTypeScopes) ?? PolicyService.GetDefaultPolicy <T> (mimeTypeScopes);
            }
            return((T)pol);
        }
Exemplo n.º 28
0
 T GetDefaultValue()
 {
     if (defaultPolicyContainer != null)
     {
         return(defaultPolicyContainer.Get <T> ());
     }
     else
     {
         return(PolicyService.GetDefaultPolicy <T> ());
     }
 }
Exemplo n.º 29
0
        public static void SetFormatOptions(CSharpOutputVisitor outputVisitor, PolicyContainer policyParent)
        {
            IEnumerable <string> types         = DesktopService.GetMimeTypeInheritanceChain(MimeType);
            TextStylePolicy      currentPolicy = policyParent != null?policyParent.Get <TextStylePolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy> (types);

            CSharpFormattingPolicy codePolicy = policyParent != null?policyParent.Get <CSharpFormattingPolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <CSharpFormattingPolicy> (types);

            outputVisitor.Options.IndentationChar = currentPolicy.TabsToSpaces ? ' ' : '\t';
            outputVisitor.Options.TabSize         = currentPolicy.TabWidth;
            outputVisitor.Options.IndentSize      = currentPolicy.TabWidth;
            outputVisitor.Options.EolMarker       = TextStylePolicy.GetEolMarker(currentPolicy.EolMarker);

            CodeFormatDescription descr = CSharpFormattingPolicyPanel.CodeFormatDescription;
            Type optionType             = outputVisitor.Options.GetType();

            foreach (CodeFormatOption option in descr.AllOptions)
            {
                KeyValuePair <string, string> val = descr.GetValue(codePolicy, option);
                PropertyInfo info = optionType.GetProperty(option.Name);
                if (info == null)
                {
                    System.Console.WriteLine("option : " + option.Name + " not found.");
                    continue;
                }
                object cval = null;
                if (info.PropertyType.IsEnum)
                {
                    cval = Enum.Parse(info.PropertyType, val.Key);
                }
                else if (info.PropertyType == typeof(bool))
                {
                    cval = Convert.ToBoolean(val.Key);
                }
                else
                {
                    cval = Convert.ChangeType(val.Key, info.PropertyType);
                }
                //System.Console.WriteLine("set " + option.Name + " to " + cval);
                info.SetValue(outputVisitor.Options, cval, null);
            }
        }
Exemplo n.º 30
0
        protected override ITextSource FormatImplementation(PolicyContainer policyParent, string mimeType, ITextSource input, int startOffset, int length)
        {
            var chain      = IdeServices.DesktopService.GetMimeTypeInheritanceChain(mimeType);
            var policy     = policyParent.Get <CSharpFormattingPolicy> (chain);
            var textPolicy = policyParent.Get <TextStylePolicy> (chain);
            var optionSet  = policy.CreateOptions(textPolicy);

            if (input is IReadonlyTextDocument doc)
            {
                try {
                    var conventions = EditorConfigService.GetEditorConfigContext(doc.FileName).WaitAndGetResult();
                    if (conventions != null)
                    {
                        optionSet = new FormattingDocumentOptionSet(optionSet, new DocumentOptions(optionSet, conventions.CurrentConventions));
                    }
                } catch (Exception e) {
                    LoggingService.LogError("Error while loading coding conventions.", e);
                }
            }

            return(new StringTextSource(FormatText(optionSet, input.Text, startOffset, startOffset + length)));
        }
Exemplo n.º 31
0
        protected override string InternalFormat(PolicyContainer policyParent, string mimeType, string input, int startOffset, int endOffset)
        {
            IEnumerable <string> mtypes        = DesktopService.GetMimeTypeInheritanceChain(mimeType);
            TextStylePolicy      currentPolicy = policyParent != null
                                        ? policyParent.Get <TextStylePolicy> (mtypes)
                                        : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy> (mtypes);

            input = input ?? "";
            int           line = 0, col = 0;
            string        eolMarker = currentPolicy.GetEolMarker();
            StringBuilder result    = new StringBuilder();

            for (int i = startOffset; i <= endOffset; i++)
            {
                char ch = input[i];
                switch (ch)
                {
                case '\t':
                    if (currentPolicy.TabsToSpaces)
                    {
                        int tabWidth = GetNextTabstop(col, currentPolicy.TabWidth) - col;
                        result.Append(new string (' ', tabWidth));
                        col += tabWidth;
                    }
                    else
                    {
                        goto default;
                    }
                    break;

                case '\r':
                    if (i + 1 < input.Length && input[i + 1] == '\n')
                    {
                        i++;
                    }
                    goto case '\n';

                case '\n':
                    result.Append(eolMarker);
                    line++;
                    col = 0;
                    break;

                default:
                    result.Append(ch);
                    col++;
                    break;
                }
            }
            return(result.ToString());
        }
Exemplo n.º 32
0
        static void SetFormatOptions(CSharpOutputVisitor outputVisitor, PolicyContainer policyParent)
        {
            IEnumerable <string> types         = DesktopService.GetMimeTypeInheritanceChain(CSharpFormatter.MimeType);
            TextStylePolicy      currentPolicy = policyParent != null?policyParent.Get <TextStylePolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy> (types);

            CSharpFormattingPolicy codePolicy = policyParent != null?policyParent.Get <CSharpFormattingPolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <CSharpFormattingPolicy> (types);

            outputVisitor.Options.IndentationChar = currentPolicy.TabsToSpaces ? ' ' : '\t';
            outputVisitor.Options.TabSize         = currentPolicy.TabWidth;
            outputVisitor.Options.IndentSize      = currentPolicy.TabWidth;

            outputVisitor.Options.EolMarker = TextStylePolicy.GetEolMarker(currentPolicy.EolMarker);
            Type optionType = outputVisitor.Options.GetType();

            foreach (var property in typeof(CSharpFormattingPolicy).GetProperties())
            {
                PropertyInfo info = optionType.GetProperty(property.Name);
                if (info == null)
                {
                    continue;
                }
                object val  = property.GetValue(codePolicy, null);
                object cval = null;
                if (info.PropertyType.IsEnum)
                {
                    cval = Enum.Parse(info.PropertyType, val.ToString());
                }
                else if (info.PropertyType == typeof(bool))
                {
                    cval = Convert.ToBoolean(val);
                }
                else
                {
                    cval = Convert.ChangeType(val, info.PropertyType);
                }
                info.SetValue(outputVisitor.Options, cval, null);
            }
        }
Exemplo n.º 33
0
        public override string FormatText(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain,
                                          string input, int startOffset, int endOffset)
        {
            var currentPolicy = policyParent.Get <TextStylePolicy> (mimeTypeChain);

            input = input ?? "";
            int    line = 0, col = 0;
            string eolMarker = currentPolicy.GetEolMarker();
            var    result    = new StringBuilder();

            for (int i = startOffset; i < endOffset && i < input.Length; i++)
            {
                char ch = input[i];
                switch (ch)
                {
                case '\t':
                    if (currentPolicy.TabsToSpaces)
                    {
                        int tabWidth = GetNextTabstop(col, currentPolicy.TabWidth) - col;
                        result.Append(new string (' ', tabWidth));
                        col += tabWidth;
                    }
                    else
                    {
                        goto default;
                    }
                    break;

                case '\r':
                    if (i + 1 < input.Length && input[i + 1] == '\n')
                    {
                        i++;
                    }
                    goto case '\n';

                case '\n':
                    result.Append(eolMarker);
                    line++;
                    col = 0;
                    break;

                default:
                    result.Append(ch);
                    col++;
                    break;
                }
            }
            return(result.ToString());
        }
Exemplo n.º 34
0
        protected override ITextSource FormatImplementation(PolicyContainer policyParent, string mimeType, ITextSource input, int startOffset, int length)
        {
            var currentPolicy = policyParent.Get <TextStylePolicy> (mimeType);

            int    line = 0, col = 0;
            string eolMarker = currentPolicy.GetEolMarker();
            var    result    = new StringBuilder();
            var    endOffset = startOffset + length;

            for (int i = startOffset; i < endOffset && i < input.Length; i++)
            {
                char ch = input[i];
                switch (ch)
                {
                case '\t':
                    if (currentPolicy.TabsToSpaces)
                    {
                        int tabWidth = GetNextTabstop(col, currentPolicy.TabWidth) - col;
                        result.Append(new string (' ', tabWidth));
                        col += tabWidth;
                    }
                    else
                    {
                        goto default;
                    }
                    break;

                case '\r':
                    if (i + 1 < input.Length && input[i + 1] == '\n')
                    {
                        i++;
                    }
                    goto case '\n';

                case '\n':
                    result.Append(eolMarker);
                    line++;
                    col = 0;
                    break;

                default:
                    result.Append(ch);
                    col++;
                    break;
                }
            }

            return(new StringTextSource(result.ToString(), input.Encoding, input.UseBOM));
        }
Exemplo n.º 35
0
        public string FormatText(PolicyContainer policyParent, string mimeType, string input)
        {
            TextStylePolicy policy;

            if (policyParent != null)
            {
                policy = policyParent.Get <TextStylePolicy> (DesktopService.GetMimeTypeInheritanceChain(mimeType));
            }
            else
            {
                policy = PolicyService.GetDefaultPolicy <TextStylePolicy> (DesktopService.GetMimeTypeInheritanceChain(mimeType));
            }

            XmlTextReader reader = new XmlTextReader(new StringReader(input));

            reader.WhitespaceHandling = WhitespaceHandling.None;

            StringWriter      indentedXmlWriter = new StringWriter();
            XmlWriterSettings settings          = new XmlWriterSettings();

            settings.Indent = true;
            if (policy.TabsToSpaces)
            {
                settings.IndentChars = new string (' ', policy.TabWidth);
            }
            else
            {
                settings.IndentChars = "\t";
            }
            settings.NewLineChars = policy.GetEolMarker();

            try {
                XmlWriter xmlWriter = XmlTextWriter.Create(indentedXmlWriter, settings);
                xmlWriter.WriteNode(reader, false);
                xmlWriter.Flush();
            } catch {
                // Ignore malfored xml
                return(input);
            }

            return(indentedXmlWriter.ToString());
        }
Exemplo n.º 36
0
		public static void Format (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain,
			TextEditorData data, ProjectDom dom, DomLocation location, bool correctBlankLines)
		{
			var compilationUnit = new MonoDevelop.CSharp.Parser.CSharpParser ().Parse (data);
			var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
			var domSpacingVisitor = new DomSpacingVisitor (policy, data) {
				AutoAcceptChanges = false,
			};
			compilationUnit.AcceptVisitor (domSpacingVisitor, null);
			
			var domIndentationVisitor = new DomIndentationVisitor (policy, data) {
				AutoAcceptChanges = false,
			};
			domIndentationVisitor.CorrectBlankLines = correctBlankLines;
			compilationUnit.AcceptVisitor (domIndentationVisitor, null);
			
			var changes = new List<Change> ();
			changes.AddRange (domSpacingVisitor.Changes);
			changes.AddRange (domIndentationVisitor.Changes);
			RefactoringService.AcceptChanges (null, null, changes);
		}
		protected override string InternalFormat (PolicyContainer policyParent, string mimeType, string input, int startOffset, int endOffset)
		{
			IEnumerable<string> mtypes = DesktopService.GetMimeTypeInheritanceChain (mimeType);
			TextStylePolicy currentPolicy = policyParent != null
					? policyParent.Get<TextStylePolicy> (mtypes)
					: MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<TextStylePolicy> (mtypes);
			
			input = input ?? "";
			int line = 0, col = 0;
			string eolMarker = currentPolicy.GetEolMarker ();
			StringBuilder result = new StringBuilder ();
			
			for (int i = startOffset; i <= endOffset; i++) {
				char ch = input[i];
				switch (ch) {
				case '\t':
					if (currentPolicy.TabsToSpaces) {
						int tabWidth = GetNextTabstop (col, currentPolicy.TabWidth) - col;
						result.Append (new string (' ', tabWidth));
						col += tabWidth;
					} else 
						goto default;
					break;
				case '\r':
					if (i + 1 < input.Length && input[i + 1] == '\n')
						i++;
					goto case '\n';
				case '\n':
					result.Append (eolMarker);
					line++;
					col = 0;
					break;
				default:
					result.Append (ch);
					col++;
					break;
				}
			}
			return result.ToString ();
		}
Exemplo n.º 38
0
		public override string FormatText (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain,
			string input, int startOffset, int endOffset)
		{
			var currentPolicy = policyParent.Get<TextStylePolicy> (mimeTypeChain);
			
			input = input ?? "";
			int line = 0, col = 0;
			string eolMarker = currentPolicy.GetEolMarker ();
			var result = new StringBuilder ();
			
			for (int i = startOffset; i <= endOffset && i < input.Length; i++) {
				char ch = input[i];
				switch (ch) {
				case '\t':
					if (currentPolicy.TabsToSpaces) {
						int tabWidth = GetNextTabstop (col, currentPolicy.TabWidth) - col;
						result.Append (new string (' ', tabWidth));
						col += tabWidth;
					} else 
						goto default;
					break;
				case '\r':
					if (i + 1 < input.Length && input[i + 1] == '\n')
						i++;
					goto case '\n';
				case '\n':
					result.Append (eolMarker);
					line++;
					col = 0;
					break;
				default:
					result.Append (ch);
					col++;
					break;
				}
			}
			return result.ToString ();
		}
		protected override ITextSource FormatImplementation (PolicyContainer policyParent, string mimeType, ITextSource input, int startOffset, int length)
		{
			var currentPolicy = policyParent.Get<TextStylePolicy> (mimeType);
			
			int line = 0, col = 0;
			string eolMarker = currentPolicy.GetEolMarker ();
			var result = new StringBuilder ();
			var endOffset = startOffset + length;
			for (int i = startOffset; i < endOffset && i < input.Length; i++) {
				char ch = input[i];
				switch (ch) {
				case '\t':
					if (currentPolicy.TabsToSpaces) {
						int tabWidth = GetNextTabstop (col, currentPolicy.TabWidth) - col;
						result.Append (new string (' ', tabWidth));
						col += tabWidth;
					} else 
						goto default;
					break;
				case '\r':
					if (i + 1 < input.Length && input[i + 1] == '\n')
						i++;
					goto case '\n';
				case '\n':
					result.Append (eolMarker);
					line++;
					col = 0;
					break;
				default:
					result.Append (ch);
					col++;
					break;
				}
			}

			return new StringTextSource (result.ToString (), input.Encoding, input.UseBOM);
		}
        void IMimeTypePolicyOptionsPanel.LoadSetPolicy(PolicyContainer pset)
        {
            object selected = pset.Get <T> (mimeTypeScopes);

            if (selected == null)
            {
                selected = PolicyService.GetDefaultPolicy <T> (mimeTypeScopes);
            }

            if (loaded)
            {
                if (defaultSettingsButton != null)
                {
                    defaultSettingsButton.Active = false;
                    panelWidget.Sensitive        = true;
                }
                LoadFrom((T)selected);
            }
            else
            {
                cachedPolicy    = selected;
                hasCachedPolicy = true;
            }
        }
Exemplo n.º 41
0
		public static string SaveFormattedXml (PolicyContainer policies, AddinDescription adesc)
		{
			XmlDocument doc = adesc.SaveToXml ();
			
			TextStylePolicy textPolicy = policies.Get<TextStylePolicy> (DesktopService.GetMimeTypeInheritanceChain ("application/x-addin+xml"));
			XmlFormattingPolicy xmlPolicy = policies.Get<XmlFormattingPolicy> (DesktopService.GetMimeTypeInheritanceChain ("application/x-addin+xml"));
			
			return XmlFormatter.FormatXml (textPolicy, xmlPolicy, doc.OuterXml);
		}
Exemplo n.º 42
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 ();
		}
Exemplo n.º 43
0
		public string FormatText (PolicyContainer policyParent, string mimeType, string input)
		{
			XmlFormattingPolicy xmlPol = policyParent.Get<XmlFormattingPolicy> (mimeType);
			TextStylePolicy txtPol = policyParent.Get<TextStylePolicy> (mimeType);
			return FormatXml (txtPol, xmlPol, input);
		}
		static AstFormattingVisitor GetFormattingChanges (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, MonoDevelop.Ide.Gui.Document document, string input, DomRegion formattingRegion, ref int formatStartOffset, ref int formatLength, bool formatLastStatementOnly)
		{
			using (var stubData = TextEditorData.CreateImmutable (input)) {
				stubData.Document.FileName = document.FileName;
				var parser = document.HasProject ? new PlayScriptParser (TypeSystemParser.GetCompilerArguments (document.Project)) : new PlayScriptParser ();
				var compilationUnit = parser.Parse (stubData);
				bool hadErrors = parser.HasErrors;
				if (hadErrors) {
					using (var stubData2 = TextEditorData.CreateImmutable (input + "}")) {
						compilationUnit = parser.Parse (stubData2);
						hadErrors = parser.HasErrors;
					}
				}
				// try it out, if the behavior is better when working only with correct code.
				if (hadErrors) {
					return null;
				}
				
				var policy = policyParent.Get<PlayScriptFormattingPolicy> (mimeTypeChain);
				
				var formattingVisitor = new AstFormattingVisitor (policy.CreateOptions (), stubData.Document, document.Editor.CreateNRefactoryTextEditorOptions ()) {
					HadErrors = hadErrors,
				};
				formattingVisitor.AddFormattingRegion (formattingRegion);

				compilationUnit.AcceptVisitor (formattingVisitor);

				if (formatLastStatementOnly) {
					AstNode node = compilationUnit.GetAdjacentNodeAt<Statement> (stubData.OffsetToLocation (formatStartOffset + formatLength - 1));
					if (node != null) {
						while (node.Role == Roles.EmbeddedStatement || node.Role == IfElseStatement.TrueRole || node.Role == IfElseStatement.FalseRole)
							node = node.Parent;
						var start = stubData.LocationToOffset (node.StartLocation);
						if (start > formatStartOffset) {
							var end = stubData.LocationToOffset (node.EndLocation);
							formatStartOffset = start;
							formatLength = end - start;
						}
					}
				}
				return formattingVisitor;
			}
		}
Exemplo n.º 45
0
		public string FormatText (PolicyContainer policyParent, IEnumerable<string> mimeTypeInheritanceChain, string input)
		{
			var txtPol = policyParent.Get<TextStylePolicy> (mimeTypeInheritanceChain);
			var xmlPol = policyParent.Get<XmlFormattingPolicy> (mimeTypeInheritanceChain);
			return FormatXml (txtPol, xmlPol, input);
		}
Exemplo n.º 46
0
		public static void Format (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, 
			MonoDevelop.Ide.Gui.Document data, ProjectDom dom, DomLocation location, bool correctBlankLines, bool runAferCR = false)
		{
			var unit = data.ParsedDocument.CompilationUnit.Tag as MonoDevelop.CSharp.Ast.CompilationUnit;
			if (unit == null)
				return;

			AstLocation loc = new AstLocation (location.Line + (runAferCR ? -1 : 0), location.Column);
			AstNode member = null;
			foreach (AstNode node in MonoDevelop.CSharp.Ast.Utils.TreeTraversal.PreOrder (unit.Children, n => n.Parent != null && n.Parent.NodeType == NodeType.TypeDeclaration ? Enumerable.Empty<AstNode> () : n.Children)) {
				if (node.NodeType != NodeType.Member)
					continue;
				if (node.StartLocation < loc && loc <= node.EndLocation) {
					member = node;
					break;
				}
			}
			if (member == null)
				return;
			StringBuilder sb = new StringBuilder ();
			int closingBrackets = 0;
			var parent = member.Parent;
			while (parent != null) {
				if (parent.NodeType == NodeType.TypeDeclaration) {
					sb.Insert (0, "class Stub {");
					closingBrackets++;
				} else if (parent is NamespaceDeclaration) {
					sb.Insert (0, "namespace Stub {");
					closingBrackets++;
				}
				parent = parent.Parent;
			}
			sb.AppendLine ();
			System.Console.WriteLine ("caret offset:" + data.Editor.Caret.Offset);
			System.Console.WriteLine (data.Editor.Length);
			int startOffset = sb.Length;
			sb.Append (data.Editor.GetTextBetween (member.StartLocation.Line, 1, member.EndLocation.Line + (runAferCR ? 1 : 0), member.EndLocation.Column));
			int endOffset = sb.Length;
			sb.AppendLine ();
			sb.Append (new string ('}', closingBrackets));

			TextEditorData stubData = new TextEditorData () { Text = sb.ToString () };
			stubData.Document.FileName = data.FileName;
			var compilationUnit = new MonoDevelop.CSharp.Parser.CSharpParser ().Parse (stubData);

			var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
			var domSpacingVisitor = new AstSpacingVisitor (policy, stubData) {
				AutoAcceptChanges = false,
			};
			compilationUnit.AcceptVisitor (domSpacingVisitor, null);

			var domIndentationVisitor = new AstIndentationVisitor (policy, stubData) {
				AutoAcceptChanges = false,
			};
			domIndentationVisitor.CorrectBlankLines = correctBlankLines;
			compilationUnit.AcceptVisitor (domIndentationVisitor, null);

			var changes = new List<Change> ();
			changes.AddRange (domSpacingVisitor.Changes.Cast<TextReplaceChange> ().Where (c => startOffset < c.Offset && c.Offset < endOffset));
			changes.AddRange (domIndentationVisitor.Changes.Cast<TextReplaceChange> ().Where (c => startOffset < c.Offset && c.Offset < endOffset));
			int delta = data.Editor.LocationToOffset (member.StartLocation.Line, 1) - startOffset;
			HashSet<int> lines = new HashSet<int> ();
			foreach (TextReplaceChange change in changes) {
				if (change is AstSpacingVisitor.MyTextReplaceChange) 
					((AstSpacingVisitor.MyTextReplaceChange)change).SetTextEditorData (data.Editor);
				change.Offset += delta;
				lines.Add (data.Editor.OffsetToLineNumber (change.Offset));
			}
			RefactoringService.AcceptChanges (null, null, changes);
			foreach (int line in lines)
				data.Editor.Document.CommitLineUpdate (line);
			stubData.Dispose ();
		}
Exemplo n.º 47
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);
			}
		}
Exemplo n.º 48
0
		protected override string InternalFormat (PolicyContainer policyParent, string mimeType, string input, int startOffset, int endOffset)
		{
			IEnumerable<string> types = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType);
			
			TextEditorData data = new TextEditorData ();
			data.Text = input;
			data.Document.MimeType = mimeType;
			data.Document.SuppressHighlightUpdate = true;
			data.Document.FileName = "toformat.cs";
			var textPolicy = policyParent != null ? policyParent.Get<TextStylePolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<TextStylePolicy> (types);
			data.Options.TabsToSpaces = textPolicy.TabsToSpaces;
			data.Options.TabSize = textPolicy.TabWidth;
			data.Options.OverrideDocumentEolMarker = true;
			data.Options.DefaultEolMarker = textPolicy.GetEolMarker ();
			
			endOffset += CorrectFormatting (data, startOffset, endOffset);
			
			CSharp.Dom.CompilationUnit compilationUnit = new MonoDevelop.CSharp.Parser.CSharpParser ().Parse (data);
			CSharpFormattingPolicy policy = policyParent != null ? policyParent.Get<CSharpFormattingPolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<CSharpFormattingPolicy> (types);
			
			DomSpacingVisitor domSpacingVisitor = new DomSpacingVisitor (policy, data);
			domSpacingVisitor.AutoAcceptChanges = false;
			compilationUnit.AcceptVisitor (domSpacingVisitor, null);
			
			DomIndentationVisitor domIndentationVisitor = new DomIndentationVisitor (policy, data);
			domIndentationVisitor.AutoAcceptChanges = false;
			compilationUnit.AcceptVisitor (domIndentationVisitor, null);
			
			List<Change> changes = new List<Change> ();
			
			changes.AddRange (domSpacingVisitor.Changes.
				Concat (domIndentationVisitor.Changes).
				Where (c => c is TextReplaceChange && (startOffset <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset < endOffset)));
			
			RefactoringService.AcceptChanges (null, null, changes);
			int end = endOffset;
			foreach (TextReplaceChange c in changes) {
				end -= c.RemovedChars;
				if (c.InsertedText != null)
					end += c.InsertedText.Length;
			}
			string result = data.GetTextBetween (startOffset, end);
			return result;
		}
Exemplo n.º 49
0
		public override string FormatText (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain,
			string input, int startOffset, int endOffset)
		{
			var data = new TextEditorData ();
			data.Document.SuppressHighlightUpdate = true;
			data.Document.MimeType = mimeTypeChain.First ();
			data.Document.FileName = "toformat.cs";
			var textPolicy = policyParent.Get<TextStylePolicy> (mimeTypeChain);
			data.Options.TabsToSpaces = textPolicy.TabsToSpaces;
			data.Options.TabSize = textPolicy.TabWidth;
			data.Options.OverrideDocumentEolMarker = true;
			data.Options.DefaultEolMarker = textPolicy.GetEolMarker ();
			data.Text = input;

			//			System.Console.WriteLine ("TABS:" + textPolicy.TabsToSpaces);
			endOffset += CorrectFormatting (data, startOffset, endOffset);
			
			/*			System.Console.WriteLine ("-----");
			System.Console.WriteLine (data.Text.Replace (" ", ".").Replace ("\t", "->"));
			System.Console.WriteLine ("-----");*/

			var compilationUnit = new MonoDevelop.CSharp.Parser.CSharpParser ().Parse (data);
			var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);

			var domSpacingVisitor = new AstSpacingVisitor (policy, data) {
				AutoAcceptChanges = false,
			};
			compilationUnit.AcceptVisitor (domSpacingVisitor, null);

			var domIndentationVisitor = new AstIndentationVisitor (policy, data) {
				AutoAcceptChanges = false,
			};
			compilationUnit.AcceptVisitor (domIndentationVisitor, null);

			var changes = new List<Change> ();

			changes.AddRange (domSpacingVisitor.Changes.
				Concat (domIndentationVisitor.Changes).
				Where (c => c is TextReplaceChange && (startOffset <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset < endOffset)));

			RefactoringService.AcceptChanges (null, null, changes);
			int end = endOffset;
			foreach (TextReplaceChange 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;
		}
Exemplo n.º 50
0
		static FormattingChanges GetFormattingChanges (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, MonoDevelop.Ide.Gui.Document document, string input, DomRegion formattingRegion, ref int formatStartOffset, ref int formatLength, bool formatLastStatementOnly)
		{
			using (var stubData = TextEditorData.CreateImmutable (input)) {
				stubData.Document.FileName = document.FileName;
				var parser = document.HasProject ? new CSharpParser (TypeSystemParser.GetCompilerArguments (document.Project)) : new CSharpParser ();
				var compilationUnit = parser.Parse (stubData);
				bool hadErrors = parser.HasErrors;
				if (hadErrors) {
					using (var stubData2 = TextEditorData.CreateImmutable (input + "}")) {
						compilationUnit = parser.Parse (stubData2);
						hadErrors = parser.HasErrors;
					}
				}
				// try it out, if the behavior is better when working only with correct code.
				if (hadErrors) {
					return null;
				}
				
				var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
				
				var formattingVisitor = new ICSharpCode.NRefactory.CSharp.CSharpFormatter (policy.CreateOptions (), document.Editor.CreateNRefactoryTextEditorOptions ());
				formattingVisitor.FormattingMode = FormattingMode.Intrusive;
				formattingVisitor.AddFormattingRegion (formattingRegion);


				var changes = formattingVisitor.AnalyzeFormatting (stubData.Document, compilationUnit);

				if (formatLastStatementOnly) {
					AstNode node = compilationUnit.GetAdjacentNodeAt<Statement> (stubData.OffsetToLocation (formatStartOffset + formatLength - 1));
					if (node != null) {
						while (node.Role == Roles.EmbeddedStatement || node.Role == IfElseStatement.TrueRole || node.Role == IfElseStatement.FalseRole)
							node = node.Parent;
						// include indentation if node starts in new line
						var formatNode = node.GetPrevNode ();
						if (formatNode.Role != Roles.NewLine)
							formatNode = node;
						var start = stubData.LocationToOffset (formatNode.StartLocation);
						if (start > formatStartOffset) {
							var end = stubData.LocationToOffset (node.EndLocation);
							formatStartOffset = start;
							formatLength = end - start;
						}
					}
				}
				return changes;
			}
		}
Exemplo n.º 51
0
		public override void OnTheFlyFormat (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain,
			TextEditorData data, int startOffset, int endOffset)
		{
			var compilationUnit = new MonoDevelop.CSharp.Parser.CSharpParser ().Parse (data);
			var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
			var domSpacingVisitor = new AstSpacingVisitor (policy, data) {
				AutoAcceptChanges = false,
			};
			compilationUnit.AcceptVisitor (domSpacingVisitor, null);

			var domIndentationVisitor = new AstIndentationVisitor (policy, data) {
				AutoAcceptChanges = false,
			};
			compilationUnit.AcceptVisitor (domIndentationVisitor, null);

			var changes = new List<Change> ();

			changes.AddRange (domSpacingVisitor.Changes.
				Concat (domIndentationVisitor.Changes).
				Where (c => c is TextReplaceChange && (startOffset <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset < endOffset)));

			RefactoringService.AcceptChanges (null, null, changes);
			CorrectFormatting (data, startOffset, endOffset);
		}
Exemplo n.º 52
0
		public static void SetFormatOptions (CSharpOutputVisitor outputVisitor, PolicyContainer policyParent)
		{
			IEnumerable<string> types = DesktopService.GetMimeTypeInheritanceChain (MimeType);
			TextStylePolicy currentPolicy = policyParent != null ? policyParent.Get<TextStylePolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<TextStylePolicy> (types);
			CSharpFormattingPolicy codePolicy = policyParent != null ? policyParent.Get<CSharpFormattingPolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<CSharpFormattingPolicy> (types);

			outputVisitor.Options.IndentationChar = currentPolicy.TabsToSpaces ? ' ' : '\t';
			outputVisitor.Options.TabSize = currentPolicy.TabWidth;
			outputVisitor.Options.IndentSize = currentPolicy.TabWidth;
			outputVisitor.Options.EolMarker = TextStylePolicy.GetEolMarker(currentPolicy.EolMarker);

			CodeFormatDescription descr = CSharpFormattingPolicyPanel.CodeFormatDescription;
			Type optionType = outputVisitor.Options.GetType ();

			foreach (CodeFormatOption option in descr.AllOptions) {
				KeyValuePair<string, string> val = descr.GetValue (codePolicy, option);
				PropertyInfo info = optionType.GetProperty (option.Name);
				if (info == null) {
					System.Console.WriteLine ("option : " + option.Name + " not found.");
					continue;
				}
				object cval = null;
				if (info.PropertyType.IsEnum) {
					cval = Enum.Parse (info.PropertyType, val.Key);
				} else if (info.PropertyType == typeof(bool)) {
					cval = Convert.ToBoolean (val.Key);
				} else {
					cval = Convert.ChangeType (val.Key, info.PropertyType);
				}
				//System.Console.WriteLine("set " + option.Name + " to " + cval);
				info.SetValue (outputVisitor.Options, cval, null);
			}
		}
Exemplo n.º 53
0
		static AstFormattingVisitor GetFormattingChanges (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, MonoDevelop.Ide.Gui.Document document, string input)
		{
			using (var stubData = TextEditorData.CreateImmutable (input)) {
				stubData.Document.FileName = document.FileName;
				var parser = document.HasProject ? new ICSharpCode.NRefactory.CSharp.CSharpParser (TypeSystemParser.GetCompilerArguments (document.Project)) : new ICSharpCode.NRefactory.CSharp.CSharpParser ();
				var compilationUnit = parser.Parse (stubData);
				bool hadErrors = parser.HasErrors;
				// try it out, if the behavior is better when working only with correct code.
				if (hadErrors) {
					return null;
				}
				
				var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
				
				var formattingVisitor = new AstFormattingVisitor (policy.CreateOptions (), stubData.Document, document.Editor.CreateNRefactoryTextEditorOptions ()) {
					HadErrors = hadErrors
				};
				compilationUnit.AcceptVisitor (formattingVisitor);
				return formattingVisitor;
			}
		}
Exemplo n.º 54
0
		public override void OnTheFlyFormat (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, 
			TextEditorData data, int startOffset, int endOffset)
		{
			var parser = new MonoDevelop.CSharp.Parser.CSharpParser ();
			var compilationUnit = parser.Parse (data);
			bool hadErrors = parser.ErrorReportPrinter.ErrorsCount + parser.ErrorReportPrinter.FatalCounter > 0;
			var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
			var formattingVisitor = new AstFormattingVisitor (policy, data) {
				AutoAcceptChanges = false,
			};
			compilationUnit.AcceptVisitor (formattingVisitor, null);
			
			
			var changes = new List<Change> ();

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

			RefactoringService.AcceptChanges (null, null, changes);
		}
Exemplo n.º 55
0
		static void Format (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, TextEditor editor, DocumentContext context, int startOffset, int endOffset, bool exact, bool formatLastStatementOnly = false, OptionSet optionSet = null)
		{
			TextSpan span;
			if (exact) {
				span = new TextSpan (startOffset, endOffset - startOffset);
			} else {
				span = new TextSpan (0, endOffset);
			}

			var analysisDocument = context.AnalysisDocument;
			if (analysisDocument == null)
				return;
			using (var undo = editor.OpenUndoGroup (/*OperationType.Format*/)) {
				try {
					var syntaxTree = analysisDocument.GetSyntaxTreeAsync ().Result;

					if (formatLastStatementOnly) {
						var root = syntaxTree.GetRoot ();
						var token = root.FindToken (endOffset);
						var tokens = ICSharpCode.NRefactory6.CSharp.FormattingRangeHelper.FindAppropriateRange (token);
						if (tokens.HasValue) {
							span = new TextSpan (tokens.Value.Item1.SpanStart, tokens.Value.Item2.Span.End - tokens.Value.Item1.SpanStart);
						} else {
							var parent = token.Parent;
							if (parent != null)
								span = parent.FullSpan;
						}
					}

					if (optionSet == null) {
						var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
						var textPolicy = policyParent.Get<TextStylePolicy> (mimeTypeChain);
						optionSet = policy.CreateOptions (textPolicy);
					}

					var doc = Formatter.FormatAsync (analysisDocument, span, optionSet).Result;
					var newTree = doc.GetSyntaxTreeAsync ().Result;
					var caretOffset = editor.CaretOffset;

					int delta = 0;
					foreach (var change in newTree.GetChanges (syntaxTree)) {
						if (!exact && change.Span.Start + delta >= caretOffset)
							continue;
						var newText = change.NewText;
						editor.ReplaceText (delta + change.Span.Start, change.Span.Length, newText);
						delta = delta - change.Span.Length + newText.Length;
					}
					if (startOffset < caretOffset) {
						var caretEndOffset = caretOffset + delta;
						if (0 <= caretEndOffset && caretEndOffset < editor.Length)
							editor.CaretOffset = caretEndOffset;
						if (editor.CaretColumn == 1) {
							if (editor.CaretLine > 1 && editor.GetLine (editor.CaretLine - 1).Length == 0)
								editor.CaretLine--;
							editor.CaretColumn = editor.GetVirtualIndentationColumn (editor.CaretLine);
						}
					}
				} catch (Exception e) {
					LoggingService.LogError ("Error in on the fly formatter", e);
				}
			}
		}
Exemplo n.º 56
0
		public override string FormatText (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, string input, int startOffset, int endOffset)
		{
			var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
			var textPolicy = policyParent.Get<TextStylePolicy> (mimeTypeChain);

			return FormatText (policy, textPolicy, mimeTypeChain.First (), input, startOffset, endOffset);

		}
Exemplo n.º 57
0
		protected override ITextSource FormatImplementation (PolicyContainer policyParent, string mimeType, ITextSource input, int startOffset, int length)
		{
			var policy = policyParent.Get<CSharpFormattingPolicy> (mimeType);
			var textPolicy = policyParent.Get<TextStylePolicy> (mimeType);

			return new StringTextSource (FormatText (policy, textPolicy, input.Text, startOffset, startOffset + length));
		}
Exemplo n.º 58
0
		public override void OnTheFlyFormat (PolicyContainer policyParent, object textEditorData, int startOffset, int endOffset)
		{
			TextEditorData data = (TextEditorData)textEditorData;
			
			CSharp.Dom.CompilationUnit compilationUnit = new MonoDevelop.CSharp.Parser.CSharpParser ().Parse (data);
			IEnumerable<string> types = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType);
			CSharpFormattingPolicy policy = policyParent != null ? policyParent.Get<CSharpFormattingPolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<CSharpFormattingPolicy> (types);
			DomSpacingVisitor domSpacingVisitor = new DomSpacingVisitor (policy, data);
			domSpacingVisitor.AutoAcceptChanges = false;
			compilationUnit.AcceptVisitor (domSpacingVisitor, null);
			
			DomIndentationVisitor domIndentationVisitor = new DomIndentationVisitor (policy, data);
			domIndentationVisitor.AutoAcceptChanges = false;
			compilationUnit.AcceptVisitor (domIndentationVisitor, null);
			
			List<Change> changes = new List<Change> ();
			
			changes.AddRange (domSpacingVisitor.Changes.
				Concat (domIndentationVisitor.Changes).
				Where (c => c is TextReplaceChange && (startOffset <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset < endOffset)));
			
			RefactoringService.AcceptChanges (null, null, changes);
			CorrectFormatting (data, startOffset, endOffset);
		}
Exemplo n.º 59
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)
					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;
			sb.Append (data.Editor.GetTextBetween (member.Location.Line, 1, member.BodyRegion.End.Line + (runAferCR ? 1 : 0), member.BodyRegion.End.Column));
			int endOffset = sb.Length;
			sb.AppendLine ();
			sb.Append (new string ('}', closingBrackets));

			TextEditorData stubData = new TextEditorData () { Text = sb.ToString () };
			stubData.Document.FileName = data.FileName;
			var compilationUnit = new MonoDevelop.CSharp.Parser.CSharpParser ().Parse (stubData);

			var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
			var domSpacingVisitor = new AstSpacingVisitor (policy, stubData) {
				AutoAcceptChanges = false,
			};
			compilationUnit.AcceptVisitor (domSpacingVisitor, null);

			var domIndentationVisitor = new AstIndentationVisitor (policy, stubData) {
				AutoAcceptChanges = false,
			};
			domIndentationVisitor.CorrectBlankLines = correctBlankLines;
			compilationUnit.AcceptVisitor (domIndentationVisitor, null);

			var changes = new List<Change> ();
			changes.AddRange (domSpacingVisitor.Changes.Cast<TextReplaceChange> ().Where (c => startOffset < c.Offset && c.Offset < endOffset));
			changes.AddRange (domIndentationVisitor.Changes.Cast<TextReplaceChange> ().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 (TextReplaceChange change in changes) {
				if (change is AstSpacingVisitor.MyTextReplaceChange) 
					((AstSpacingVisitor.MyTextReplaceChange)change).SetTextEditorData (data.Editor);
				change.Offset += delta;
				lines.Add (data.Editor.OffsetToLineNumber (change.Offset));
			}
			RefactoringService.AcceptChanges (null, null, changes);
			foreach (int line in lines)
				data.Editor.Document.CommitLineUpdate (line);
			stubData.Dispose ();
		}