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.IndentationSize = textPolicy.IndentWidth; data.Options.IndentStyle = textPolicy.RemoveTrailingWhitespace ? IndentStyle.Virtual : IndentStyle.Smart; } 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 originalVersion = data.Document.Version; var textEditorOptions = data.CreateNRefactoryTextEditorOptions (); var formattingVisitor = new ICSharpCode.NRefactory.CSharp.CSharpFormatter ( policy.CreateOptions (), textEditorOptions ) { FormattingMode = FormattingMode.Intrusive }; var changes = formattingVisitor.AnalyzeFormatting (data.Document, compilationUnit); try { changes.ApplyChanges (startOffset, endOffset - startOffset); } catch (Exception e) { LoggingService.LogError ("Error in code formatter", e); return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset)); } // 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."); return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset)); } var currentVersion = data.Document.Version; string result = data.GetTextBetween (startOffset, originalVersion.MoveOffsetTo (currentVersion, endOffset, ICSharpCode.NRefactory.Editor.AnchorMovementType.Default)); data.Dispose (); return result; }
public static string FormatXml (TextStylePolicy textPolicy, XmlFormattingPolicy formattingPolicy, string input) { XmlDocument doc; try { doc = new XmlDocument (); doc.LoadXml (input); } catch (XmlException ex) { // handle xml files without root element (https://bugzilla.xamarin.com/show_bug.cgi?id=4748) if (ex.Message == "Root element is missing.") return input; MonoDevelop.Core.LoggingService.LogWarning ("Error formatting XML file", ex); IdeApp.Workbench.StatusBar.ShowError ("Error formatting file: " + ex.Message); return input; } catch (Exception ex) { // Ignore malformed xml MonoDevelop.Core.LoggingService.LogWarning ("Error formatting XML file", ex); IdeApp.Workbench.StatusBar.ShowError ("Error formatting file: " + ex.Message); return input; } var sw = new StringWriter (); var xmlWriter = new XmlFormatterWriter (sw); xmlWriter.WriteNode (doc, formattingPolicy, textPolicy); xmlWriter.Flush (); return sw.ToString (); }
// Constructors public CSharpIndentEngine (CSharpFormattingPolicy policy, TextStylePolicy textPolicy) { if (policy == null) throw new ArgumentNullException ("policy"); if (textPolicy == null) throw new ArgumentNullException ("textPolicy"); this.policy = policy; this.textPolicy = textPolicy; stack = new IndentStack (this); linebuf = new StringBuilder (); Reset (); }
public CSharpIndentEngine(CSharpFormattingPolicy policy, TextStylePolicy textPolicy) { if (policy == null) { throw new ArgumentNullException("policy"); } if (textPolicy == null) { throw new ArgumentNullException("textPolicy"); } this.policy = policy; this.textPolicy = textPolicy; stack = new IndentStack(this); linebuf = new StringBuilder(); Reset(); }
DefaultSourceEditorOptions(TextStylePolicy currentPolicy) { WordNavigationStyle defaultWordNavigation = WordNavigationStyle.Unix; if (Platform.IsWindows) { defaultWordNavigation = WordNavigationStyle.Windows; } wordNavigationStyle = ConfigurationProperty.Create("WordNavigationStyle", defaultWordNavigation); UpdateStylePolicy(currentPolicy); FontService.RegisterFontChangedCallback("Editor", UpdateFont); FontService.RegisterFontChangedCallback("MessageBubbles", UpdateFont); IdeApp.Preferences.ColorScheme.Changed += OnColorSchemeChanged; }
public override string CreateContent(MonoDevelop.Projects.Project project, Dictionary <string, string> tags, string language) { var cc = base.CreateContent(project, tags, language); if (addStdHeader) { StandardHeaderPolicy headerPolicy = project != null?project.Policies.Get <StandardHeaderPolicy>() : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <StandardHeaderPolicy>(); TextStylePolicy textPolicy = project != null?project.Policies.Get <TextStylePolicy>("text/plain") : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy>("text/plain"); DFormattingPolicy dPolicy = project != null?project.Policies.Get <DFormattingPolicy>("text/x-d") : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <DFormattingPolicy>("text/x-d"); if (string.IsNullOrWhiteSpace(headerPolicy.Text) || !headerPolicy.IncludeInNewFiles) { return(cc); } var eol = TextStylePolicy.GetEolMarker(textPolicy.EolMarker); var hdr = StringParserService.Parse(headerPolicy.Text, tags); if (dPolicy.CommentOutStandardHeaders) { var headerLines = hdr.Split('\n'); if (headerLines.Length == 1) { return("/// " + headerLines[0].Trim() + eol + cc); } else { var ret = "/**" + eol; for (int i = 0; i < headerLines.Length; i++) { ret += " * " + headerLines[i].Trim() + eol; } return(ret + " */" + eol + cc); } } else { return(hdr + eol + cc); } } return(cc); }
public static string GetHeader (AuthorInformation authorInfo, StandardHeaderPolicy policy, TextStylePolicy textPolicy, string fileName, bool newFile) { string[] comment = Document.GetCommentTags (fileName); if (comment == null) return ""; if (string.IsNullOrEmpty (policy.Text) || (newFile && !policy.IncludeInNewFiles)) return ""; string result; string eolMarker = TextStylePolicy.GetEolMarker (textPolicy.EolMarker); if (comment.Length == 1) { string cmt = comment[0]; //make sure there's a space between the comment char and the license text if (!char.IsWhiteSpace (cmt[cmt.Length - 1])) cmt = cmt + " "; StringBuilder sb = new StringBuilder (policy.Text.Length); string[] lines = policy.Text.Split ('\n'); foreach (string line in lines) { if (string.IsNullOrWhiteSpace (line)) { sb.Append (cmt.TrimEnd ()); sb.Append (eolMarker); continue; } sb.Append (cmt); sb.Append (line); sb.Append (eolMarker); } result = sb.ToString (); } else { //multiline comment result = String.Concat (comment[0], "\n", policy.Text, "\n", comment[1], "\n"); } return StringParserService.Parse (result, new string[,] { { "FileName", Path.GetFileName (fileName) }, { "FileNameWithoutExtension", Path.GetFileNameWithoutExtension (fileName) }, { "Directory", Path.GetDirectoryName (fileName) }, { "FullFileName", fileName }, { "AuthorName", authorInfo.Name }, { "AuthorEmail", authorInfo.Email }, { "CopyrightHolder", authorInfo.Copyright }, }); }
public string FormatXml (TextStylePolicy textPolicy, XmlFormattingPolicy formattingPolicy, string input) { XmlDocument doc; try { doc = new XmlDocument (); doc.LoadXml (input); } catch { // Ignore malformed xml return input; } StringWriter sw = new StringWriter (); XmlFormatterWriter xmlWriter = new XmlFormatterWriter (sw); xmlWriter.WriteNode (doc, formattingPolicy, textPolicy); xmlWriter.Flush (); return sw.ToString (); }
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; }
public override Stream CreateFileContent(SolutionFolderItem policyParent, Project project, string language, string fileName, string identifier) { if (Outer.FormatCode) { return(base.CreateFileContent(policyParent, project, language, fileName, identifier)); } var model = GetTagModel(policyParent, project, language, identifier, fileName); string text = CreateContent(project, model.OverrideTags, language); text = ProcessContent(text, model); var memoryStream = new MemoryStream(); byte[] preamble = Encoding.UTF8.GetPreamble(); memoryStream.Write(preamble, 0, preamble.Length); if (AddStandardHeader) { string header = StandardHeaderService.GetHeader(policyParent, fileName, true); byte[] bytes = Encoding.UTF8.GetBytes(header); memoryStream.Write(bytes, 0, bytes.Length); } var textDocument = TextEditorFactory.CreateNewDocument(); //var textDocument = new TextDocument (); textDocument.Text = text; var textStylePolicy = (policyParent == null) ? PolicyService.GetDefaultPolicy <TextStylePolicy> ("text/plain") : policyParent.Policies.Get <TextStylePolicy> ("text/plain"); string eolMarker = TextStylePolicy.GetEolMarker(textStylePolicy.EolMarker); byte[] eol = Encoding.UTF8.GetBytes(eolMarker); string indent = (!textStylePolicy.TabsToSpaces) ? null : new string (' ', textStylePolicy.TabWidth); foreach (var current in textDocument.GetLines()) { string line = textDocument.GetTextAt(current.Offset, current.Length); if (indent != null) { line = line.Replace(" ", indent); } byte[] bytes = Encoding.UTF8.GetBytes(line); memoryStream.Write(bytes, 0, bytes.Length); memoryStream.Write(eol, 0, eol.Length); } memoryStream.Position = 0; return(memoryStream); }
// 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); Formatter formatter = !String.IsNullOrEmpty(mime) ? TextFileService.GetFormatter(mime) : null; if (formatter != null) { content = formatter.FormatText(policyParent != null ? policyParent.Policies : null, content); } MemoryStream ms = new MemoryStream(); 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.Document doc = new Mono.TextEditor.Document(); 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); foreach (Mono.TextEditor.LineSegment line in doc.Lines) { data = System.Text.Encoding.UTF8.GetBytes(doc.GetTextAt(line.Offset, line.EditableLength)); ms.Write(data, 0, data.Length); ms.Write(eolMarkerBytes, 0, eolMarkerBytes.Length); } ms.Position = 0; return(ms); }
public static string FormatXml (TextStylePolicy textPolicy, XmlFormattingPolicy formattingPolicy, string input) { XmlDocument doc; try { doc = new XmlDocument (); doc.LoadXml (input); } catch (Exception ex) { // Ignore malformed xml MonoDevelop.Core.LoggingService.LogWarning ("Error formatting XML file", ex); return null; } var sw = new StringWriter (); var xmlWriter = new XmlFormatterWriter (sw); xmlWriter.WriteNode (doc, formattingPolicy, textPolicy); xmlWriter.Flush (); return sw.ToString (); }
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); } }
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); } }
public override void Initialize() { base.Initialize(); IEnumerable <string> types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain(CSharpFormatter.MimeType); if (base.Document.Project != null && base.Document.Project.Policies != null) { policy = base.Document.Project.Policies.Get <CSharpFormattingPolicy> (types); textStylePolicy = base.Document.Project.Policies.Get <TextStylePolicy> (types); } textEditorData = Document.Editor; if (textEditorData != null) { textEditorData.Options.Changed += delegate { var project = base.Document.Project; if (project != null) { policy = project.Policies.Get <CSharpFormattingPolicy> (types); textStylePolicy = project.Policies.Get <TextStylePolicy> (types); } textEditorData.IndentationTracker = new IndentVirtualSpaceManager( textEditorData, new DocumentStateTracker <CSharpIndentEngine> (new CSharpIndentEngine(policy, textStylePolicy), textEditorData) ); }; textEditorData.IndentationTracker = new IndentVirtualSpaceManager( textEditorData, new DocumentStateTracker <CSharpIndentEngine> (new CSharpIndentEngine(policy, textStylePolicy), textEditorData) ); } InitTracker(); Document.Editor.Paste += HandleTextPaste; }
public OptionSet CreateOptions(TextStylePolicy policy) { return(Apply(options, policy)); }
public void Init() { textPolicy = new TextStylePolicy(); xmlPolicy = new XmlFormattingPolicy(); }
public TextStyleAdapter(TextStylePolicy txt) { this.textStyle = txt; }
public string FormatText(PlayScriptFormattingPolicy 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.IndentationSize = textPolicy.IndentWidth; data.Options.IndentStyle = textPolicy.RemoveTrailingWhitespace ? IndentStyle.Virtual : IndentStyle.Smart; } data.Text = input; // System.Console.WriteLine ("-----"); // System.Console.WriteLine (data.Text.Replace (" ", ".").Replace ("\t", "->")); // System.Console.WriteLine ("-----"); var parser = new PlayScriptParser(); 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 originalVersion = data.Document.Version; var textEditorOptions = data.CreateNRefactoryTextEditorOptions(); var formattingVisitor = new ICSharpCode.NRefactory.PlayScript.CSharpFormatter( policy.CreateOptions(), textEditorOptions ) { FormattingMode = FormattingMode.Intrusive }; var changes = formattingVisitor.AnalyzeFormatting(data.Document, compilationUnit); try { changes.ApplyChanges(startOffset, endOffset - startOffset); } catch (Exception e) { LoggingService.LogError("Error in code formatter", e); return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset))); } // check if the formatter has produced errors parser = new PlayScriptParser(); parser.Parse(data); if (parser.HasErrors) { LoggingService.LogError("C# formatter produced source code errors. See console for output."); return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset))); } var currentVersion = data.Document.Version; string result = data.GetTextBetween(startOffset, originalVersion.MoveOffsetTo(currentVersion, endOffset, ICSharpCode.NRefactory.Editor.AnchorMovementType.Default)); data.Dispose(); return(result); }
internal void SetPolicy (CSharpFormattingPolicy formattingPolicy, TextStylePolicy textStylePolicy) { policy = formattingPolicy; this.textStylePolicy = textStylePolicy; FormatSample (); }
public void Init () { textPolicy = new TextStylePolicy (); xmlPolicy = new XmlFormattingPolicy (); }
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; }
public void SetPolicy(TextStylePolicy textStylePolicy) { this.textStylePolicy = textStylePolicy; FormatSample(); }
public void Init() { textPolicy = new TextStylePolicy().WithEolMarker(EolMarker.Unix); xmlPolicy = new XmlFormattingPolicy(); }
// Returns a stream with the content of the file. // project and language parameters are optional public virtual Stream CreateFileContent(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(); 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> ("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 (var line in doc.GetLines()) { 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); }
public override void Initialize() { base.Initialize (); IEnumerable<string> types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain (TypeScriptFormatter.MimeType); if (Document.Project != null && Document.Project.Policies != null) { policy = base.Document.Project.Policies.Get<TypeScriptFormattingPolicy> (types); textStylePolicy = base.Document.Project.Policies.Get<TextStylePolicy> (types); } if (Editor != null) { Editor.Options.Changed += (o, args) => { var project = Document.Project; if (project != null) { policy = project.Policies.Get<TypeScriptFormattingPolicy> (types); textStylePolicy = project.Policies.Get<TextStylePolicy> (types); } /* Editor.IndentationTracker = new IndentVirtualSpaceManager ( Editor, new DocumentStateTracker<TypeScriptIndentEngine> (new TypeScriptIndentEngine (policy, textStylePolicy), Editor) ); */ }; /* Editor.IndentationTracker = new IndentVirtualSpaceManager ( Editor, new DocumentStateTracker<TypeScriptIndentEngine> (new TypeScriptIndentEngine (policy, textStylePolicy), Editor) );*/ } InitTracker (); Document.Editor.Paste += HandleTextPaste; }
public static string GetHeader(AuthorInformation authorInfo, StandardHeaderPolicy policy, TextStylePolicy textPolicy, string fileName, bool newFile) { string[] comment = Document.GetCommentTags(fileName); if (comment == null) { return(""); } if (string.IsNullOrEmpty(policy.Text) || (newFile && !policy.IncludeInNewFiles)) { return(""); } string result; string eolMarker = TextStylePolicy.GetEolMarker(textPolicy.EolMarker); if (comment.Length == 1) { string cmt = comment[0]; //make sure there's a space between the comment char and the license text if (!char.IsWhiteSpace(cmt[cmt.Length - 1])) { cmt = cmt + " "; } StringBuilder sb = new StringBuilder(policy.Text.Length); string[] lines = policy.Text.Split('\n'); foreach (string line in lines) { if (string.IsNullOrWhiteSpace(line)) { sb.Append(cmt.TrimEnd()); sb.Append(eolMarker); continue; } sb.Append(cmt); sb.Append(line); sb.Append(eolMarker); } result = sb.ToString(); } else { //multiline comment result = String.Concat(comment[0], "\n", policy.Text, "\n", comment[1], "\n"); } return(StringParserService.Parse(result, new string[, ] { { "FileName", Path.GetFileName(fileName) }, { "FileNameWithoutExtension", Path.GetFileNameWithoutExtension(fileName) }, { "Directory", Path.GetDirectoryName(fileName) }, { "FullFileName", fileName }, { "AuthorName", authorInfo.Name }, { "AuthorEmail", authorInfo.Email }, { "CopyrightHolder", authorInfo.Copyright }, })); }
public static void SaveFormatted (AddinDescription adesc) { XmlDocument doc = adesc.SaveToXml (); XmlFormatter formatter = new XmlFormatter (); TextStylePolicy textPolicy = new TextStylePolicy (80, 4, false, false, true, EolMarker.Unix); XmlFormattingPolicy xmlPolicy = new XmlFormattingPolicy (); XmlFormatingSettings f = new XmlFormatingSettings (); f.ScopeXPath.Add ("*/*"); f.EmptyLinesBeforeStart = 1; f.EmptyLinesAfterEnd = 1; xmlPolicy.Formats.Add (f); f = new XmlFormatingSettings (); f.ScopeXPath.Add ("Addin"); f.AttributesInNewLine = true; f.AlignAttributes = true; f.AttributesInNewLine = false; xmlPolicy.Formats.Add (f); string xml = formatter.FormatXml (textPolicy, xmlPolicy, doc.OuterXml); File.WriteAllText (adesc.FileName, xml); }
// 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); }
DefaultSourceEditorOptions (TextStylePolicy currentPolicy) { WordNavigationStyle defaultWordNavigation = WordNavigationStyle.Unix; if (Platform.IsWindows) { defaultWordNavigation = WordNavigationStyle.Windows; } wordNavigationStyle = ConfigurationProperty.Create ("WordNavigationStyle", defaultWordNavigation); UpdateStylePolicy (currentPolicy); FontService.RegisterFontChangedCallback ("Editor", UpdateFont); FontService.RegisterFontChangedCallback ("MessageBubbles", UpdateFont); }
internal void SetPolicy(CSharpFormattingPolicy formattingPolicy, TextStylePolicy textStylePolicy) { policy = formattingPolicy; this.textStylePolicy = textStylePolicy; FormatSample(); }
public DIndentEngine(DFormattingPolicy policy, TextStylePolicy textStyle) : base(policy.Options, textStyle.TabsToSpaces, textStyle.IndentWidth, policy.KeepAlignmentSpaces) { this.policy = policy; this.textStyle = textStyle; }
public TextDocumentOptions(TextStylePolicy policy) { this.policy = policy; }
public void SetPolicy (TextStylePolicy textStylePolicy) { this.textStylePolicy = textStylePolicy; FormatSample (); }
public static string FormatText (CSharpFormattingPolicy policy, TextStylePolicy textPolicy, string input, int startOffset, int endOffset) { var inputTree = CSharpSyntaxTree.ParseText (input); var root = inputTree.GetRoot (); var doc = Formatter.Format (root, new TextSpan (startOffset, endOffset - startOffset), TypeSystemService.Workspace, policy.CreateOptions (textPolicy)); var result = doc.ToFullString (); return result.Substring (startOffset, endOffset + result.Length - input.Length - startOffset); }
public void WriteNode (XmlNode node, XmlFormattingPolicy formattingPolicy, TextStylePolicy textPolicy) { this.TextPolicy = textPolicy; formatMap.Clear (); defaultFormatSettings = formattingPolicy.DefaultFormat; foreach (XmlFormattingSettings format in formattingPolicy.Formats) { foreach (string xpath in format.ScopeXPath) { foreach (XmlNode n in node.SelectNodes (xpath)) formatMap [n] = format; } } WriteNode (node); }
public void SetPolicy (CSharpFormattingPolicy cSharpFormattingPolicy, TextStylePolicy textStylePolicy) { this.policy = cSharpFormattingPolicy; this.textStylePolicy = textStylePolicy; FormatSample (); }
void HandlePolicyChanged(object sender, MonoDevelop.Projects.Policies.PolicyChangedEventArgs args) { TextStylePolicy pol = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <TextStylePolicy> ("text/plain"); UpdateStylePolicy(pol); }
public void SetPolicy(CSharpFormattingPolicy cSharpFormattingPolicy, TextStylePolicy textStylePolicy) { this.policy = cSharpFormattingPolicy; this.textStylePolicy = textStylePolicy; FormatSample(); }
void HandlePolicyChanged (object sender, MonoDevelop.Projects.Policies.PolicyChangedEventArgs args) { currentPolicy = policyContainer.Get<TextStylePolicy> (mimeTypes); this.changed (this, EventArgs.Empty); }
public CSharpTextEditorIndentation () { IEnumerable<string> types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType); policy = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<CSharpFormattingPolicy> (types); textStylePolicy = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<TextStylePolicy> (types); }
// 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); }
public override void Initialize () { base.Initialize (); IEnumerable<string> types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType); if (base.Document.Project != null && base.Document.Project.Policies != null) { policy = base.Document.Project.Policies.Get<CSharpFormattingPolicy> (types); textStylePolicy = base.Document.Project.Policies.Get<TextStylePolicy> (types); } textEditorData = Document.Editor; if (textEditorData != null) { textEditorData.IndentationTracker = new IndentVirtualSpaceManager ( textEditorData, new DocumentStateTracker<CSharpIndentEngine> (new CSharpIndentEngine (policy, textStylePolicy), textEditorData) ); } InitTracker (); // Document.Editor.Paste += HandleTextPaste; }
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); }
public DIndentEngine(DFormattingPolicy policy, TextStylePolicy textStyle) : base(policy.Options, textStyle.TabsToSpaces, textStyle.IndentWidth) { this.policy = policy; this.textStyle = textStyle; }