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;
		}
Beispiel #2
0
        public virtual Stream CreateFileContent(SolutionFolderItem policyParent, Project project, string language, string fileName, string identifier)
        {
            if (createFileContentFromDerivedClass)
            {
                return(null);
            }

            var model = CombinedTagModel.GetTagModel(ProjectTagModel, policyParent, project, language, identifier, fileName);

            //HACK: for API compat, CreateContent just gets the override, not the base model
            // but ProcessContent gets the entire model
            string content = CreateContent(project, model.OverrideTags, language);

            content = ProcessContent(content, model);

            string mime      = DesktopService.GetMimeTypeForUri(fileName);
            var    formatter = !string.IsNullOrEmpty(mime) ? CodeFormatterService.GetFormatter(mime) : null;

            if (formatter != null)
            {
                var formatted = formatter.FormatText(policyParent != null ? policyParent.Policies : null, content);
                if (formatted != null)
                {
                    content = formatted;
                }
            }

            var ms = new MemoryStream();

            var bom = Encoding.UTF8.GetPreamble();

            ms.Write(bom, 0, bom.Length);

            byte[] data;
            if (AddStandardHeader)
            {
                string header = StandardHeaderService.GetHeader(policyParent, fileName, true);
                data = System.Text.Encoding.UTF8.GetBytes(header);
                ms.Write(data, 0, data.Length);
            }

            var doc = TextEditorFactory.CreateNewDocument();

            doc.Text = content;

            TextStylePolicy textPolicy = policyParent != null?policyParent.Policies.Get <TextStylePolicy> (mime ?? "text/plain")
                                             : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy> (mime ?? "text/plain");

            string eolMarker = TextStylePolicy.GetEolMarker(textPolicy.EolMarker);

            byte[] eolMarkerBytes = System.Text.Encoding.UTF8.GetBytes(eolMarker);

            var tabToSpaces = textPolicy.TabsToSpaces? new string (' ', textPolicy.TabWidth) : null;

            foreach (var line in doc.GetLines())
            {
                var lineText = doc.GetTextAt(line.Offset, line.Length);
                if (tabToSpaces != null)
                {
                    lineText = lineText.Replace("\t", tabToSpaces);
                }
                if (line.LengthIncludingDelimiter > 0)
                {
                    data = System.Text.Encoding.UTF8.GetBytes(lineText);
                    ms.Write(data, 0, data.Length);
                    ms.Write(eolMarkerBytes, 0, eolMarkerBytes.Length);
                }
            }

            ms.Position = 0;
            return(ms);
        }
        // Returns a stream with the content of the file.
        // project and language parameters are optional
        public virtual Stream CreateFileContent(SolutionItem policyParent, Project project, string language, string fileName, string identifier)
        {
            Dictionary <string, string> tags = new Dictionary <string, string> ();

            ModifyTags(policyParent, project, language, identifier, fileName, ref tags);

            string content = CreateContent(project, tags, language);

            content = StringParserService.Parse(content, tags);
            string        mime      = DesktopService.GetMimeTypeForUri(fileName);
            CodeFormatter formatter = !string.IsNullOrEmpty(mime) ? CodeFormatterService.GetFormatter(mime) : null;

            if (formatter != null)
            {
                var formatted = formatter.FormatText(policyParent != null ? policyParent.Policies : null, content);
                if (formatted != null)
                {
                    content = formatted;
                }
            }

            var ms = new MemoryStream();

            var bom = Encoding.UTF8.GetPreamble();

            ms.Write(bom, 0, bom.Length);

            byte[] data;
            if (AddStandardHeader)
            {
                string header = StandardHeaderService.GetHeader(policyParent, fileName, true);
                data = System.Text.Encoding.UTF8.GetBytes(header);
                ms.Write(data, 0, data.Length);
            }

            Mono.TextEditor.TextDocument doc = new Mono.TextEditor.TextDocument();
            doc.Text = content;

            TextStylePolicy textPolicy = policyParent != null?policyParent.Policies.Get <TextStylePolicy> ("text/plain")
                                             : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy> ("text/plain");

            string eolMarker = TextStylePolicy.GetEolMarker(textPolicy.EolMarker);

            byte[] eolMarkerBytes = System.Text.Encoding.UTF8.GetBytes(eolMarker);

            var tabToSpaces = textPolicy.TabsToSpaces? new string (' ', textPolicy.TabWidth) : null;

            foreach (Mono.TextEditor.DocumentLine line in doc.Lines)
            {
                var lineText = doc.GetTextAt(line.Offset, line.Length);
                if (tabToSpaces != null)
                {
                    lineText = lineText.Replace("\t", tabToSpaces);
                }
                data = System.Text.Encoding.UTF8.GetBytes(lineText);
                ms.Write(data, 0, data.Length);
                ms.Write(eolMarkerBytes, 0, eolMarkerBytes.Length);
            }

            ms.Position = 0;
            return(ms);
        }
Beispiel #4
0
        public static OptionSet Apply(OptionSet options, TextStylePolicy policy)
        {
            var result = options;

            if (policy != null)
            {
                result = result.WithChangedOption(Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentationSize, LanguageNames.CSharp, policy.IndentWidth);
                result = result.WithChangedOption(Microsoft.CodeAnalysis.Formatting.FormattingOptions.NewLine, LanguageNames.CSharp, policy.GetEolMarker());
                result = result.WithChangedOption(Microsoft.CodeAnalysis.Formatting.FormattingOptions.SmartIndent, LanguageNames.CSharp, FormattingOptions.IndentStyle.Smart);
                result = result.WithChangedOption(Microsoft.CodeAnalysis.Formatting.FormattingOptions.TabSize, LanguageNames.CSharp, policy.TabWidth);
                result = result.WithChangedOption(Microsoft.CodeAnalysis.Formatting.FormattingOptions.UseTabs, LanguageNames.CSharp, !policy.TabsToSpaces);
            }
            return(result);
        }
Beispiel #5
0
        // Returns a stream with the content of the file.
        // project and language parameters are optional
        public virtual async Task <Stream> CreateFileContentAsync(SolutionFolderItem policyParent, Project project, string language, string fileName, string identifier)
        {
            var model = CombinedTagModel.GetTagModel(ProjectTagModel, policyParent, project, language, identifier, fileName);

            //HACK: for API compat, CreateContent just gets the override, not the base model
            // but ProcessContent gets the entire model
            string content = CreateContent(project, model.OverrideTags, language);

            content = ProcessContent(content, model);

            string mime      = DesktopService.GetMimeTypeForUri(fileName);
            var    formatter = !string.IsNullOrEmpty(mime) ? CodeFormatterService.GetFormatter(mime) : null;

            if (formatter != null)
            {
                var formatted = formatter.FormatText(policyParent != null ? policyParent.Policies : null, content);
                if (formatted != null)
                {
                    content = formatted;
                }
            }

            var             ms         = new MemoryStream();
            Encoding        encoding   = null;
            TextStylePolicy textPolicy = policyParent != null?policyParent.Policies.Get <TextStylePolicy> (mime ?? "text/plain")
                                             : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy> (mime ?? "text/plain");

            string eolMarker = TextStylePolicy.GetEolMarker(textPolicy.EolMarker);

            var ctx = await EditorConfigService.GetEditorConfigContext(fileName);

            if (ctx != null)
            {
                ctx.CurrentConventions.UniversalConventions.TryGetEncoding(out encoding);
                if (ctx.CurrentConventions.UniversalConventions.TryGetLineEnding(out string lineEnding))
                {
                    eolMarker = lineEnding;
                }
            }
            if (encoding == null)
            {
                encoding = System.Text.Encoding.UTF8;
            }
            var bom = encoding.GetPreamble();

            if (bom != null && bom.Length > 0)
            {
                ms.Write(bom, 0, bom.Length);
            }

            byte[] data;
            if (AddStandardHeader)
            {
                string header = StandardHeaderService.GetHeader(policyParent, fileName, true);
                data = encoding.GetBytes(header);
                ms.Write(data, 0, data.Length);
            }

            var doc = TextEditorFactory.CreateNewDocument();

            doc.Text = content;


            byte[] eolMarkerBytes = encoding.GetBytes(eolMarker);

            var           tabToSpaces = textPolicy.TabsToSpaces? new string (' ', textPolicy.TabWidth) : null;
            IDocumentLine lastLine    = null;

            foreach (var line in doc.GetLines())
            {
                var lineText = doc.GetTextAt(line.Offset, line.Length);
                if (tabToSpaces != null)
                {
                    lineText = lineText.Replace("\t", tabToSpaces);
                }
                if (line.LengthIncludingDelimiter > 0)
                {
                    data = encoding.GetBytes(lineText);
                    ms.Write(data, 0, data.Length);
                    ms.Write(eolMarkerBytes, 0, eolMarkerBytes.Length);
                }
                lastLine = line;
            }
            if (ctx != null && lastLine != null && lastLine.Length > 0)
            {
                if (ctx.CurrentConventions.UniversalConventions.TryGetRequireFinalNewline(out bool requireNewLine))
                {
                    if (requireNewLine)
                    {
                        ms.Write(eolMarkerBytes, 0, eolMarkerBytes.Length);
                    }
                }
            }

            ms.Position = 0;
            return(ms);
        }