From 5746d75d5b544f41e0e7df3623a1ac7e0164fb1f Mon Sep 17 00:00:00 2001 From: MakiWolf Date: Sun, 23 Jul 2023 21:31:53 +0200 Subject: [PATCH 1/6] comment out --- .../CSharpFormatter.cs | 72 +-- .../CSharpDocumentOptionsProvider.cs | 220 ++++----- .../OptionProviderFactory.cs | 16 +- .../MonoDevelop.TextEditor/TextViewContent.cs | 446 +++++++++--------- .../MonoDevelop.Core/MonoDevelop.Core.csproj | 4 +- .../ExtensionModel/MonoDevelop.Ide.addin.xml | 4 +- .../DefaultSourceEditorOptions.cs | 137 +++--- .../EditorConfigService.cs | 347 +++++++------- .../MonoDevelop.Ide.Editor/TextEditor.cs | 14 +- .../TextEditorViewContent.cs | 14 +- .../SingleFileDescriptionTemplate.cs | 38 +- .../MonoDevelop.Ide/MonoDevelop.Ide.csproj | 2 +- 12 files changed, 658 insertions(+), 656 deletions(-) diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpFormatter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpFormatter.cs index bf0d3cbef83..3ebabd9ef5e 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpFormatter.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpFormatter.cs @@ -47,7 +47,7 @@ using Roslyn.Utilities; using Microsoft.CodeAnalysis.Options; using MonoDevelop.CSharp.OptionProvider; -using Microsoft.VisualStudio.CodingConventions; +//using Microsoft.VisualStudio.CodingConventions; using System.Linq; using System.Collections.Immutable; using System.Runtime.CompilerServices; @@ -144,13 +144,13 @@ protected override ITextSource FormatImplementation (PolicyContainer policyParen 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); - } + // 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)); @@ -159,41 +159,41 @@ protected override ITextSource FormatImplementation (PolicyContainer policyParen sealed class DocumentOptions : IDocumentOptions { readonly OptionSet optionSet; - readonly ICodingConventionsSnapshot codingConventionsSnapshot; + //readonly ICodingConventionsSnapshot codingConventionsSnapshot; private static readonly ConditionalWeakTable, IReadOnlyDictionary> s_convertedDictionaryCache = new ConditionalWeakTable, IReadOnlyDictionary> (); - public DocumentOptions (OptionSet optionSet, ICodingConventionsSnapshot codingConventionsSnapshot) - { - this.optionSet = optionSet; - this.codingConventionsSnapshot = codingConventionsSnapshot; - } + // public DocumentOptions (OptionSet optionSet, ICodingConventionsSnapshot codingConventionsSnapshot) + // { + // this.optionSet = optionSet; + // this.codingConventionsSnapshot = codingConventionsSnapshot; + // } public bool TryGetDocumentOption (OptionKey option, out object value) { - if (codingConventionsSnapshot != null) { - var editorConfigPersistence = option.Option.StorageLocations.OfType ().SingleOrDefault (); - if (editorConfigPersistence != null) { - // Temporarly map our old Dictionary to a Dictionary. This can go away once we either - // eliminate the legacy editorconfig support, or we change IEditorConfigStorageLocation.TryGetOption to take - // some interface that lets us pass both the Dictionary we get from the new system, and the - // Dictionary from the old system. - // - // We cache this with a conditional weak table so we're able to maintain the assumptions in EditorConfigNamingStyleParser - // that the instance doesn't regularly change and thus can be used for further caching - var allRawConventions = s_convertedDictionaryCache.GetValue ( - codingConventionsSnapshot.AllRawConventions, - d => ImmutableDictionary.CreateRange (d.Select (c => KeyValuePairUtil.Create (c.Key, c.Value.ToString ())))); - - try { - if (editorConfigPersistence.TryGetOption (allRawConventions, option.Option.Type, out value)) - return true; - } catch (Exception ex) { - LoggingService.LogError ("Error while getting editor config preferences.", ex); - } - } - } + // if (codingConventionsSnapshot != null) { + // var editorConfigPersistence = option.Option.StorageLocations.OfType ().SingleOrDefault (); + // if (editorConfigPersistence != null) { + // // Temporarly map our old Dictionary to a Dictionary. This can go away once we either + // // eliminate the legacy editorconfig support, or we change IEditorConfigStorageLocation.TryGetOption to take + // // some interface that lets us pass both the Dictionary we get from the new system, and the + // // Dictionary from the old system. + // // + // // We cache this with a conditional weak table so we're able to maintain the assumptions in EditorConfigNamingStyleParser + // // that the instance doesn't regularly change and thus can be used for further caching + // var allRawConventions = s_convertedDictionaryCache.GetValue ( + // codingConventionsSnapshot.AllRawConventions, + // d => ImmutableDictionary.CreateRange (d.Select (c => KeyValuePairUtil.Create (c.Key, c.Value.ToString ())))); + + // try { + // if (editorConfigPersistence.TryGetOption (allRawConventions, option.Option.Type, out value)) + // return true; + // } catch (Exception ex) { + // LoggingService.LogError ("Error while getting editor config preferences.", ex); + // } + // } + // } var result = optionSet.GetOption (option); value = result; diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/CSharpDocumentOptionsProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/CSharpDocumentOptionsProvider.cs index b48aca4ce4c..c5f7b3efb9d 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/CSharpDocumentOptionsProvider.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/CSharpDocumentOptionsProvider.cs @@ -34,7 +34,7 @@ using MonoDevelop.Ide.Gui.Content; using MonoDevelop.Ide.TypeSystem; using MonoDevelop.Projects.Policies; -using Microsoft.VisualStudio.CodingConventions; +//using Microsoft.VisualStudio.CodingConventions; using System.IO; using MonoDevelop.Core; using System.Linq; @@ -45,113 +45,113 @@ namespace MonoDevelop.CSharp.OptionProvider { - class CSharpDocumentOptionsProvider : IDocumentOptionsProvider - { - async Task IDocumentOptionsProvider.GetOptionsForDocumentAsync (Document document, CancellationToken cancellationToken) - { - var mdws = document.Project.Solution.Workspace as MonoDevelopWorkspace; - var project = mdws?.GetMonoProject (document.Project.Id); - - var path = GetPath (document); - ICodingConventionContext conventions = null; - try { - if (path != null) - conventions = await EditorConfigService.GetEditorConfigContext (path, cancellationToken); - } catch (Exception e) { - LoggingService.LogError("Error while loading coding conventions.", e); - } - return new DocumentOptions (project?.Policies, conventions?.CurrentConventions); - } - - static string GetPath(Document document) - { - if (document.FilePath != null) - return document.FilePath; - - // The file might not actually have a path yet, if it's a file being proposed by a code action. We'll guess a file path to use - if (document.Name != null && document.Project.FilePath != null) { - return Path.Combine (Path.GetDirectoryName (document.Project.FilePath), document.Name); - } - - // Really no idea where this is going, so bail - return null; - } - - internal class DocumentOptions : IDocumentOptions - { - readonly static IEnumerable types = Ide.IdeServices.DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType); - readonly PolicyBag policyBag; - - CSharpFormattingPolicy policy; - CSharpFormattingPolicy Policy => policy ?? (policy = policyBag?.Get (types) ?? PolicyService.InvariantPolicies.Get (types)); - - TextStylePolicy textpolicy; - TextStylePolicy TextPolicy => textpolicy ?? (textpolicy = policyBag?.Get (types) ?? PolicyService.InvariantPolicies?.Get (types)); - - readonly ICodingConventionsSnapshot codingConventionsSnapshot; - private static readonly ConditionalWeakTable, IReadOnlyDictionary> s_convertedDictionaryCache = - new ConditionalWeakTable, IReadOnlyDictionary> (); - - public DocumentOptions (PolicyBag policyBag, ICodingConventionsSnapshot codingConventionsSnapshot) - { - this.policyBag = policyBag; - this.codingConventionsSnapshot = codingConventionsSnapshot; - } - - public bool TryGetDocumentOption (OptionKey option, out object value) - { - if (codingConventionsSnapshot != null) { - var editorConfigPersistence = option.Option.StorageLocations.OfType ().SingleOrDefault (); - if (editorConfigPersistence != null) { - // Temporarly map our old Dictionary to a Dictionary. This can go away once we either - // eliminate the legacy editorconfig support, or we change IEditorConfigStorageLocation.TryGetOption to take - // some interface that lets us pass both the Dictionary we get from the new system, and the - // Dictionary from the old system. - // - // We cache this with a conditional weak table so we're able to maintain the assumptions in EditorConfigNamingStyleParser - // that the instance doesn't regularly change and thus can be used for further caching - var allRawConventions = s_convertedDictionaryCache.GetValue ( - codingConventionsSnapshot.AllRawConventions, - d => ImmutableDictionary.CreateRange (d.Select (c => KeyValuePairUtil.Create (c.Key, c.Value.ToString ())))); - - try { - if (editorConfigPersistence.TryGetOption (allRawConventions, option.Option.Type, out value)) - return true; - } catch (Exception ex) { - LoggingService.LogError ("Error while getting editor config preferences.", ex); - } - } - } - - if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentationSize) { - value = TextPolicy.IndentWidth; - return true; - } - - if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.NewLine) { - value = TextPolicy.GetEolMarker (); - return true; - } - - if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.SmartIndent) { - value = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle.Smart; - return true; - } - - if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.TabSize) { - value = TextPolicy.TabWidth; - return true; - } - - if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.UseTabs) { - value = !TextPolicy.TabsToSpaces; - return true; - } - - var result = Policy.OptionSet.GetOption (option); - value = result; - return true; - } - } - } + //class CSharpDocumentOptionsProvider : IDocumentOptionsProvider + //{ + // async Task IDocumentOptionsProvider.GetOptionsForDocumentAsync (Document document, CancellationToken cancellationToken) + // { + // var mdws = document.Project.Solution.Workspace as MonoDevelopWorkspace; + // var project = mdws?.GetMonoProject (document.Project.Id); + + // var path = GetPath (document); + // //ICodingConventionContext conventions = null; + // // try { + // // if (path != null) + // // //conventions = await EditorConfigService.GetEditorConfigContext (path, cancellationToken); + // // } catch (Exception e) { + // // LoggingService.LogError("Error while loading coding conventions.", e); + // // } + // //return new DocumentOptions (project?.Policies, conventions?.CurrentConventions); + // } + + // static string GetPath(Document document) + // { + // if (document.FilePath != null) + // return document.FilePath; + + // // The file might not actually have a path yet, if it's a file being proposed by a code action. We'll guess a file path to use + // if (document.Name != null && document.Project.FilePath != null) { + // return Path.Combine (Path.GetDirectoryName (document.Project.FilePath), document.Name); + // } + + // // Really no idea where this is going, so bail + // return null; + // } + + //internal class DocumentOptions : IDocumentOptions + //{ + //readonly static IEnumerable types = Ide.IdeServices.DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType); + //readonly PolicyBag policyBag; + + //CSharpFormattingPolicy policy; + //CSharpFormattingPolicy Policy => policy ?? (policy = policyBag?.Get (types) ?? PolicyService.InvariantPolicies.Get (types)); + + //TextStylePolicy textpolicy; + //TextStylePolicy TextPolicy => textpolicy ?? (textpolicy = policyBag?.Get (types) ?? PolicyService.InvariantPolicies?.Get (types)); + + //readonly ICodingConventionsSnapshot codingConventionsSnapshot; + //private static readonly ConditionalWeakTable, IReadOnlyDictionary> s_convertedDictionaryCache = + // new ConditionalWeakTable, IReadOnlyDictionary> (); + + // public DocumentOptions (PolicyBag policyBag, ICodingConventionsSnapshot codingConventionsSnapshot) + // { + // this.policyBag = policyBag; + // this.codingConventionsSnapshot = codingConventionsSnapshot; + // } + + // public bool TryGetDocumentOption (OptionKey option, out object value) + // { + // if (codingConventionsSnapshot != null) { + // var editorConfigPersistence = option.Option.StorageLocations.OfType ().SingleOrDefault (); + // if (editorConfigPersistence != null) { + // // Temporarly map our old Dictionary to a Dictionary. This can go away once we either + // // eliminate the legacy editorconfig support, or we change IEditorConfigStorageLocation.TryGetOption to take + // // some interface that lets us pass both the Dictionary we get from the new system, and the + // // Dictionary from the old system. + // // + // // We cache this with a conditional weak table so we're able to maintain the assumptions in EditorConfigNamingStyleParser + // // that the instance doesn't regularly change and thus can be used for further caching + // var allRawConventions = s_convertedDictionaryCache.GetValue ( + // codingConventionsSnapshot.AllRawConventions, + // d => ImmutableDictionary.CreateRange (d.Select (c => KeyValuePairUtil.Create (c.Key, c.Value.ToString ())))); + + // try { + // if (editorConfigPersistence.TryGetOption (allRawConventions, option.Option.Type, out value)) + // return true; + // } catch (Exception ex) { + // LoggingService.LogError ("Error while getting editor config preferences.", ex); + // } + // } + // } + + // if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentationSize) { + // value = TextPolicy.IndentWidth; + // return true; + // } + + // if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.NewLine) { + // value = TextPolicy.GetEolMarker (); + // return true; + // } + + // if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.SmartIndent) { + // value = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle.Smart; + // return true; + // } + + // if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.TabSize) { + // value = TextPolicy.TabWidth; + // return true; + // } + + // if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.UseTabs) { + // value = !TextPolicy.TabsToSpaces; + // return true; + // } + + // var result = Policy.OptionSet.GetOption (option); + // value = result; + // return true; + // } + // } + //} } diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/OptionProviderFactory.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/OptionProviderFactory.cs index b10358ea09b..9f940d2b499 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/OptionProviderFactory.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/OptionProviderFactory.cs @@ -30,12 +30,12 @@ namespace MonoDevelop.CSharp.OptionProvider { - [Export (typeof (IDocumentOptionsProviderFactory))] - class EditorConfigDocumentOptionsProviderFactory : IDocumentOptionsProviderFactory - { - public IDocumentOptionsProvider TryCreate (Workspace workspace) - { - return new CSharpDocumentOptionsProvider (); - } - } + // [Export (typeof (IDocumentOptionsProviderFactory))] + // class EditorConfigDocumentOptionsProviderFactory : IDocumentOptionsProviderFactory + // { + // // public IDocumentOptionsProvider TryCreate (Workspace workspace) + // // { + // // return new CSharpDocumentOptionsProvider (); + // // } + // } } diff --git a/main/src/addins/MonoDevelop.TextEditor/MonoDevelop.TextEditor/TextViewContent.cs b/main/src/addins/MonoDevelop.TextEditor/MonoDevelop.TextEditor/TextViewContent.cs index 29c89bce8ff..b977a28e9bd 100644 --- a/main/src/addins/MonoDevelop.TextEditor/MonoDevelop.TextEditor/TextViewContent.cs +++ b/main/src/addins/MonoDevelop.TextEditor/MonoDevelop.TextEditor/TextViewContent.cs @@ -32,7 +32,7 @@ using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Utilities; -using Microsoft.VisualStudio.CodingConventions; +//using Microsoft.VisualStudio.CodingConventions; using Microsoft.VisualStudio.Threading; using Microsoft.VisualStudio.Utilities; @@ -49,7 +49,7 @@ using MonoDevelop.Ide.Gui.Documents; using AutoSave = MonoDevelop.Ide.Editor.AutoSave; -using EditorConfigService = MonoDevelop.Ide.Editor.EditorConfigService; +//using EditorConfigService = MonoDevelop.Ide.Editor.EditorConfigService; using DefaultSourceEditorOptions = MonoDevelop.Ide.Editor.DefaultSourceEditorOptions; using MonoDevelop.Components; using System.Threading; @@ -86,7 +86,7 @@ abstract partial class TextViewContent : static bool settingZoomLevel; PolicyContainer policyContainer; - ICodingConventionContext editorConfigContext; + //ICodingConventionContext editorConfigContext; bool warnOverwrite; IDisposable textBufferRegistration; @@ -161,7 +161,7 @@ protected override async Task OnGetViewControlAsync (CancellationToken EditorOperations = (EditorOperationsInterface)Imports.EditorOperationsProvider.GetEditorOperations (TextView); EditorOptions = Imports.EditorOptionsFactoryService.GetOptions (TextView); TextBufferOptions = Imports.EditorOptionsFactoryService.GetOptions (TextView.TextBuffer); - UpdateTextEditorOptions (this, EventArgs.Empty); + //UpdateTextEditorOptions (this, EventArgs.Empty); contentProviders = new List (Imports.EditorContentProviderService.GetContentProvidersForView (TextView)); TextView.Properties [typeof (DocumentController)] = this; @@ -199,7 +199,7 @@ protected override async Task OnGetViewControlAsync (CancellationToken // Content providers can provide additional content NotifyContentChanged (); - await Load (false); + ////await Load (false); return control; } @@ -249,11 +249,11 @@ protected override void OnFileNameChanged () warnOverwrite = false; - if (editorConfigContext != null) { - editorConfigContext.CodingConventionsChangedAsync -= UpdateOptionsFromEditorConfigAsync; - EditorConfigService.RemoveEditConfigContext (TextDocument.FilePath).Ignore (); - editorConfigContext = null; - } + // if (editorConfigContext != null) { + // editorConfigContext.CodingConventionsChangedAsync -= UpdateOptionsFromEditorConfigAsync; + // EditorConfigService.RemoveEditConfigContext (TextDocument.FilePath).Ignore (); + // editorConfigContext = null; + // } if (FilePath != TextDocument.FilePath && !string.IsNullOrEmpty (TextDocument.FilePath)) AutoSave.RemoveAutoSaveFile (TextDocument.FilePath); @@ -272,7 +272,7 @@ protected override void OnFileNameChanged () UpdateTextBufferRegistration (); - UpdateTextEditorOptions (null, null); + //UpdateTextEditorOptions (null, null); } protected override void OnOwnerChanged () @@ -280,7 +280,7 @@ protected override void OnOwnerChanged () base.OnOwnerChanged (); if (TextDocument != null) { - UpdateTextEditorOptions (null, null); + //UpdateTextEditorOptions (null, null); UpdateTextBufferRegistration (); } } @@ -312,19 +312,19 @@ protected override void OnDispose () UnsubscribeFromEvents (); - if (policyContainer != null) - policyContainer.PolicyChanged -= PolicyChanged; - if (editorConfigContext != null) { - editorConfigContext.CodingConventionsChangedAsync -= UpdateOptionsFromEditorConfigAsync; - EditorConfigService.RemoveEditConfigContext (FilePath).Ignore (); - } + //if (policyContainer != null) + // policyContainer.PolicyChanged -= PolicyChanged; + //if (editorConfigContext != null) { + //editorConfigContext.CodingConventionsChangedAsync -= UpdateOptionsFromEditorConfigAsync; + //EditorConfigService.RemoveEditConfigContext (FilePath).Ignore (); + //} base.OnDispose (); } protected virtual void SubscribeToEvents () { - sourceEditorOptions.Changed += UpdateTextEditorOptions; + //sourceEditorOptions.Changed += UpdateTextEditorOptions; TextDocument.DirtyStateChanged += HandleTextDocumentDirtyStateChanged; TextBuffer.Changed += HandleTextBufferChanged; TextView.Options.OptionChanged += TextBufferOptionsChanged; @@ -332,8 +332,8 @@ protected virtual void SubscribeToEvents () protected virtual void UnsubscribeFromEvents () { - if (sourceEditorOptions != null) - sourceEditorOptions.Changed -= UpdateTextEditorOptions; + // if (sourceEditorOptions != null) + // sourceEditorOptions.Changed -= UpdateTextEditorOptions; if (TextDocument != null) TextDocument.DirtyStateChanged -= HandleTextDocumentDirtyStateChanged; @@ -362,38 +362,38 @@ void UpdateLineNumberMarginOption () sourceEditorOptions.ShowLineNumberMargin); } - void UpdateTextEditorOptions (object sender, EventArgs e) - { - UpdateTextEditorOptionsAsync ().Forget (); - } + // void UpdateTextEditorOptions (object sender, EventArgs e) + // { + // UpdateTextEditorOptionsAsync ().Forget (); + // } - async Task UpdateTextEditorOptionsAsync () - { - UpdateLineNumberMarginOption (); + // async Task UpdateTextEditorOptionsAsync () + // { + // UpdateLineNumberMarginOption (); - var foldMargin = PropertyService.Get ("ShowFoldMargin"); - Imports.OutliningManagerService.GetOutliningManager (TextView).Enabled = foldMargin; + // var foldMargin = PropertyService.Get ("ShowFoldMargin"); + // Imports.OutliningManagerService.GetOutliningManager (TextView).Enabled = foldMargin; - var newPolicyContainer = (Owner as IPolicyProvider)?.Policies; - if (newPolicyContainer != policyContainer) { - if (policyContainer != null) - policyContainer.PolicyChanged -= PolicyChanged; - policyContainer = newPolicyContainer; - } - if (policyContainer != null) - policyContainer.PolicyChanged += PolicyChanged; - - var newEditorConfigContext = await EditorConfigService.GetEditorConfigContext (FilePath, default); - if (newEditorConfigContext != editorConfigContext) { - if (editorConfigContext != null) - editorConfigContext.CodingConventionsChangedAsync -= UpdateOptionsFromEditorConfigAsync; - editorConfigContext = newEditorConfigContext; - } - if (editorConfigContext != null) - editorConfigContext.CodingConventionsChangedAsync += UpdateOptionsFromEditorConfigAsync; + // var newPolicyContainer = (Owner as IPolicyProvider)?.Policies; + // if (newPolicyContainer != policyContainer) { + // if (policyContainer != null) + // policyContainer.PolicyChanged -= PolicyChanged; + // policyContainer = newPolicyContainer; + // } + // if (policyContainer != null) + // policyContainer.PolicyChanged += PolicyChanged; - await UpdateOptionsFromEditorConfigAsync (null, null); - } + // var newEditorConfigContext = await EditorConfigService.GetEditorConfigContext (FilePath, default); + // if (newEditorConfigContext != editorConfigContext) { + // if (editorConfigContext != null) + // editorConfigContext.CodingConventionsChangedAsync -= UpdateOptionsFromEditorConfigAsync; + // editorConfigContext = newEditorConfigContext; + // } + // if (editorConfigContext != null) + // editorConfigContext.CodingConventionsChangedAsync += UpdateOptionsFromEditorConfigAsync; + + // await UpdateOptionsFromEditorConfigAsync (null, null); + // } void ClearOptionValue(string optionName) { @@ -438,179 +438,179 @@ private void UpdateOptionsFromPolicy() #endif } - private Task UpdateOptionsFromEditorConfigAsync (object sender, CodingConventionsChangedEventArgs args) - { - // Set base options first, then override with editorconfig values - UpdateOptionsFromPolicy (); - - if (editorConfigContext == null) - return Task.CompletedTask; - - if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetIndentStyle (out var indentStyle)) - SetOptionValue (DefaultOptions.ConvertTabsToSpacesOptionName, indentStyle == IndentStyle.Spaces); - if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetTabWidth (out var tabWidth)) - SetOptionValue (DefaultOptions.TabSizeOptionName, tabWidth); - if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetIndentSize (out var indentSize)) - SetOptionValue (DefaultOptions.IndentSizeOptionName, indentSize); - if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetLineEnding (out var lineEnding)) - SetOptionValue (DefaultOptions.NewLineCharacterOptionName, lineEnding); - if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetAllowTrailingWhitespace (out var allowTrailingWhitespace)) - SetOptionValue (DefaultOptions.TrimTrailingWhiteSpaceOptionName, !allowTrailingWhitespace); - - var setVerticalRulers = false; - int [] verticalRulers = null; - - // "Show column ruler" preference still needs to be checked, regardless of whether or not editorconfig - // has a setting for where rulers should appear - if (PropertyService.Get ("ShowRuler")) { - if (editorConfigContext.CurrentConventions.TryGetConventionValue (EditorConfigService.RulersConvention, out var rulers)) { - setVerticalRulers = true; - if (!string.IsNullOrEmpty (rulers)) { - verticalRulers = Array.ConvertAll (rulers.Split (','), val => { - if (int.TryParse (val, out var col)) - return col; - return 0; - }); - } - } else if (editorConfigContext.CurrentConventions.TryGetConventionValue (EditorConfigService.MaxLineLengthConvention, out var maxLineLength)) { - if (maxLineLength != "off" && int.TryParse (maxLineLength, out var i)) { - setVerticalRulers = true; - verticalRulers = new [] { i }; - } else - setVerticalRulers = false; - } - } - -#if !WINDOWS - if (setVerticalRulers) - EditorOptions.SetOptionValue (DefaultTextViewOptions.VerticalRulersName, verticalRulers ?? Array.Empty ()); -#endif - - return Task.CompletedTask; - } - - private void PolicyChanged (object sender, PolicyChangedEventArgs e) - => UpdateTextEditorOptions (sender, e); - - protected override object OnGetContent (Type type) - { - if (contentProviders != null) { - foreach (var provider in contentProviders) { - var content = provider.GetContent (TextView, type); - if (content != null) { - return content; - } - } - } - return GetIntrinsicType (type); - } - - protected override IEnumerable OnGetContents (Type type) - { - if (contentProviders != null) { - foreach (var provider in contentProviders) { - var contents = provider.GetContents (TextView, type); - if (contents != null) { - foreach (var content in contents) - yield return content; - } - } - } - - var intrinsicType = GetIntrinsicType (type); - if (intrinsicType != null) { - yield return intrinsicType; - } - } - - object GetIntrinsicType (Type type) - { - if (type.IsInstanceOfType (TextBuffer)) - return TextBuffer; - if (type.IsInstanceOfType (TextDocument)) - return TextDocument; - if (type.IsInstanceOfType (TextView)) - return TextView; - if (type.IsInstanceOfType (this)) - return this; - return null; - } - - Task Load (bool reloading) - { - // We actually load initial content at construction time, so this - // overload only needs to cover reload and autosave scenarios - - if (warnOverwrite) { - warnOverwrite = false; - DismissInfoBar (); - ShowNotification = false; - } - - if (reloading) { - TextDocument.Reload (); - } else if (AutoSave.AutoSaveExists (FilePath)) { - var autosaveContent = AutoSave.LoadAutoSave (FilePath); - - MarkDirty (); - warnOverwrite = true; - - // Set editor read-only until user picks one of the above options. - var setWritable = !TextView.Options.DoesViewProhibitUserInput (); - if (setWritable) - TextView.Options.SetOptionValue (DefaultTextViewOptions.ViewProhibitUserInputId, true); - - var (primaryMessageText, secondaryMessageText) = SplitMessageString ( - BrandingService.BrandApplicationName (GettextCatalog.GetString ( - "An autosave file has been found for this file.\n" + - "This could mean that another instance of MonoDevelop is editing this " + - "file, or that MonoDevelop crashed with unsaved changes.\n\n" + - "Do you want to use the original file, or load from the autosave file?"))); - - PresentInfobar ( - primaryMessageText, - secondaryMessageText, - new InfoBarAction ( - GetButtonString (GettextCatalog.GetString ("_Use original file")), - UseOriginalFile), - new InfoBarAction ( - GetButtonString (GettextCatalog.GetString ("_Load from autosave")), - LoadFromAutosave, - isDefault: true)); - - void OnActionSelected () - { - DismissInfoBar (); - if (setWritable) - TextView.Options.SetOptionValue (DefaultTextViewOptions.ViewProhibitUserInputId, false); - } - - void LoadFromAutosave () - { - try { - AutoSave.RemoveAutoSaveFile (FilePath); - ReplaceContent (autosaveContent.Text, autosaveContent.Encoding); - } catch (Exception e) { - LoggingService.LogError ("Could not load the autosave file", e); - } finally { - OnActionSelected (); - } - } - - void UseOriginalFile () - { - try { - AutoSave.RemoveAutoSaveFile (FilePath); - } catch (Exception e) { - LoggingService.LogError ("Could not remove the autosave file", e); - } finally { - OnActionSelected (); - } - } - } - - return Task.CompletedTask; - } +// private Task UpdateOptionsFromEditorConfigAsync (object sender, CodingConventionsChangedEventArgs args) +// { +// // Set base options first, then override with editorconfig values +// UpdateOptionsFromPolicy (); + +// if (editorConfigContext == null) +// return Task.CompletedTask; + +// if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetIndentStyle (out var indentStyle)) +// SetOptionValue (DefaultOptions.ConvertTabsToSpacesOptionName, indentStyle == IndentStyle.Spaces); +// if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetTabWidth (out var tabWidth)) +// SetOptionValue (DefaultOptions.TabSizeOptionName, tabWidth); +// if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetIndentSize (out var indentSize)) +// SetOptionValue (DefaultOptions.IndentSizeOptionName, indentSize); +// if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetLineEnding (out var lineEnding)) +// SetOptionValue (DefaultOptions.NewLineCharacterOptionName, lineEnding); +// if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetAllowTrailingWhitespace (out var allowTrailingWhitespace)) +// SetOptionValue (DefaultOptions.TrimTrailingWhiteSpaceOptionName, !allowTrailingWhitespace); + +// var setVerticalRulers = false; +// int [] verticalRulers = null; + +// // "Show column ruler" preference still needs to be checked, regardless of whether or not editorconfig +// // has a setting for where rulers should appear +// if (PropertyService.Get ("ShowRuler")) { +// if (editorConfigContext.CurrentConventions.TryGetConventionValue (EditorConfigService.RulersConvention, out var rulers)) { +// setVerticalRulers = true; +// if (!string.IsNullOrEmpty (rulers)) { +// verticalRulers = Array.ConvertAll (rulers.Split (','), val => { +// if (int.TryParse (val, out var col)) +// return col; +// return 0; +// }); +// } +// } else if (editorConfigContext.CurrentConventions.TryGetConventionValue (EditorConfigService.MaxLineLengthConvention, out var maxLineLength)) { +// if (maxLineLength != "off" && int.TryParse (maxLineLength, out var i)) { +// setVerticalRulers = true; +// verticalRulers = new [] { i }; +// } else +// setVerticalRulers = false; +// } +// } + +// #if !WINDOWS +// if (setVerticalRulers) +// EditorOptions.SetOptionValue (DefaultTextViewOptions.VerticalRulersName, verticalRulers ?? Array.Empty ()); +// #endif + +// return Task.CompletedTask; +// } + +// private void PolicyChanged (object sender, PolicyChangedEventArgs e) +// => UpdateTextEditorOptions (sender, e); + +// protected override object OnGetContent (Type type) +// { +// if (contentProviders != null) { +// foreach (var provider in contentProviders) { +// var content = provider.GetContent (TextView, type); +// if (content != null) { +// return content; +// } +// } +// } +// return GetIntrinsicType (type); +// } + +// protected override IEnumerable OnGetContents (Type type) +// { +// if (contentProviders != null) { +// foreach (var provider in contentProviders) { +// var contents = provider.GetContents (TextView, type); +// if (contents != null) { +// foreach (var content in contents) +// yield return content; +// } +// } +// } + +// var intrinsicType = GetIntrinsicType (type); +// if (intrinsicType != null) { +// yield return intrinsicType; +// } +// } + +// object GetIntrinsicType (Type type) +// { +// if (type.IsInstanceOfType (TextBuffer)) +// return TextBuffer; +// if (type.IsInstanceOfType (TextDocument)) +// return TextDocument; +// if (type.IsInstanceOfType (TextView)) +// return TextView; +// if (type.IsInstanceOfType (this)) +// return this; +// return null; +// } + +// Task Load (bool reloading) +// { +// // We actually load initial content at construction time, so this +// // overload only needs to cover reload and autosave scenarios + +// if (warnOverwrite) { +// warnOverwrite = false; +// DismissInfoBar (); +// ShowNotification = false; +// } + +// if (reloading) { +// TextDocument.Reload (); +// } else if (AutoSave.AutoSaveExists (FilePath)) { +// var autosaveContent = AutoSave.LoadAutoSave (FilePath); + +// MarkDirty (); +// warnOverwrite = true; + +// // Set editor read-only until user picks one of the above options. +// var setWritable = !TextView.Options.DoesViewProhibitUserInput (); +// if (setWritable) +// TextView.Options.SetOptionValue (DefaultTextViewOptions.ViewProhibitUserInputId, true); + +// var (primaryMessageText, secondaryMessageText) = SplitMessageString ( +// BrandingService.BrandApplicationName (GettextCatalog.GetString ( +// "An autosave file has been found for this file.\n" + +// "This could mean that another instance of MonoDevelop is editing this " + +// "file, or that MonoDevelop crashed with unsaved changes.\n\n" + +// "Do you want to use the original file, or load from the autosave file?"))); + +// PresentInfobar ( +// primaryMessageText, +// secondaryMessageText, +// new InfoBarAction ( +// GetButtonString (GettextCatalog.GetString ("_Use original file")), +// UseOriginalFile), +// new InfoBarAction ( +// GetButtonString (GettextCatalog.GetString ("_Load from autosave")), +// LoadFromAutosave, +// isDefault: true)); + +// void OnActionSelected () +// { +// DismissInfoBar (); +// if (setWritable) +// TextView.Options.SetOptionValue (DefaultTextViewOptions.ViewProhibitUserInputId, false); +// } + +// void LoadFromAutosave () +// { +// try { +// AutoSave.RemoveAutoSaveFile (FilePath); +// ReplaceContent (autosaveContent.Text, autosaveContent.Encoding); +// } catch (Exception e) { +// LoggingService.LogError ("Could not load the autosave file", e); +// } finally { +// OnActionSelected (); +// } +// } + +// void UseOriginalFile () +// { +// try { +// AutoSave.RemoveAutoSaveFile (FilePath); +// } catch (Exception e) { +// LoggingService.LogError ("Could not remove the autosave file", e); +// } finally { +// OnActionSelected (); +// } +// } +// } + +// return Task.CompletedTask; +// } /// /// Replace document content with new content. This marks the document as dirty. @@ -779,7 +779,7 @@ void ReloadFromDisk () if (IsDisposed || !File.Exists (FilePath)) return; - Load (true); + ////Load (true); ShowNotification = false; } catch (Exception ex) { MessageService.ShowError ("Could not reload the file.", ex); diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Core.csproj b/main/src/core/MonoDevelop.Core/MonoDevelop.Core.csproj index f2c4d8c12df..36139d27727 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Core.csproj +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Core.csproj @@ -88,7 +88,7 @@ - + @@ -137,7 +137,7 @@ - + diff --git a/main/src/core/MonoDevelop.Ide/ExtensionModel/MonoDevelop.Ide.addin.xml b/main/src/core/MonoDevelop.Ide/ExtensionModel/MonoDevelop.Ide.addin.xml index cacaf7a52cc..878a0fe7820 100644 --- a/main/src/core/MonoDevelop.Ide/ExtensionModel/MonoDevelop.Ide.addin.xml +++ b/main/src/core/MonoDevelop.Ide/ExtensionModel/MonoDevelop.Ide.addin.xml @@ -1,6 +1,6 @@ - + @@ -431,7 +431,7 @@ - + diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/DefaultSourceEditorOptions.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/DefaultSourceEditorOptions.cs index 53745babf69..06539353847 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/DefaultSourceEditorOptions.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/DefaultSourceEditorOptions.cs @@ -28,7 +28,7 @@ using MonoDevelop.Ide.Gui.Content; using MonoDevelop.Ide.Fonts; using MonoDevelop.Ide.Editor.Extension; -using Microsoft.VisualStudio.CodingConventions; +//using Microsoft.VisualStudio.CodingConventions; using System.Threading.Tasks; using MonoDevelop.Ide.TypeSystem; @@ -58,7 +58,7 @@ public sealed class DefaultSourceEditorOptions : ITextEditorOptions static DefaultSourceEditorOptions instance; static ITextEditorOptions plainEditor; static bool inited; - ICodingConventionContext context; + //ICodingConventionContext context; public static DefaultSourceEditorOptions Instance { get { @@ -187,8 +187,8 @@ bool ITextEditorOptions.RemoveTrailingWhitespaces { get { return DefaultSourceEditorOptions.Instance.RemoveTrailingWhitespaces; } - } - + } + [Obsolete ("Old editor")] bool ITextEditorOptions.WrapLines { get { @@ -277,13 +277,13 @@ void HandlePolicyChanged (object sender, MonoDevelop.Projects.Policies.PolicyCha }); IdeApp.Preferences.ColorScheme.Changed += OnColorSchemeChanged; - IdeApp.Preferences.Editor.FollowCodingConventions.Changed += OnFollowCodingConventionsChanged; + //IdeApp.Preferences.Editor.FollowCodingConventions.Changed += OnFollowCodingConventionsChanged; } - void OnFollowCodingConventionsChanged (object sender, EventArgs e) - { - UpdateContextOptions (null, null).Ignore (); - } + // void OnFollowCodingConventionsChanged (object sender, EventArgs e) + // { + // UpdateContextOptions (null, null).Ignore (); + // } void UpdateFont () @@ -319,57 +319,57 @@ public DefaultSourceEditorOptions WithTextStyle (TextStylePolicy policy) return result; } - internal void SetContext (ICodingConventionContext context) - { - if (this.context == context) - return; - if (this.context != null) - this.context.CodingConventionsChangedAsync -= UpdateContextOptions; - this.context = context; - context.CodingConventionsChangedAsync += UpdateContextOptions; - UpdateContextOptions (null, null).Ignore (); - } - - private Task UpdateContextOptions (object sender, CodingConventionsChangedEventArgs arg) - { - if (context == null) - return Task.CompletedTask; - - bool followCodingConventions = IdeApp.Preferences.Editor.FollowCodingConventions; - - defaultEolMarkerFromContext = null; - if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetLineEnding (out string eolMarker)) - defaultEolMarkerFromContext = eolMarker; - - tabsToSpacesFromContext = null; - if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetIndentStyle (out Microsoft.VisualStudio.CodingConventions.IndentStyle result)) - tabsToSpacesFromContext = result == Microsoft.VisualStudio.CodingConventions.IndentStyle.Spaces; - - indentationSizeFromContext = null; - if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetIndentSize (out int indentSize)) - indentationSizeFromContext = indentSize; - - removeTrailingWhitespacesFromContext = null; - if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetAllowTrailingWhitespace (out bool allowTrailing)) - removeTrailingWhitespacesFromContext = !allowTrailing; - - tabSizeFromContext = null; - if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetTabWidth (out int tSize)) - tabSizeFromContext = tSize; - - rulerColumnFromContext = null; - showRulerFromContext = null; - if (followCodingConventions && context.CurrentConventions.TryGetConventionValue (EditorConfigService.MaxLineLengthConvention, out string maxLineLength)) { - if (maxLineLength != "off" && int.TryParse (maxLineLength, out int i)) { - rulerColumnFromContext = i; - showRulerFromContext = true; - } else { - showRulerFromContext = false; - } - } - this.FireChange (); - return Task.CompletedTask; - } + // internal void SetContext (ICodingConventionContext context) + // { + // if (this.context == context) + // return; + // if (this.context != null) + // this.context.CodingConventionsChangedAsync -= UpdateContextOptions; + // this.context = context; + // context.CodingConventionsChangedAsync += UpdateContextOptions; + // UpdateContextOptions (null, null).Ignore (); + // } + + // private Task UpdateContextOptions (object sender, CodingConventionsChangedEventArgs arg) + // { + // if (context == null) + // return Task.CompletedTask; + + // bool followCodingConventions = IdeApp.Preferences.Editor.FollowCodingConventions; + + // defaultEolMarkerFromContext = null; + // if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetLineEnding (out string eolMarker)) + // defaultEolMarkerFromContext = eolMarker; + + // tabsToSpacesFromContext = null; + // //if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetIndentStyle (out Microsoft.VisualStudio.CodingConventions.IndentStyle result)) + // // tabsToSpacesFromContext = result == Microsoft.VisualStudio.CodingConventions.IndentStyle.Spaces; + + // indentationSizeFromContext = null; + // if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetIndentSize (out int indentSize)) + // indentationSizeFromContext = indentSize; + + // removeTrailingWhitespacesFromContext = null; + // if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetAllowTrailingWhitespace (out bool allowTrailing)) + // removeTrailingWhitespacesFromContext = !allowTrailing; + + // tabSizeFromContext = null; + // if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetTabWidth (out int tSize)) + // tabSizeFromContext = tSize; + + // rulerColumnFromContext = null; + // showRulerFromContext = null; + // if (followCodingConventions && context.CurrentConventions.TryGetConventionValue (EditorConfigService.MaxLineLengthConvention, out string maxLineLength)) { + // if (maxLineLength != "off" && int.TryParse (maxLineLength, out int i)) { + // rulerColumnFromContext = i; + // showRulerFromContext = true; + // } else { + // showRulerFromContext = false; + // } + // } + // this.FireChange (); + // return Task.CompletedTask; + // } #region new options @@ -929,14 +929,15 @@ public bool SmartBackspace{ } #endregion - public void Dispose () - { - IdeServices.FontService.RemoveCallback (UpdateFont); - IdeApp.Preferences.ColorScheme.Changed -= OnColorSchemeChanged; - IdeApp.Preferences.Editor.FollowCodingConventions.Changed -= OnFollowCodingConventionsChanged; - if (context != null) - context.CodingConventionsChangedAsync -= UpdateContextOptions; - } + public void Dispose () + { + // IdeServices.FontService.RemoveCallback (UpdateFont); + // IdeApp.Preferences.ColorScheme.Changed -= OnColorSchemeChanged; + // IdeApp.Preferences.Editor.FollowCodingConventions.Changed -= OnFollowCodingConventionsChanged; + // if (context != null) + // context.CodingConventionsChangedAsync -= UpdateContextOptions; + + } void OnChanged (EventArgs args) { diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/EditorConfigService.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/EditorConfigService.cs index cfbe6a55127..5ecf1e66b5e 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/EditorConfigService.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/EditorConfigService.cs @@ -23,176 +23,177 @@ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -using System; -using System.Collections.Immutable; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.CodingConventions; -using System.Collections.Generic; -using MonoDevelop.Core; -using MonoDevelop.Projects; - -namespace MonoDevelop.Ide.Editor -{ - static class EditorConfigService - { - public readonly static string MaxLineLengthConvention = "max_line_length"; - public readonly static string RulersConvention = "rulers"; - - readonly static object contextCacheLock = new object (); - readonly static ICodingConventionsManager codingConventionsManager = CodingConventionsManagerFactory.CreateCodingConventionsManager (new ConventionsFileManager()); - static ImmutableDictionary contextCache = ImmutableDictionary.Empty; - - public static async Task GetEditorConfigContext (string fileName, CancellationToken token = default (CancellationToken)) - { - if (string.IsNullOrEmpty (fileName)) - return null; - try { - var directory = Path.GetDirectoryName (fileName); - if (string.IsNullOrEmpty (directory)) { - return null; - } - - // HACK: Work around for a library issue https://github.com/mono/monodevelop/issues/6104 - if (directory == "/") { - return null; - } - } catch { - return null; - } - if (contextCache.TryGetValue (fileName, out var oldresult)) - return oldresult; - try { - var result = await codingConventionsManager.GetConventionContextAsync (fileName, token); - lock (contextCacheLock) { - // check if another thread already requested a coding convention context and ensure - // that only one is alive. - if (contextCache.TryGetValue (fileName, out var result2)) { - if (result != result2) - result.Dispose (); - return result2; - } - contextCache = contextCache.SetItem (fileName, result); - } - return result; - } catch (OperationCanceledException) { - return null; - } catch (Exception e) { - LoggingService.LogError ("Error while getting coding conventions,", e); - return null; - } - } - - public static Task RemoveEditConfigContext (string fileName) - { - return Task.Run (() => { - ICodingConventionContext ctx; - lock (contextCacheLock) { - if (!contextCache.TryGetValue (fileName, out ctx)) - return; - contextCache = contextCache.Remove (fileName); - } - if (ctx != null) - ctx.Dispose (); - }); - } - - class ConventionsFileManager : IFileWatcher - { - HashSet watchedFiles = new HashSet (); - - public event ConventionsFileChangedAsyncEventHandler ConventionFileChanged; - public event ContextFileMovedAsyncEventHandler ContextFileMoved; - - public ConventionsFileManager () - { - FileService.FileChanged += FileService_FileChanged; - FileService.FileRemoved += FileService_FileRemoved; - FileService.FileMoved += FileService_FileMoved; - FileService.FileRenamed += FileService_FileMoved; - } - - void FileService_FileMoved (object sender, FileCopyEventArgs e) - { - lock (watchedFiles) { - foreach (var file in e) { - if (watchedFiles.Remove (file.SourceFile)) { - ContextFileMoved?.Invoke (this, new ContextFileMovedEventArgs (file.SourceFile, file.TargetFile)); - if (file.SourceFile == file.TargetFile) { - StartWatching (file.TargetFile.FileName, file.TargetFile.ParentDirectory); - } - } - } - } - } - - void FileService_FileChanged (object sender, FileEventArgs e) - { - lock (watchedFiles) { - foreach (var file in e) { - if (watchedFiles.Contains (file.FileName)) { - ConventionFileChanged?.Invoke (this, new ConventionsFileChangeEventArgs (file.FileName.FileName, file.FileName.ParentDirectory, ChangeType.FileModified)); - } - } - } - } - - void FileService_FileRemoved (object sender, FileEventArgs e) - { - lock (watchedFiles) { - foreach (var file in e) { - if (watchedFiles.Remove (file.FileName)) { - ConventionFileChanged?.Invoke (this, new ConventionsFileChangeEventArgs (file.FileName.FileName, file.FileName.ParentDirectory, ChangeType.FileDeleted)); - WatchDirectories (); - } - } - } - } - - public void Dispose () - { - FileService.FileMoved -= FileService_FileMoved; - FileService.FileRenamed -= FileService_FileMoved; - FileService.FileRemoved -= FileService_FileRemoved; - FileService.FileChanged -= FileService_FileChanged; - FileWatcherService.WatchDirectories (this, null).Ignore (); - lock (watchedFiles) { - watchedFiles = null; - } - } - - public void StartWatching (string fileName, string directoryPath) - { - lock (watchedFiles) { - var key = directoryPath + Path.DirectorySeparatorChar.ToString () + fileName; - - if (!File.Exists (key)) - return; - - if (!watchedFiles.Add (key)) - return; - - WatchDirectories (); - } - } - - public void StopWatching (string fileName, string directoryPath) - { - lock (watchedFiles) { - var key = directoryPath + Path.DirectorySeparatorChar.ToString () + fileName; - if (watchedFiles.Remove (key)) { - WatchDirectories (); - } - } - } - - void WatchDirectories () - { - var directories = watchedFiles.Count == 0 ? null : watchedFiles.Select (file => new FilePath (file).ParentDirectory); - FileWatcherService.WatchDirectories (this, directories).Ignore (); - } - } - } -} +//using System; +//using System.Collections.Immutable; +//using System.IO; +//using System.Linq; +//using System.Threading; +//using System.Threading.Tasks; +//using Microsoft.VisualStudio.CodingConventions; +//using System.Collections.Generic; +//using MonoDevelop.Core; +//using MonoDevelop.Projects; + +//namespace MonoDevelop.Ide.Editor +//{ + //static class EditorConfigService + //{ + //public readonly static string MaxLineLengthConvention = "max_line_length"; + //public readonly static string RulersConvention = "rulers"; + + //readonly static object contextCacheLock = new object (); + //readonly static ICodingConventionsManager codingConventionsManager = CodingConventionsManagerFactory.CreateCodingConventionsManager (new ConventionsFileManager()); + //static ImmutableDictionary contextCache = ImmutableDictionary.Empty; + //public static class GetEditorConfigContext (string fileName, CancellationToken token = default (CancellationToken)) + // public static async Task GetEditorConfigContext (string fileName, CancellationToken token = default (CancellationToken)) + // { + // if (string.IsNullOrEmpty (fileName)) + // return null; + // try { + // var directory = Path.GetDirectoryName (fileName); + // if (string.IsNullOrEmpty (directory)) { + // return null; + // } + + // // HACK: Work around for a library issue https://github.com/mono/monodevelop/issues/6104 + // if (directory == "/") { + // return null; + // } + // } catch { + // return null; + // } + // if (contextCache.TryGetValue (fileName, out var oldresult)) + // return oldresult; + // try { + // var result = await codingConventionsManager.GetConventionContextAsync (fileName, token); + // lock (contextCacheLock) { + // // check if another thread already requested a coding convention context and ensure + // // that only one is alive. + // if (contextCache.TryGetValue (fileName, out var result2)) { + // if (result != result2) + // result.Dispose (); + // return result2; + // } + // contextCache = contextCache.SetItem (fileName, result); + // } + // return result; + // } catch (OperationCanceledException) { + // return null; + // } catch (Exception e) { + // LoggingService.LogError ("Error while getting coding conventions,", e); + // return null; + // } + // } + + // public static Task RemoveEditConfigContext (string fileName) + // { + // return Task.Run (() => { + // ICodingConventionContext ctx; + // lock (contextCacheLock) { + // if (!contextCache.TryGetValue (fileName, out ctx)) + // return; + // contextCache = contextCache.Remove (fileName); + // } + // if (ctx != null) + // ctx.Dispose (); + // }); + // } + + // class ConventionsFileManager : IFileWatcher + // { + // HashSet watchedFiles = new HashSet (); + + // public event ConventionsFileChangedAsyncEventHandler ConventionFileChanged; + // public event ContextFileMovedAsyncEventHandler ContextFileMoved; + + // public ConventionsFileManager () + // { + // FileService.FileChanged += FileService_FileChanged; + // FileService.FileRemoved += FileService_FileRemoved; + // FileService.FileMoved += FileService_FileMoved; + // FileService.FileRenamed += FileService_FileMoved; + // } + + // void FileService_FileMoved (object sender, FileCopyEventArgs e) + // { + // lock (watchedFiles) { + // foreach (var file in e) { + // if (watchedFiles.Remove (file.SourceFile)) { + // ContextFileMoved?.Invoke (this, new ContextFileMovedEventArgs (file.SourceFile, file.TargetFile)); + // if (file.SourceFile == file.TargetFile) { + // StartWatching (file.TargetFile.FileName, file.TargetFile.ParentDirectory); + // } + // } + // } + // } + // } + + // void FileService_FileChanged (object sender, FileEventArgs e) + // { + // lock (watchedFiles) { + // foreach (var file in e) { + // if (watchedFiles.Contains (file.FileName)) { + // ConventionFileChanged?.Invoke (this, new ConventionsFileChangeEventArgs (file.FileName.FileName, file.FileName.ParentDirectory, ChangeType.FileModified)); + // } + // } + // } + // } + + // void FileService_FileRemoved (object sender, FileEventArgs e) + // { + // lock (watchedFiles) { + // foreach (var file in e) { + // if (watchedFiles.Remove (file.FileName)) { + // ConventionFileChanged?.Invoke (this, new ConventionsFileChangeEventArgs (file.FileName.FileName, file.FileName.ParentDirectory, ChangeType.FileDeleted)); + // WatchDirectories (); + // } + // } + // } + // } + + // public void Dispose () + // { + // FileService.FileMoved -= FileService_FileMoved; + // FileService.FileRenamed -= FileService_FileMoved; + // FileService.FileRemoved -= FileService_FileRemoved; + // FileService.FileChanged -= FileService_FileChanged; + // FileWatcherService.WatchDirectories (this, null).Ignore (); + // lock (watchedFiles) { + // watchedFiles = null; + // } + // } + + // public void StartWatching (string fileName, string directoryPath) + // { + // lock (watchedFiles) { + // var key = directoryPath + Path.DirectorySeparatorChar.ToString () + fileName; + + // if (!File.Exists (key)) + // return; + + // if (!watchedFiles.Add (key)) + // return; + + // WatchDirectories (); + // } + // } + + // public void StopWatching (string fileName, string directoryPath) + // { + // lock (watchedFiles) { + + // var key = directoryPath + Path.DirectorySeparatorChar.ToString () + fileName; + // if (watchedFiles.Remove (key)) { + // WatchDirectories (); + // } + // } + // } + + // void WatchDirectories () + // { + // var directories = watchedFiles.Count == 0 ? null : watchedFiles.Select (file => new FilePath (file).ParentDirectory); + // FileWatcherService.WatchDirectories (this, directories).Ignore (); + // } + // } + // } +//} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/TextEditor.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/TextEditor.cs index aeeb4f2e1a8..c96955a0475 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/TextEditor.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/TextEditor.cs @@ -1071,18 +1071,18 @@ void TextEditor_ZoomLevelChanged (object sender, EventArgs e) async void TextEditor_FileNameChanged (object sender, EventArgs e) { - fileTypeCondition.SetFileName (FileName); + //fileTypeCondition.SetFileName (FileName); // This is a sync call to remove from the cache, then async to dispose the context after the load is awaited. - EditorConfigService.RemoveEditConfigContext (FileName).Ignore (); + //EditorConfigService.RemoveEditConfigContext (FileName).Ignore (); // There is no use to try and create a cached context if we won't use it. - if (!(Options is DefaultSourceEditorOptions options)) - return; + //if (!(Options is DefaultSourceEditorOptions options)) + // return; - var context = await EditorConfigService.GetEditorConfigContext (FileName); - if (context != null) - options.SetContext (context); + //var context = await EditorConfigService.GetEditorConfigContext (FileName); + //if (context != null) + // options.SetContext (context); } void TextEditor_MimeTypeChanged (object sender, EventArgs e) diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/TextEditorViewContent.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/TextEditorViewContent.cs index b262e0c3cfd..472a9e8f3ca 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/TextEditorViewContent.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/TextEditorViewContent.cs @@ -236,10 +236,10 @@ async Task UpdateStyleParent (WorkspaceObject owner, string mimeType, Cancellati policyContainer.PolicyChanged += HandlePolicyChanged; ((DefaultSourceEditorOptions)textEditor.Options).UpdateStylePolicy (currentPolicy); - var context = await EditorConfigService.GetEditorConfigContext (textEditor.FileName, token); - if (context == null) - return; - ((DefaultSourceEditorOptions)textEditor.Options).SetContext (context); + //var context = await EditorConfigService.GetEditorConfigContext (textEditor.FileName, token); + //if (context == null) + // return; + // ((DefaultSourceEditorOptions)textEditor.Options).SetContext (context); } void HandlePolicyChanged (object sender, MonoDevelop.Projects.Policies.PolicyChangedEventArgs args) @@ -325,8 +325,8 @@ internal protected override ProjectReloadCapability OnGetProjectReloadCapability protected override IEnumerable OnGetContents (Type type) { foreach (var r in base.OnGetContents (type)) - yield return r; - + yield return r; + if (textEditorImpl != null) { if (type == typeof(ITextBuffer)) { yield return textEditor.TextView.TextBuffer; @@ -379,7 +379,7 @@ protected override void OnDispose () if (!string.IsNullOrEmpty (textEditorImpl.ContentName)) AutoSave.RemoveAutoSaveFile (textEditorImpl.ContentName); - EditorConfigService.RemoveEditConfigContext (textEditor.FileName).Ignore (); + //EditorConfigService.RemoveEditConfigContext (textEditor.FileName).Ignore (); textEditorImpl.DirtyChanged -= HandleDirtyChanged; textEditor.MimeTypeChanged -= UpdateTextEditorOptions; textEditor.TextChanged -= HandleTextChanged; diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/SingleFileDescriptionTemplate.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/SingleFileDescriptionTemplate.cs index 80334f39e95..ad2aa016065 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/SingleFileDescriptionTemplate.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/SingleFileDescriptionTemplate.cs @@ -482,12 +482,12 @@ public virtual async Task CreateFileContentAsync (SolutionFolderItem pol : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy (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; - } + // 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 (); @@ -509,12 +509,12 @@ public virtual async Task CreateFileContentAsync (SolutionFolderItem pol bool convertTabsToSpaces = textPolicy.TabsToSpaces; int tabWidth = textPolicy.TabWidth; - if (ctx != null) { - if (ctx.CurrentConventions.UniversalConventions.TryGetIndentStyle (out Microsoft.VisualStudio.CodingConventions.IndentStyle result)) - convertTabsToSpaces = result == Microsoft.VisualStudio.CodingConventions.IndentStyle.Spaces; - if (ctx.CurrentConventions.UniversalConventions.TryGetTabWidth (out int editorConfigTabWidth)) - tabWidth = editorConfigTabWidth; - } + //if (ctx != null) { + //if (ctx.CurrentConventions.UniversalConventions.TryGetIndentStyle (out Microsoft.VisualStudio.CodingConventions.IndentStyle result)) + //convertTabsToSpaces = result == Microsoft.VisualStudio.CodingConventions.IndentStyle.Spaces; + //if (ctx.CurrentConventions.UniversalConventions.TryGetTabWidth (out int editorConfigTabWidth)) + // tabWidth = editorConfigTabWidth; + //} var tabToSpaces = convertTabsToSpaces ? new string (' ', tabWidth) : null; IDocumentLine lastLine = null; @@ -529,13 +529,13 @@ public virtual async Task CreateFileContentAsync (SolutionFolderItem pol } 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); - } - } - ctx.Dispose (); + //if (ctx != null && lastLine != null && lastLine.Length > 0) { + // if (ctx.CurrentConventions.UniversalConventions.TryGetRequireFinalNewline (out bool requireNewLine)) { + // if (requireNewLine) + // ms.Write (eolMarkerBytes, 0, eolMarkerBytes.Length); + // } + //} + //ctx.Dispose (); ms.Position = 0; return ms; } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.csproj b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.csproj index d8d54222f30..2ecf6a4fcf2 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.csproj +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.csproj @@ -55,7 +55,7 @@ - + From 5cadc4b998d39160a1d08575ea9163de7b77f6ea Mon Sep 17 00:00:00 2001 From: MakiWolf Date: Sun, 23 Jul 2023 22:55:44 +0200 Subject: [PATCH 2/6] comment out unit tests --- .../EditorConfigTests.cs | 324 +++++++++--------- 1 file changed, 162 insertions(+), 162 deletions(-) diff --git a/main/tests/Ide.Tests/MonoDevelop.Ide.Editor/EditorConfigTests.cs b/main/tests/Ide.Tests/MonoDevelop.Ide.Editor/EditorConfigTests.cs index 10094a00f96..9397909862d 100644 --- a/main/tests/Ide.Tests/MonoDevelop.Ide.Editor/EditorConfigTests.cs +++ b/main/tests/Ide.Tests/MonoDevelop.Ide.Editor/EditorConfigTests.cs @@ -24,165 +24,165 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -using System.IO; -using NUnit.Framework; -using UnitTests; -using System.Threading; -using GuiUnit; -using System; -using System.Threading.Tasks; -using MonoDevelop.Ide.TextEditing; - -namespace MonoDevelop.Ide.Editor -{ - [TestFixture] - [RequireService(typeof(TextEditorService))] - class EditorConfigTests : IdeTestBase - { - - static async Task InvokeEditConfigTest (string editConfig, Action test) - { - string tempPath; - int i = 0; - while (true) { - tempPath = Path.Combine (Path.GetTempPath (), Path.GetRandomFileName ()); - if (!File.Exists (tempPath)) - break; - if (i++ > 100) - Assert.Fail ("Can't create random path."); - } - - Directory.CreateDirectory (tempPath); - try { - string editorConfigFile = Path.Combine (tempPath, ".editorconfig"); - File.WriteAllText (editorConfigFile, editConfig); - var editor = TextEditorFactory.CreateNewEditor (); - string fileName = Path.Combine (tempPath, "a.cs"); - try { - using (var ctx = await EditorConfigService.GetEditorConfigContext (fileName)) { - ((DefaultSourceEditorOptions)editor.Options).SetContext (ctx); - test (editor); - } - } finally { - await EditorConfigService.RemoveEditConfigContext (fileName); - } - } finally { - Directory.Delete (tempPath, true); - } - } - - [Test] - public async Task Test_indent_style () - { - await InvokeEditConfigTest (@" -root = true -[*.cs] -indent_style = space -", editor => { - Assert.AreEqual (true, editor.Options.TabsToSpaces); - }); - await InvokeEditConfigTest (@" -root = true -[*.cs] -indent_style = tab -", editor => { - Assert.AreEqual (false, editor.Options.TabsToSpaces); - }); - } - - [Test] - public async Task Test_indent_size () - { - await InvokeEditConfigTest (@" -root = true -[*.cs] -indent_size = 42 -", editor => { - Assert.AreEqual (42, editor.Options.IndentationSize); - }); - } - - [Test] - public async Task Test_tab_width () - { - await InvokeEditConfigTest (@" -root = true -[*.cs] -tab_width = 42 -", editor => { - Assert.AreEqual (42, editor.Options.TabSize); - }); - } - - [Test] - public async Task Test_end_of_line () - { - await InvokeEditConfigTest (@" -root = true -[*.cs] -end_of_line = lf -", editor => { - Assert.AreEqual ("\n", editor.Options.DefaultEolMarker); - }); - await InvokeEditConfigTest (@" -root = true -[*.cs] -end_of_line = cr -", editor => { - Assert.AreEqual ("\r", editor.Options.DefaultEolMarker); - }); - await InvokeEditConfigTest (@" -root = true -[*.cs] -end_of_line = crlf -", editor => { - Assert.AreEqual ("\r\n", editor.Options.DefaultEolMarker); - }); - } - - [Test] - public async Task Test_trim_trailing_whitespace () - { - await InvokeEditConfigTest (@" -root = true -[*.cs] -trim_trailing_whitespace = true -", editor => { - Assert.AreEqual (true, editor.Options.RemoveTrailingWhitespaces); - }); - - await InvokeEditConfigTest (@" -root = true -[*.cs] -trim_trailing_whitespace = false -", editor => { - Assert.AreEqual (false, editor.Options.RemoveTrailingWhitespaces); - }); - } - - [Test] - public async Task Test_max_line_length () - { - await InvokeEditConfigTest (@" -root = true -[*.cs] -max_line_length = off -", editor => { - Assert.AreEqual (false, editor.Options.ShowRuler); - }); - - await InvokeEditConfigTest (@" -root = true -[*.cs] -max_line_length = 42 -", editor => { - Assert.AreEqual (true, editor.Options.ShowRuler); - Assert.AreEqual (42, editor.Options.RulerColumn); - }); - } - - - - - } -} +// using System.IO; +// using NUnit.Framework; +// using UnitTests; +// using System.Threading; +// using GuiUnit; +// using System; +// using System.Threading.Tasks; +// using MonoDevelop.Ide.TextEditing; + +// namespace MonoDevelop.Ide.Editor +// { +// [TestFixture] +// [RequireService(typeof(TextEditorService))] +// class EditorConfigTests : IdeTestBase +// { + +// static async Task InvokeEditConfigTest (string editConfig, Action test) +// { +// string tempPath; +// int i = 0; +// while (true) { +// tempPath = Path.Combine (Path.GetTempPath (), Path.GetRandomFileName ()); +// if (!File.Exists (tempPath)) +// break; +// if (i++ > 100) +// Assert.Fail ("Can't create random path."); +// } + +// Directory.CreateDirectory (tempPath); +// try { +// string editorConfigFile = Path.Combine (tempPath, ".editorconfig"); +// File.WriteAllText (editorConfigFile, editConfig); +// var editor = TextEditorFactory.CreateNewEditor (); +// string fileName = Path.Combine (tempPath, "a.cs"); +// try { +// using (var ctx = await EditorConfigService.GetEditorConfigContext (fileName)) { +// ((DefaultSourceEditorOptions)editor.Options).SetContext (ctx); +// test (editor); +// } +// } finally { +// await EditorConfigService.RemoveEditConfigContext (fileName); +// } +// } finally { +// Directory.Delete (tempPath, true); +// } +// } + +// [Test] +// public async Task Test_indent_style () +// { +// await InvokeEditConfigTest (@" +// root = true +// [*.cs] +// indent_style = space +// ", editor => { +// Assert.AreEqual (true, editor.Options.TabsToSpaces); +// }); +// await InvokeEditConfigTest (@" +// root = true +// [*.cs] +// indent_style = tab +// ", editor => { +// Assert.AreEqual (false, editor.Options.TabsToSpaces); +// }); +// } + +// [Test] +// public async Task Test_indent_size () +// { +// await InvokeEditConfigTest (@" +// root = true +// [*.cs] +// indent_size = 42 +// ", editor => { +// Assert.AreEqual (42, editor.Options.IndentationSize); +// }); +// } + +// [Test] +// public async Task Test_tab_width () +// { +// await InvokeEditConfigTest (@" +// root = true +// [*.cs] +// tab_width = 42 +// ", editor => { +// Assert.AreEqual (42, editor.Options.TabSize); +// }); +// } + +// [Test] +// public async Task Test_end_of_line () +// { +// await InvokeEditConfigTest (@" +// root = true +// [*.cs] +// end_of_line = lf +// ", editor => { +// Assert.AreEqual ("\n", editor.Options.DefaultEolMarker); +// }); +// await InvokeEditConfigTest (@" +// root = true +// [*.cs] +// end_of_line = cr +// ", editor => { +// Assert.AreEqual ("\r", editor.Options.DefaultEolMarker); +// }); +// await InvokeEditConfigTest (@" +// root = true +// [*.cs] +// end_of_line = crlf +// ", editor => { +// Assert.AreEqual ("\r\n", editor.Options.DefaultEolMarker); +// }); +// } + +// [Test] +// public async Task Test_trim_trailing_whitespace () +// { +// await InvokeEditConfigTest (@" +// root = true +// [*.cs] +// trim_trailing_whitespace = true +// ", editor => { +// Assert.AreEqual (true, editor.Options.RemoveTrailingWhitespaces); +// }); + +// await InvokeEditConfigTest (@" +// root = true +// [*.cs] +// trim_trailing_whitespace = false +// ", editor => { +// Assert.AreEqual (false, editor.Options.RemoveTrailingWhitespaces); +// }); +// } + +// [Test] +// public async Task Test_max_line_length () +// { +// await InvokeEditConfigTest (@" +// root = true +// [*.cs] +// max_line_length = off +// ", editor => { +// Assert.AreEqual (false, editor.Options.ShowRuler); +// }); + +// await InvokeEditConfigTest (@" +// root = true +// [*.cs] +// max_line_length = 42 +// ", editor => { +// Assert.AreEqual (true, editor.Options.ShowRuler); +// Assert.AreEqual (42, editor.Options.RulerColumn); +// }); +// } + + + + +// } +// } From ebba3b807fa3dfa0e8f94e4f235e62403ea432c4 Mon Sep 17 00:00:00 2001 From: MakiWolf Date: Mon, 24 Jul 2023 19:55:25 +0200 Subject: [PATCH 3/6] formating --- .../CSharpFormatter.cs | 82 ++-- .../CSharpDocumentOptionsProvider.cs | 223 ++++----- .../OptionProviderFactory.cs | 19 +- .../MonoDevelop.TextEditor/TextViewContent.cs | 424 +++++++++--------- .../DefaultSourceEditorOptions.cs | 126 +++--- .../EditorConfigService.cs | 346 +++++++------- .../SingleFileDescriptionTemplate.cs | 38 +- .../EditorConfigTests.cs | 325 +++++++------- 8 files changed, 793 insertions(+), 790 deletions(-) diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpFormatter.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpFormatter.cs index 3ebabd9ef5e..3fd8c234baf 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpFormatter.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpFormatter.cs @@ -143,63 +143,63 @@ protected override ITextSource FormatImplementation (PolicyContainer policyParen var textPolicy = policyParent.Get (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); - // } - } + /* 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)); } - sealed class DocumentOptions : IDocumentOptions + /* sealed class DocumentOptions : IDocumentOptions { readonly OptionSet optionSet; - //readonly ICodingConventionsSnapshot codingConventionsSnapshot; + readonly ICodingConventionsSnapshot codingConventionsSnapshot; private static readonly ConditionalWeakTable, IReadOnlyDictionary> s_convertedDictionaryCache = new ConditionalWeakTable, IReadOnlyDictionary> (); - // public DocumentOptions (OptionSet optionSet, ICodingConventionsSnapshot codingConventionsSnapshot) - // { - // this.optionSet = optionSet; - // this.codingConventionsSnapshot = codingConventionsSnapshot; - // } + public DocumentOptions (OptionSet optionSet, ICodingConventionsSnapshot codingConventionsSnapshot) + { + this.optionSet = optionSet; + this.codingConventionsSnapshot = codingConventionsSnapshot; + } - public bool TryGetDocumentOption (OptionKey option, out object value) + public bool TryGetDocumentOption (OptionKey option, out object value) { - // if (codingConventionsSnapshot != null) { - // var editorConfigPersistence = option.Option.StorageLocations.OfType ().SingleOrDefault (); - // if (editorConfigPersistence != null) { - // // Temporarly map our old Dictionary to a Dictionary. This can go away once we either - // // eliminate the legacy editorconfig support, or we change IEditorConfigStorageLocation.TryGetOption to take - // // some interface that lets us pass both the Dictionary we get from the new system, and the - // // Dictionary from the old system. - // // - // // We cache this with a conditional weak table so we're able to maintain the assumptions in EditorConfigNamingStyleParser - // // that the instance doesn't regularly change and thus can be used for further caching - // var allRawConventions = s_convertedDictionaryCache.GetValue ( - // codingConventionsSnapshot.AllRawConventions, - // d => ImmutableDictionary.CreateRange (d.Select (c => KeyValuePairUtil.Create (c.Key, c.Value.ToString ())))); - - // try { - // if (editorConfigPersistence.TryGetOption (allRawConventions, option.Option.Type, out value)) - // return true; - // } catch (Exception ex) { - // LoggingService.LogError ("Error while getting editor config preferences.", ex); - // } - // } - // } + if (codingConventionsSnapshot != null) { + var editorConfigPersistence = option.Option.StorageLocations.OfType ().SingleOrDefault (); + if (editorConfigPersistence != null) { + // Temporarly map our old Dictionary to a Dictionary. This can go away once we either + // eliminate the legacy editorconfig support, or we change IEditorConfigStorageLocation.TryGetOption to take + // some interface that lets us pass both the Dictionary we get from the new system, and the + // Dictionary from the old system. + // + // We cache this with a conditional weak table so we're able to maintain the assumptions in EditorConfigNamingStyleParser + // that the instance doesn't regularly change and thus can be used for further caching + var allRawConventions = s_convertedDictionaryCache.GetValue ( + codingConventionsSnapshot.AllRawConventions, + d => ImmutableDictionary.CreateRange (d.Select (c => KeyValuePairUtil.Create (c.Key, c.Value.ToString ())))); + + try { + if (editorConfigPersistence.TryGetOption (allRawConventions, option.Option.Type, out value)) + return true; + } catch (Exception ex) { + LoggingService.LogError ("Error while getting editor config preferences.", ex); + } + } + } var result = optionSet.GetOption (option); value = result; return true; - } - } + } + } */ sealed class FormattingDocumentOptionSet : OptionSet { diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/CSharpDocumentOptionsProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/CSharpDocumentOptionsProvider.cs index c5f7b3efb9d..63477e3126c 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/CSharpDocumentOptionsProvider.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/CSharpDocumentOptionsProvider.cs @@ -23,7 +23,7 @@ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -using System; +/* using System; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; @@ -34,7 +34,7 @@ using MonoDevelop.Ide.Gui.Content; using MonoDevelop.Ide.TypeSystem; using MonoDevelop.Projects.Policies; -//using Microsoft.VisualStudio.CodingConventions; +using Microsoft.VisualStudio.CodingConventions; using System.IO; using MonoDevelop.Core; using System.Linq; @@ -45,113 +45,114 @@ namespace MonoDevelop.CSharp.OptionProvider { - //class CSharpDocumentOptionsProvider : IDocumentOptionsProvider - //{ - // async Task IDocumentOptionsProvider.GetOptionsForDocumentAsync (Document document, CancellationToken cancellationToken) - // { - // var mdws = document.Project.Solution.Workspace as MonoDevelopWorkspace; - // var project = mdws?.GetMonoProject (document.Project.Id); - - // var path = GetPath (document); - // //ICodingConventionContext conventions = null; - // // try { - // // if (path != null) - // // //conventions = await EditorConfigService.GetEditorConfigContext (path, cancellationToken); - // // } catch (Exception e) { - // // LoggingService.LogError("Error while loading coding conventions.", e); - // // } - // //return new DocumentOptions (project?.Policies, conventions?.CurrentConventions); - // } - - // static string GetPath(Document document) - // { - // if (document.FilePath != null) - // return document.FilePath; - - // // The file might not actually have a path yet, if it's a file being proposed by a code action. We'll guess a file path to use - // if (document.Name != null && document.Project.FilePath != null) { - // return Path.Combine (Path.GetDirectoryName (document.Project.FilePath), document.Name); - // } - - // // Really no idea where this is going, so bail - // return null; - // } - - //internal class DocumentOptions : IDocumentOptions - //{ - //readonly static IEnumerable types = Ide.IdeServices.DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType); - //readonly PolicyBag policyBag; - - //CSharpFormattingPolicy policy; - //CSharpFormattingPolicy Policy => policy ?? (policy = policyBag?.Get (types) ?? PolicyService.InvariantPolicies.Get (types)); - - //TextStylePolicy textpolicy; - //TextStylePolicy TextPolicy => textpolicy ?? (textpolicy = policyBag?.Get (types) ?? PolicyService.InvariantPolicies?.Get (types)); - - //readonly ICodingConventionsSnapshot codingConventionsSnapshot; - //private static readonly ConditionalWeakTable, IReadOnlyDictionary> s_convertedDictionaryCache = - // new ConditionalWeakTable, IReadOnlyDictionary> (); - - // public DocumentOptions (PolicyBag policyBag, ICodingConventionsSnapshot codingConventionsSnapshot) - // { - // this.policyBag = policyBag; - // this.codingConventionsSnapshot = codingConventionsSnapshot; - // } - - // public bool TryGetDocumentOption (OptionKey option, out object value) - // { - // if (codingConventionsSnapshot != null) { - // var editorConfigPersistence = option.Option.StorageLocations.OfType ().SingleOrDefault (); - // if (editorConfigPersistence != null) { - // // Temporarly map our old Dictionary to a Dictionary. This can go away once we either - // // eliminate the legacy editorconfig support, or we change IEditorConfigStorageLocation.TryGetOption to take - // // some interface that lets us pass both the Dictionary we get from the new system, and the - // // Dictionary from the old system. - // // - // // We cache this with a conditional weak table so we're able to maintain the assumptions in EditorConfigNamingStyleParser - // // that the instance doesn't regularly change and thus can be used for further caching - // var allRawConventions = s_convertedDictionaryCache.GetValue ( - // codingConventionsSnapshot.AllRawConventions, - // d => ImmutableDictionary.CreateRange (d.Select (c => KeyValuePairUtil.Create (c.Key, c.Value.ToString ())))); - - // try { - // if (editorConfigPersistence.TryGetOption (allRawConventions, option.Option.Type, out value)) - // return true; - // } catch (Exception ex) { - // LoggingService.LogError ("Error while getting editor config preferences.", ex); - // } - // } - // } - - // if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentationSize) { - // value = TextPolicy.IndentWidth; - // return true; - // } - - // if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.NewLine) { - // value = TextPolicy.GetEolMarker (); - // return true; - // } - - // if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.SmartIndent) { - // value = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle.Smart; - // return true; - // } - - // if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.TabSize) { - // value = TextPolicy.TabWidth; - // return true; - // } - - // if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.UseTabs) { - // value = !TextPolicy.TabsToSpaces; - // return true; - // } - - // var result = Policy.OptionSet.GetOption (option); - // value = result; - // return true; - // } - // } - //} + class CSharpDocumentOptionsProvider : IDocumentOptionsProvider + { + async Task IDocumentOptionsProvider.GetOptionsForDocumentAsync (Document document, CancellationToken cancellationToken) + { + var mdws = document.Project.Solution.Workspace as MonoDevelopWorkspace; + var project = mdws?.GetMonoProject (document.Project.Id); + + var path = GetPath (document); + ICodingConventionContext conventions = null; + try { + if (path != null) + //conventions = await EditorConfigService.GetEditorConfigContext (path, cancellationToken); + } catch (Exception e) { + LoggingService.LogError("Error while loading coding conventions.", e); + } + return new DocumentOptions (project?.Policies, conventions?.CurrentConventions); + } + + static string GetPath(Document document) + { + if (document.FilePath != null) + return document.FilePath; + + // The file might not actually have a path yet, if it's a file being proposed by a code action. We'll guess a file path to use + if (document.Name != null && document.Project.FilePath != null) { + return Path.Combine (Path.GetDirectoryName (document.Project.FilePath), document.Name); + } + + // Really no idea where this is going, so bail + return null; + } + + internal class DocumentOptions : IDocumentOptions + { + readonly static IEnumerable types = Ide.IdeServices.DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType); + readonly PolicyBag policyBag; + + CSharpFormattingPolicy policy; + CSharpFormattingPolicy Policy => policy ?? (policy = policyBag?.Get (types) ?? PolicyService.InvariantPolicies.Get (types)); + + TextStylePolicy textpolicy; + TextStylePolicy TextPolicy => textpolicy ?? (textpolicy = policyBag?.Get (types) ?? PolicyService.InvariantPolicies?.Get (types)); + + readonly ICodingConventionsSnapshot codingConventionsSnapshot; + private static readonly ConditionalWeakTable, IReadOnlyDictionary> s_convertedDictionaryCache = + new ConditionalWeakTable, IReadOnlyDictionary> (); + + public DocumentOptions (PolicyBag policyBag, ICodingConventionsSnapshot codingConventionsSnapshot) + { + this.policyBag = policyBag; + this.codingConventionsSnapshot = codingConventionsSnapshot; + } + + public bool TryGetDocumentOption (OptionKey option, out object value) + { + if (codingConventionsSnapshot != null) { + var editorConfigPersistence = option.Option.StorageLocations.OfType ().SingleOrDefault (); + if (editorConfigPersistence != null) { + // Temporarly map our old Dictionary to a Dictionary. This can go away once we either + // eliminate the legacy editorconfig support, or we change IEditorConfigStorageLocation.TryGetOption to take + // some interface that lets us pass both the Dictionary we get from the new system, and the + // Dictionary from the old system. + // + // We cache this with a conditional weak table so we're able to maintain the assumptions in EditorConfigNamingStyleParser + // that the instance doesn't regularly change and thus can be used for further caching + var allRawConventions = s_convertedDictionaryCache.GetValue ( + codingConventionsSnapshot.AllRawConventions, + d => ImmutableDictionary.CreateRange (d.Select (c => KeyValuePairUtil.Create (c.Key, c.Value.ToString ())))); + + try { + if (editorConfigPersistence.TryGetOption (allRawConventions, option.Option.Type, out value)) + return true; + } catch (Exception ex) { + LoggingService.LogError ("Error while getting editor config preferences.", ex); + } + } + } + + if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentationSize) { + value = TextPolicy.IndentWidth; + return true; + } + + if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.NewLine) { + value = TextPolicy.GetEolMarker (); + return true; + } + + if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.SmartIndent) { + value = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle.Smart; + return true; + } + + if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.TabSize) { + value = TextPolicy.TabWidth; + return true; + } + + if (option.Option == Microsoft.CodeAnalysis.Formatting.FormattingOptions.UseTabs) { + value = !TextPolicy.TabsToSpaces; + return true; + } + + var result = Policy.OptionSet.GetOption (option); + value = result; + return true; + } + } + } } + */ \ No newline at end of file diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/OptionProviderFactory.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/OptionProviderFactory.cs index 9f940d2b499..2a01af55155 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/OptionProviderFactory.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.OptionProvider/OptionProviderFactory.cs @@ -23,19 +23,20 @@ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -using System; +/* using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Options; namespace MonoDevelop.CSharp.OptionProvider { - // [Export (typeof (IDocumentOptionsProviderFactory))] - // class EditorConfigDocumentOptionsProviderFactory : IDocumentOptionsProviderFactory - // { - // // public IDocumentOptionsProvider TryCreate (Workspace workspace) - // // { - // // return new CSharpDocumentOptionsProvider (); - // // } - // } + [Export (typeof (IDocumentOptionsProviderFactory))] + class EditorConfigDocumentOptionsProviderFactory : IDocumentOptionsProviderFactory + { + public IDocumentOptionsProvider TryCreate (Workspace workspace) + { + return new CSharpDocumentOptionsProvider (); + } + } } + */ \ No newline at end of file diff --git a/main/src/addins/MonoDevelop.TextEditor/MonoDevelop.TextEditor/TextViewContent.cs b/main/src/addins/MonoDevelop.TextEditor/MonoDevelop.TextEditor/TextViewContent.cs index b977a28e9bd..fd7d3af5782 100644 --- a/main/src/addins/MonoDevelop.TextEditor/MonoDevelop.TextEditor/TextViewContent.cs +++ b/main/src/addins/MonoDevelop.TextEditor/MonoDevelop.TextEditor/TextViewContent.cs @@ -249,11 +249,11 @@ protected override void OnFileNameChanged () warnOverwrite = false; - // if (editorConfigContext != null) { - // editorConfigContext.CodingConventionsChangedAsync -= UpdateOptionsFromEditorConfigAsync; - // EditorConfigService.RemoveEditConfigContext (TextDocument.FilePath).Ignore (); - // editorConfigContext = null; - // } + /* if (editorConfigContext != null) { + editorConfigContext.CodingConventionsChangedAsync -= UpdateOptionsFromEditorConfigAsync; + EditorConfigService.RemoveEditConfigContext (TextDocument.FilePath).Ignore (); + editorConfigContext = null; + } */ if (FilePath != TextDocument.FilePath && !string.IsNullOrEmpty (TextDocument.FilePath)) AutoSave.RemoveAutoSaveFile (TextDocument.FilePath); @@ -312,12 +312,12 @@ protected override void OnDispose () UnsubscribeFromEvents (); - //if (policyContainer != null) - // policyContainer.PolicyChanged -= PolicyChanged; - //if (editorConfigContext != null) { - //editorConfigContext.CodingConventionsChangedAsync -= UpdateOptionsFromEditorConfigAsync; - //EditorConfigService.RemoveEditConfigContext (FilePath).Ignore (); - //} + /* if (policyContainer != null) + policyContainer.PolicyChanged -= PolicyChanged; + if (editorConfigContext != null) { + editorConfigContext.CodingConventionsChangedAsync -= UpdateOptionsFromEditorConfigAsync; + EditorConfigService.RemoveEditConfigContext (FilePath).Ignore (); + } */ base.OnDispose (); } @@ -362,38 +362,38 @@ void UpdateLineNumberMarginOption () sourceEditorOptions.ShowLineNumberMargin); } - // void UpdateTextEditorOptions (object sender, EventArgs e) - // { - // UpdateTextEditorOptionsAsync ().Forget (); - // } - - // async Task UpdateTextEditorOptionsAsync () - // { - // UpdateLineNumberMarginOption (); + /* void UpdateTextEditorOptions (object sender, EventArgs e) + { + UpdateTextEditorOptionsAsync ().Forget (); + } - // var foldMargin = PropertyService.Get ("ShowFoldMargin"); - // Imports.OutliningManagerService.GetOutliningManager (TextView).Enabled = foldMargin; + async Task UpdateTextEditorOptionsAsync () + { + UpdateLineNumberMarginOption (); - // var newPolicyContainer = (Owner as IPolicyProvider)?.Policies; - // if (newPolicyContainer != policyContainer) { - // if (policyContainer != null) - // policyContainer.PolicyChanged -= PolicyChanged; - // policyContainer = newPolicyContainer; - // } - // if (policyContainer != null) - // policyContainer.PolicyChanged += PolicyChanged; + var foldMargin = PropertyService.Get ("ShowFoldMargin"); + Imports.OutliningManagerService.GetOutliningManager (TextView).Enabled = foldMargin; - // var newEditorConfigContext = await EditorConfigService.GetEditorConfigContext (FilePath, default); - // if (newEditorConfigContext != editorConfigContext) { - // if (editorConfigContext != null) - // editorConfigContext.CodingConventionsChangedAsync -= UpdateOptionsFromEditorConfigAsync; - // editorConfigContext = newEditorConfigContext; - // } - // if (editorConfigContext != null) - // editorConfigContext.CodingConventionsChangedAsync += UpdateOptionsFromEditorConfigAsync; + var newPolicyContainer = (Owner as IPolicyProvider)?.Policies; + if (newPolicyContainer != policyContainer) { + if (policyContainer != null) + policyContainer.PolicyChanged -= PolicyChanged; + policyContainer = newPolicyContainer; + } + if (policyContainer != null) + policyContainer.PolicyChanged += PolicyChanged; + + var newEditorConfigContext = await EditorConfigService.GetEditorConfigContext (FilePath, default); + if (newEditorConfigContext != editorConfigContext) { + if (editorConfigContext != null) + editorConfigContext.CodingConventionsChangedAsync -= UpdateOptionsFromEditorConfigAsync; + editorConfigContext = newEditorConfigContext; + } + if (editorConfigContext != null) + editorConfigContext.CodingConventionsChangedAsync += UpdateOptionsFromEditorConfigAsync; - // await UpdateOptionsFromEditorConfigAsync (null, null); - // } + await UpdateOptionsFromEditorConfigAsync (null, null); + } */ void ClearOptionValue(string optionName) { @@ -438,179 +438,179 @@ private void UpdateOptionsFromPolicy() #endif } -// private Task UpdateOptionsFromEditorConfigAsync (object sender, CodingConventionsChangedEventArgs args) -// { -// // Set base options first, then override with editorconfig values -// UpdateOptionsFromPolicy (); - -// if (editorConfigContext == null) -// return Task.CompletedTask; - -// if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetIndentStyle (out var indentStyle)) -// SetOptionValue (DefaultOptions.ConvertTabsToSpacesOptionName, indentStyle == IndentStyle.Spaces); -// if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetTabWidth (out var tabWidth)) -// SetOptionValue (DefaultOptions.TabSizeOptionName, tabWidth); -// if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetIndentSize (out var indentSize)) -// SetOptionValue (DefaultOptions.IndentSizeOptionName, indentSize); -// if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetLineEnding (out var lineEnding)) -// SetOptionValue (DefaultOptions.NewLineCharacterOptionName, lineEnding); -// if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetAllowTrailingWhitespace (out var allowTrailingWhitespace)) -// SetOptionValue (DefaultOptions.TrimTrailingWhiteSpaceOptionName, !allowTrailingWhitespace); - -// var setVerticalRulers = false; -// int [] verticalRulers = null; - -// // "Show column ruler" preference still needs to be checked, regardless of whether or not editorconfig -// // has a setting for where rulers should appear -// if (PropertyService.Get ("ShowRuler")) { -// if (editorConfigContext.CurrentConventions.TryGetConventionValue (EditorConfigService.RulersConvention, out var rulers)) { -// setVerticalRulers = true; -// if (!string.IsNullOrEmpty (rulers)) { -// verticalRulers = Array.ConvertAll (rulers.Split (','), val => { -// if (int.TryParse (val, out var col)) -// return col; -// return 0; -// }); -// } -// } else if (editorConfigContext.CurrentConventions.TryGetConventionValue (EditorConfigService.MaxLineLengthConvention, out var maxLineLength)) { -// if (maxLineLength != "off" && int.TryParse (maxLineLength, out var i)) { -// setVerticalRulers = true; -// verticalRulers = new [] { i }; -// } else -// setVerticalRulers = false; -// } -// } - -// #if !WINDOWS -// if (setVerticalRulers) -// EditorOptions.SetOptionValue (DefaultTextViewOptions.VerticalRulersName, verticalRulers ?? Array.Empty ()); -// #endif - -// return Task.CompletedTask; -// } - -// private void PolicyChanged (object sender, PolicyChangedEventArgs e) -// => UpdateTextEditorOptions (sender, e); - -// protected override object OnGetContent (Type type) -// { -// if (contentProviders != null) { -// foreach (var provider in contentProviders) { -// var content = provider.GetContent (TextView, type); -// if (content != null) { -// return content; -// } -// } -// } -// return GetIntrinsicType (type); -// } - -// protected override IEnumerable OnGetContents (Type type) -// { -// if (contentProviders != null) { -// foreach (var provider in contentProviders) { -// var contents = provider.GetContents (TextView, type); -// if (contents != null) { -// foreach (var content in contents) -// yield return content; -// } -// } -// } - -// var intrinsicType = GetIntrinsicType (type); -// if (intrinsicType != null) { -// yield return intrinsicType; -// } -// } - -// object GetIntrinsicType (Type type) -// { -// if (type.IsInstanceOfType (TextBuffer)) -// return TextBuffer; -// if (type.IsInstanceOfType (TextDocument)) -// return TextDocument; -// if (type.IsInstanceOfType (TextView)) -// return TextView; -// if (type.IsInstanceOfType (this)) -// return this; -// return null; -// } - -// Task Load (bool reloading) -// { -// // We actually load initial content at construction time, so this -// // overload only needs to cover reload and autosave scenarios - -// if (warnOverwrite) { -// warnOverwrite = false; -// DismissInfoBar (); -// ShowNotification = false; -// } - -// if (reloading) { -// TextDocument.Reload (); -// } else if (AutoSave.AutoSaveExists (FilePath)) { -// var autosaveContent = AutoSave.LoadAutoSave (FilePath); - -// MarkDirty (); -// warnOverwrite = true; - -// // Set editor read-only until user picks one of the above options. -// var setWritable = !TextView.Options.DoesViewProhibitUserInput (); -// if (setWritable) -// TextView.Options.SetOptionValue (DefaultTextViewOptions.ViewProhibitUserInputId, true); - -// var (primaryMessageText, secondaryMessageText) = SplitMessageString ( -// BrandingService.BrandApplicationName (GettextCatalog.GetString ( -// "An autosave file has been found for this file.\n" + -// "This could mean that another instance of MonoDevelop is editing this " + -// "file, or that MonoDevelop crashed with unsaved changes.\n\n" + -// "Do you want to use the original file, or load from the autosave file?"))); - -// PresentInfobar ( -// primaryMessageText, -// secondaryMessageText, -// new InfoBarAction ( -// GetButtonString (GettextCatalog.GetString ("_Use original file")), -// UseOriginalFile), -// new InfoBarAction ( -// GetButtonString (GettextCatalog.GetString ("_Load from autosave")), -// LoadFromAutosave, -// isDefault: true)); - -// void OnActionSelected () -// { -// DismissInfoBar (); -// if (setWritable) -// TextView.Options.SetOptionValue (DefaultTextViewOptions.ViewProhibitUserInputId, false); -// } - -// void LoadFromAutosave () -// { -// try { -// AutoSave.RemoveAutoSaveFile (FilePath); -// ReplaceContent (autosaveContent.Text, autosaveContent.Encoding); -// } catch (Exception e) { -// LoggingService.LogError ("Could not load the autosave file", e); -// } finally { -// OnActionSelected (); -// } -// } - -// void UseOriginalFile () -// { -// try { -// AutoSave.RemoveAutoSaveFile (FilePath); -// } catch (Exception e) { -// LoggingService.LogError ("Could not remove the autosave file", e); -// } finally { -// OnActionSelected (); -// } -// } -// } - -// return Task.CompletedTask; -// } +/* private Task UpdateOptionsFromEditorConfigAsync (object sender, CodingConventionsChangedEventArgs args) + { + // Set base options first, then override with editorconfig values + UpdateOptionsFromPolicy (); + + if (editorConfigContext == null) + return Task.CompletedTask; + + if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetIndentStyle (out var indentStyle)) + SetOptionValue (DefaultOptions.ConvertTabsToSpacesOptionName, indentStyle == IndentStyle.Spaces); + if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetTabWidth (out var tabWidth)) + SetOptionValue (DefaultOptions.TabSizeOptionName, tabWidth); + if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetIndentSize (out var indentSize)) + SetOptionValue (DefaultOptions.IndentSizeOptionName, indentSize); + if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetLineEnding (out var lineEnding)) + SetOptionValue (DefaultOptions.NewLineCharacterOptionName, lineEnding); + if (editorConfigContext.CurrentConventions.UniversalConventions.TryGetAllowTrailingWhitespace (out var allowTrailingWhitespace)) + SetOptionValue (DefaultOptions.TrimTrailingWhiteSpaceOptionName, !allowTrailingWhitespace); + + var setVerticalRulers = false; + int [] verticalRulers = null; + + // "Show column ruler" preference still needs to be checked, regardless of whether or not editorconfig + // has a setting for where rulers should appear + if (PropertyService.Get ("ShowRuler")) { + if (editorConfigContext.CurrentConventions.TryGetConventionValue (EditorConfigService.RulersConvention, out var rulers)) { + setVerticalRulers = true; + if (!string.IsNullOrEmpty (rulers)) { + verticalRulers = Array.ConvertAll (rulers.Split (','), val => { + if (int.TryParse (val, out var col)) + return col; + return 0; + }); + } + } else if (editorConfigContext.CurrentConventions.TryGetConventionValue (EditorConfigService.MaxLineLengthConvention, out var maxLineLength)) { + if (maxLineLength != "off" && int.TryParse (maxLineLength, out var i)) { + setVerticalRulers = true; + verticalRulers = new [] { i }; + } else + setVerticalRulers = false; + } + } + +#if !WINDOWS + if (setVerticalRulers) + EditorOptions.SetOptionValue (DefaultTextViewOptions.VerticalRulersName, verticalRulers ?? Array.Empty ()); +#endif + + return Task.CompletedTask; + } + + private void PolicyChanged (object sender, PolicyChangedEventArgs e) + => UpdateTextEditorOptions (sender, e); + + protected override object OnGetContent (Type type) + { + if (contentProviders != null) { + foreach (var provider in contentProviders) { + var content = provider.GetContent (TextView, type); + if (content != null) { + return content; + } + } + } + return GetIntrinsicType (type); + } + + protected override IEnumerable OnGetContents (Type type) + { + if (contentProviders != null) { + foreach (var provider in contentProviders) { + var contents = provider.GetContents (TextView, type); + if (contents != null) { + foreach (var content in contents) + yield return content; + } + } + } + + var intrinsicType = GetIntrinsicType (type); + if (intrinsicType != null) { + yield return intrinsicType; + } + } + + object GetIntrinsicType (Type type) + { + if (type.IsInstanceOfType (TextBuffer)) + return TextBuffer; + if (type.IsInstanceOfType (TextDocument)) + return TextDocument; + if (type.IsInstanceOfType (TextView)) + return TextView; + if (type.IsInstanceOfType (this)) + return this; + return null; + } + + Task Load (bool reloading) + { + // We actually load initial content at construction time, so this + // overload only needs to cover reload and autosave scenarios + + if (warnOverwrite) { + warnOverwrite = false; + DismissInfoBar (); + ShowNotification = false; + } + + if (reloading) { + TextDocument.Reload (); + } else if (AutoSave.AutoSaveExists (FilePath)) { + var autosaveContent = AutoSave.LoadAutoSave (FilePath); + + MarkDirty (); + warnOverwrite = true; + + // Set editor read-only until user picks one of the above options. + var setWritable = !TextView.Options.DoesViewProhibitUserInput (); + if (setWritable) + TextView.Options.SetOptionValue (DefaultTextViewOptions.ViewProhibitUserInputId, true); + + var (primaryMessageText, secondaryMessageText) = SplitMessageString ( + BrandingService.BrandApplicationName (GettextCatalog.GetString ( + "An autosave file has been found for this file.\n" + + "This could mean that another instance of MonoDevelop is editing this " + + "file, or that MonoDevelop crashed with unsaved changes.\n\n" + + "Do you want to use the original file, or load from the autosave file?"))); + + PresentInfobar ( + primaryMessageText, + secondaryMessageText, + new InfoBarAction ( + GetButtonString (GettextCatalog.GetString ("_Use original file")), + UseOriginalFile), + new InfoBarAction ( + GetButtonString (GettextCatalog.GetString ("_Load from autosave")), + LoadFromAutosave, + isDefault: true)); + + void OnActionSelected () + { + DismissInfoBar (); + if (setWritable) + TextView.Options.SetOptionValue (DefaultTextViewOptions.ViewProhibitUserInputId, false); + } + + void LoadFromAutosave () + { + try { + AutoSave.RemoveAutoSaveFile (FilePath); + ReplaceContent (autosaveContent.Text, autosaveContent.Encoding); + } catch (Exception e) { + LoggingService.LogError ("Could not load the autosave file", e); + } finally { + OnActionSelected (); + } + } + + void UseOriginalFile () + { + try { + AutoSave.RemoveAutoSaveFile (FilePath); + } catch (Exception e) { + LoggingService.LogError ("Could not remove the autosave file", e); + } finally { + OnActionSelected (); + } + } + } + + return Task.CompletedTask; + } */ /// /// Replace document content with new content. This marks the document as dirty. diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/DefaultSourceEditorOptions.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/DefaultSourceEditorOptions.cs index 06539353847..6ea93638517 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/DefaultSourceEditorOptions.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/DefaultSourceEditorOptions.cs @@ -280,10 +280,10 @@ void HandlePolicyChanged (object sender, MonoDevelop.Projects.Policies.PolicyCha //IdeApp.Preferences.Editor.FollowCodingConventions.Changed += OnFollowCodingConventionsChanged; } - // void OnFollowCodingConventionsChanged (object sender, EventArgs e) - // { - // UpdateContextOptions (null, null).Ignore (); - // } + /* void OnFollowCodingConventionsChanged (object sender, EventArgs e) + { + UpdateContextOptions (null, null).Ignore (); + } */ void UpdateFont () @@ -319,57 +319,57 @@ public DefaultSourceEditorOptions WithTextStyle (TextStylePolicy policy) return result; } - // internal void SetContext (ICodingConventionContext context) - // { - // if (this.context == context) - // return; - // if (this.context != null) - // this.context.CodingConventionsChangedAsync -= UpdateContextOptions; - // this.context = context; - // context.CodingConventionsChangedAsync += UpdateContextOptions; - // UpdateContextOptions (null, null).Ignore (); - // } - - // private Task UpdateContextOptions (object sender, CodingConventionsChangedEventArgs arg) - // { - // if (context == null) - // return Task.CompletedTask; - - // bool followCodingConventions = IdeApp.Preferences.Editor.FollowCodingConventions; - - // defaultEolMarkerFromContext = null; - // if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetLineEnding (out string eolMarker)) - // defaultEolMarkerFromContext = eolMarker; - - // tabsToSpacesFromContext = null; - // //if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetIndentStyle (out Microsoft.VisualStudio.CodingConventions.IndentStyle result)) - // // tabsToSpacesFromContext = result == Microsoft.VisualStudio.CodingConventions.IndentStyle.Spaces; - - // indentationSizeFromContext = null; - // if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetIndentSize (out int indentSize)) - // indentationSizeFromContext = indentSize; - - // removeTrailingWhitespacesFromContext = null; - // if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetAllowTrailingWhitespace (out bool allowTrailing)) - // removeTrailingWhitespacesFromContext = !allowTrailing; - - // tabSizeFromContext = null; - // if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetTabWidth (out int tSize)) - // tabSizeFromContext = tSize; - - // rulerColumnFromContext = null; - // showRulerFromContext = null; - // if (followCodingConventions && context.CurrentConventions.TryGetConventionValue (EditorConfigService.MaxLineLengthConvention, out string maxLineLength)) { - // if (maxLineLength != "off" && int.TryParse (maxLineLength, out int i)) { - // rulerColumnFromContext = i; - // showRulerFromContext = true; - // } else { - // showRulerFromContext = false; - // } - // } - // this.FireChange (); - // return Task.CompletedTask; - // } + /* internal void SetContext (ICodingConventionContext context) + { + if (this.context == context) + return; + if (this.context != null) + this.context.CodingConventionsChangedAsync -= UpdateContextOptions; + this.context = context; + context.CodingConventionsChangedAsync += UpdateContextOptions; + UpdateContextOptions (null, null).Ignore (); + } + + private Task UpdateContextOptions (object sender, CodingConventionsChangedEventArgs arg) + { + if (context == null) + return Task.CompletedTask; + + bool followCodingConventions = IdeApp.Preferences.Editor.FollowCodingConventions; + + defaultEolMarkerFromContext = null; + if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetLineEnding (out string eolMarker)) + defaultEolMarkerFromContext = eolMarker; + + tabsToSpacesFromContext = null; + //if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetIndentStyle (out Microsoft.VisualStudio.CodingConventions.IndentStyle result)) + // tabsToSpacesFromContext = result == Microsoft.VisualStudio.CodingConventions.IndentStyle.Spaces; + + indentationSizeFromContext = null; + if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetIndentSize (out int indentSize)) + indentationSizeFromContext = indentSize; + + removeTrailingWhitespacesFromContext = null; + if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetAllowTrailingWhitespace (out bool allowTrailing)) + removeTrailingWhitespacesFromContext = !allowTrailing; + + tabSizeFromContext = null; + if (followCodingConventions && context.CurrentConventions.UniversalConventions.TryGetTabWidth (out int tSize)) + tabSizeFromContext = tSize; + + rulerColumnFromContext = null; + showRulerFromContext = null; + if (followCodingConventions && context.CurrentConventions.TryGetConventionValue (EditorConfigService.MaxLineLengthConvention, out string maxLineLength)) { + if (maxLineLength != "off" && int.TryParse (maxLineLength, out int i)) { + rulerColumnFromContext = i; + showRulerFromContext = true; + } else { + showRulerFromContext = false; + } + } + this.FireChange (); + return Task.CompletedTask; + } */ #region new options @@ -929,15 +929,15 @@ public bool SmartBackspace{ } #endregion - public void Dispose () - { - // IdeServices.FontService.RemoveCallback (UpdateFont); - // IdeApp.Preferences.ColorScheme.Changed -= OnColorSchemeChanged; - // IdeApp.Preferences.Editor.FollowCodingConventions.Changed -= OnFollowCodingConventionsChanged; - // if (context != null) - // context.CodingConventionsChangedAsync -= UpdateContextOptions; + public void Dispose () + { + /* IdeServices.FontService.RemoveCallback (UpdateFont); + IdeApp.Preferences.ColorScheme.Changed -= OnColorSchemeChanged; + IdeApp.Preferences.Editor.FollowCodingConventions.Changed -= OnFollowCodingConventionsChanged; + if (context != null) + context.CodingConventionsChangedAsync -= UpdateContextOptions; */ - } + } void OnChanged (EventArgs args) { diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/EditorConfigService.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/EditorConfigService.cs index 5ecf1e66b5e..d904cc5a5c1 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/EditorConfigService.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/EditorConfigService.cs @@ -23,177 +23,177 @@ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -//using System; -//using System.Collections.Immutable; -//using System.IO; -//using System.Linq; -//using System.Threading; -//using System.Threading.Tasks; -//using Microsoft.VisualStudio.CodingConventions; -//using System.Collections.Generic; -//using MonoDevelop.Core; -//using MonoDevelop.Projects; - -//namespace MonoDevelop.Ide.Editor -//{ - //static class EditorConfigService - //{ - //public readonly static string MaxLineLengthConvention = "max_line_length"; - //public readonly static string RulersConvention = "rulers"; - - //readonly static object contextCacheLock = new object (); - //readonly static ICodingConventionsManager codingConventionsManager = CodingConventionsManagerFactory.CreateCodingConventionsManager (new ConventionsFileManager()); - //static ImmutableDictionary contextCache = ImmutableDictionary.Empty; - //public static class GetEditorConfigContext (string fileName, CancellationToken token = default (CancellationToken)) - // public static async Task GetEditorConfigContext (string fileName, CancellationToken token = default (CancellationToken)) - // { - // if (string.IsNullOrEmpty (fileName)) - // return null; - // try { - // var directory = Path.GetDirectoryName (fileName); - // if (string.IsNullOrEmpty (directory)) { - // return null; - // } - - // // HACK: Work around for a library issue https://github.com/mono/monodevelop/issues/6104 - // if (directory == "/") { - // return null; - // } - // } catch { - // return null; - // } - // if (contextCache.TryGetValue (fileName, out var oldresult)) - // return oldresult; - // try { - // var result = await codingConventionsManager.GetConventionContextAsync (fileName, token); - // lock (contextCacheLock) { - // // check if another thread already requested a coding convention context and ensure - // // that only one is alive. - // if (contextCache.TryGetValue (fileName, out var result2)) { - // if (result != result2) - // result.Dispose (); - // return result2; - // } - // contextCache = contextCache.SetItem (fileName, result); - // } - // return result; - // } catch (OperationCanceledException) { - // return null; - // } catch (Exception e) { - // LoggingService.LogError ("Error while getting coding conventions,", e); - // return null; - // } - // } - - // public static Task RemoveEditConfigContext (string fileName) - // { - // return Task.Run (() => { - // ICodingConventionContext ctx; - // lock (contextCacheLock) { - // if (!contextCache.TryGetValue (fileName, out ctx)) - // return; - // contextCache = contextCache.Remove (fileName); - // } - // if (ctx != null) - // ctx.Dispose (); - // }); - // } - - // class ConventionsFileManager : IFileWatcher - // { - // HashSet watchedFiles = new HashSet (); - - // public event ConventionsFileChangedAsyncEventHandler ConventionFileChanged; - // public event ContextFileMovedAsyncEventHandler ContextFileMoved; - - // public ConventionsFileManager () - // { - // FileService.FileChanged += FileService_FileChanged; - // FileService.FileRemoved += FileService_FileRemoved; - // FileService.FileMoved += FileService_FileMoved; - // FileService.FileRenamed += FileService_FileMoved; - // } - - // void FileService_FileMoved (object sender, FileCopyEventArgs e) - // { - // lock (watchedFiles) { - // foreach (var file in e) { - // if (watchedFiles.Remove (file.SourceFile)) { - // ContextFileMoved?.Invoke (this, new ContextFileMovedEventArgs (file.SourceFile, file.TargetFile)); - // if (file.SourceFile == file.TargetFile) { - // StartWatching (file.TargetFile.FileName, file.TargetFile.ParentDirectory); - // } - // } - // } - // } - // } - - // void FileService_FileChanged (object sender, FileEventArgs e) - // { - // lock (watchedFiles) { - // foreach (var file in e) { - // if (watchedFiles.Contains (file.FileName)) { - // ConventionFileChanged?.Invoke (this, new ConventionsFileChangeEventArgs (file.FileName.FileName, file.FileName.ParentDirectory, ChangeType.FileModified)); - // } - // } - // } - // } - - // void FileService_FileRemoved (object sender, FileEventArgs e) - // { - // lock (watchedFiles) { - // foreach (var file in e) { - // if (watchedFiles.Remove (file.FileName)) { - // ConventionFileChanged?.Invoke (this, new ConventionsFileChangeEventArgs (file.FileName.FileName, file.FileName.ParentDirectory, ChangeType.FileDeleted)); - // WatchDirectories (); - // } - // } - // } - // } - - // public void Dispose () - // { - // FileService.FileMoved -= FileService_FileMoved; - // FileService.FileRenamed -= FileService_FileMoved; - // FileService.FileRemoved -= FileService_FileRemoved; - // FileService.FileChanged -= FileService_FileChanged; - // FileWatcherService.WatchDirectories (this, null).Ignore (); - // lock (watchedFiles) { - // watchedFiles = null; - // } - // } - - // public void StartWatching (string fileName, string directoryPath) - // { - // lock (watchedFiles) { - // var key = directoryPath + Path.DirectorySeparatorChar.ToString () + fileName; - - // if (!File.Exists (key)) - // return; - - // if (!watchedFiles.Add (key)) - // return; - - // WatchDirectories (); - // } - // } - - // public void StopWatching (string fileName, string directoryPath) - // { - // lock (watchedFiles) { +/* using System; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.VisualStudio.CodingConventions; +using System.Collections.Generic; +using MonoDevelop.Core; +using MonoDevelop.Projects; + +namespace MonoDevelop.Ide.Editor +{ + static class EditorConfigService + { + public readonly static string MaxLineLengthConvention = "max_line_length"; + public readonly static string RulersConvention = "rulers"; + + readonly static object contextCacheLock = new object (); + readonly static ICodingConventionsManager codingConventionsManager = CodingConventionsManagerFactory.CreateCodingConventionsManager (new ConventionsFileManager()); + static ImmutableDictionary contextCache = ImmutableDictionary.Empty; + public static class GetEditorConfigContext (string fileName, CancellationToken token = default (CancellationToken)) + public static async Task GetEditorConfigContext (string fileName, CancellationToken token = default (CancellationToken)) + { + if (string.IsNullOrEmpty (fileName)) + return null; + try { + var directory = Path.GetDirectoryName (fileName); + if (string.IsNullOrEmpty (directory)) { + return null; + } + + // HACK: Work around for a library issue https://github.com/mono/monodevelop/issues/6104 + if (directory == "/") { + return null; + } + } catch { + return null; + } + if (contextCache.TryGetValue (fileName, out var oldresult)) + return oldresult; + try { + var result = await codingConventionsManager.GetConventionContextAsync (fileName, token); + lock (contextCacheLock) { + // check if another thread already requested a coding convention context and ensure + // that only one is alive. + if (contextCache.TryGetValue (fileName, out var result2)) { + if (result != result2) + result.Dispose (); + return result2; + } + contextCache = contextCache.SetItem (fileName, result); + } + return result; + } catch (OperationCanceledException) { + return null; + } catch (Exception e) { + LoggingService.LogError ("Error while getting coding conventions,", e); + return null; + } + } + + public static Task RemoveEditConfigContext (string fileName) + { + return Task.Run (() => { + ICodingConventionContext ctx; + lock (contextCacheLock) { + if (!contextCache.TryGetValue (fileName, out ctx)) + return; + contextCache = contextCache.Remove (fileName); + } + if (ctx != null) + ctx.Dispose (); + }); + } + + class ConventionsFileManager : IFileWatcher + { + HashSet watchedFiles = new HashSet (); + + public event ConventionsFileChangedAsyncEventHandler ConventionFileChanged; + public event ContextFileMovedAsyncEventHandler ContextFileMoved; + + public ConventionsFileManager () + { + FileService.FileChanged += FileService_FileChanged; + FileService.FileRemoved += FileService_FileRemoved; + FileService.FileMoved += FileService_FileMoved; + FileService.FileRenamed += FileService_FileMoved; + } + + void FileService_FileMoved (object sender, FileCopyEventArgs e) + { + lock (watchedFiles) { + foreach (var file in e) { + if (watchedFiles.Remove (file.SourceFile)) { + ContextFileMoved?.Invoke (this, new ContextFileMovedEventArgs (file.SourceFile, file.TargetFile)); + if (file.SourceFile == file.TargetFile) { + StartWatching (file.TargetFile.FileName, file.TargetFile.ParentDirectory); + } + } + } + } + } + + void FileService_FileChanged (object sender, FileEventArgs e) + { + lock (watchedFiles) { + foreach (var file in e) { + if (watchedFiles.Contains (file.FileName)) { + ConventionFileChanged?.Invoke (this, new ConventionsFileChangeEventArgs (file.FileName.FileName, file.FileName.ParentDirectory, ChangeType.FileModified)); + } + } + } + } + + void FileService_FileRemoved (object sender, FileEventArgs e) + { + lock (watchedFiles) { + foreach (var file in e) { + if (watchedFiles.Remove (file.FileName)) { + ConventionFileChanged?.Invoke (this, new ConventionsFileChangeEventArgs (file.FileName.FileName, file.FileName.ParentDirectory, ChangeType.FileDeleted)); + WatchDirectories (); + } + } + } + } + + public void Dispose () + { + FileService.FileMoved -= FileService_FileMoved; + FileService.FileRenamed -= FileService_FileMoved; + FileService.FileRemoved -= FileService_FileRemoved; + FileService.FileChanged -= FileService_FileChanged; + FileWatcherService.WatchDirectories (this, null).Ignore (); + lock (watchedFiles) { + watchedFiles = null; + } + } + + public void StartWatching (string fileName, string directoryPath) + { + lock (watchedFiles) { + var key = directoryPath + Path.DirectorySeparatorChar.ToString () + fileName; + + if (!File.Exists (key)) + return; + + if (!watchedFiles.Add (key)) + return; + + WatchDirectories (); + } + } + + public void StopWatching (string fileName, string directoryPath) + { + lock (watchedFiles) { - // var key = directoryPath + Path.DirectorySeparatorChar.ToString () + fileName; - // if (watchedFiles.Remove (key)) { - // WatchDirectories (); - // } - // } - // } - - // void WatchDirectories () - // { - // var directories = watchedFiles.Count == 0 ? null : watchedFiles.Select (file => new FilePath (file).ParentDirectory); - // FileWatcherService.WatchDirectories (this, directories).Ignore (); - // } - // } - // } -//} + var key = directoryPath + Path.DirectorySeparatorChar.ToString () + fileName; + if (watchedFiles.Remove (key)) { + WatchDirectories (); + } + } + } + + void WatchDirectories () + { + var directories = watchedFiles.Count == 0 ? null : watchedFiles.Select (file => new FilePath (file).ParentDirectory); + FileWatcherService.WatchDirectories (this, directories).Ignore (); + } + } + } +} */ diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/SingleFileDescriptionTemplate.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/SingleFileDescriptionTemplate.cs index ad2aa016065..050293e6762 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/SingleFileDescriptionTemplate.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/SingleFileDescriptionTemplate.cs @@ -482,12 +482,12 @@ public virtual async Task CreateFileContentAsync (SolutionFolderItem pol : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy (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; - // } + /* 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 (); @@ -509,12 +509,12 @@ public virtual async Task CreateFileContentAsync (SolutionFolderItem pol bool convertTabsToSpaces = textPolicy.TabsToSpaces; int tabWidth = textPolicy.TabWidth; - //if (ctx != null) { - //if (ctx.CurrentConventions.UniversalConventions.TryGetIndentStyle (out Microsoft.VisualStudio.CodingConventions.IndentStyle result)) - //convertTabsToSpaces = result == Microsoft.VisualStudio.CodingConventions.IndentStyle.Spaces; - //if (ctx.CurrentConventions.UniversalConventions.TryGetTabWidth (out int editorConfigTabWidth)) - // tabWidth = editorConfigTabWidth; - //} + /* if (ctx != null) { + if (ctx.CurrentConventions.UniversalConventions.TryGetIndentStyle (out Microsoft.VisualStudio.CodingConventions.IndentStyle result)) + convertTabsToSpaces = result == Microsoft.VisualStudio.CodingConventions.IndentStyle.Spaces; + if (ctx.CurrentConventions.UniversalConventions.TryGetTabWidth (out int editorConfigTabWidth)) + tabWidth = editorConfigTabWidth; + } */ var tabToSpaces = convertTabsToSpaces ? new string (' ', tabWidth) : null; IDocumentLine lastLine = null; @@ -529,13 +529,13 @@ public virtual async Task CreateFileContentAsync (SolutionFolderItem pol } 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); - // } - //} - //ctx.Dispose (); + /* if (ctx != null && lastLine != null && lastLine.Length > 0) { + if (ctx.CurrentConventions.UniversalConventions.TryGetRequireFinalNewline (out bool requireNewLine)) { + if (requireNewLine) + ms.Write (eolMarkerBytes, 0, eolMarkerBytes.Length); + } + } + ctx.Dispose (); */ ms.Position = 0; return ms; } diff --git a/main/tests/Ide.Tests/MonoDevelop.Ide.Editor/EditorConfigTests.cs b/main/tests/Ide.Tests/MonoDevelop.Ide.Editor/EditorConfigTests.cs index 9397909862d..a01fdac83ae 100644 --- a/main/tests/Ide.Tests/MonoDevelop.Ide.Editor/EditorConfigTests.cs +++ b/main/tests/Ide.Tests/MonoDevelop.Ide.Editor/EditorConfigTests.cs @@ -24,165 +24,166 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -// using System.IO; -// using NUnit.Framework; -// using UnitTests; -// using System.Threading; -// using GuiUnit; -// using System; -// using System.Threading.Tasks; -// using MonoDevelop.Ide.TextEditing; - -// namespace MonoDevelop.Ide.Editor -// { -// [TestFixture] -// [RequireService(typeof(TextEditorService))] -// class EditorConfigTests : IdeTestBase -// { - -// static async Task InvokeEditConfigTest (string editConfig, Action test) -// { -// string tempPath; -// int i = 0; -// while (true) { -// tempPath = Path.Combine (Path.GetTempPath (), Path.GetRandomFileName ()); -// if (!File.Exists (tempPath)) -// break; -// if (i++ > 100) -// Assert.Fail ("Can't create random path."); -// } - -// Directory.CreateDirectory (tempPath); -// try { -// string editorConfigFile = Path.Combine (tempPath, ".editorconfig"); -// File.WriteAllText (editorConfigFile, editConfig); -// var editor = TextEditorFactory.CreateNewEditor (); -// string fileName = Path.Combine (tempPath, "a.cs"); -// try { -// using (var ctx = await EditorConfigService.GetEditorConfigContext (fileName)) { -// ((DefaultSourceEditorOptions)editor.Options).SetContext (ctx); -// test (editor); -// } -// } finally { -// await EditorConfigService.RemoveEditConfigContext (fileName); -// } -// } finally { -// Directory.Delete (tempPath, true); -// } -// } - -// [Test] -// public async Task Test_indent_style () -// { -// await InvokeEditConfigTest (@" -// root = true -// [*.cs] -// indent_style = space -// ", editor => { -// Assert.AreEqual (true, editor.Options.TabsToSpaces); -// }); -// await InvokeEditConfigTest (@" -// root = true -// [*.cs] -// indent_style = tab -// ", editor => { -// Assert.AreEqual (false, editor.Options.TabsToSpaces); -// }); -// } - -// [Test] -// public async Task Test_indent_size () -// { -// await InvokeEditConfigTest (@" -// root = true -// [*.cs] -// indent_size = 42 -// ", editor => { -// Assert.AreEqual (42, editor.Options.IndentationSize); -// }); -// } - -// [Test] -// public async Task Test_tab_width () -// { -// await InvokeEditConfigTest (@" -// root = true -// [*.cs] -// tab_width = 42 -// ", editor => { -// Assert.AreEqual (42, editor.Options.TabSize); -// }); -// } - -// [Test] -// public async Task Test_end_of_line () -// { -// await InvokeEditConfigTest (@" -// root = true -// [*.cs] -// end_of_line = lf -// ", editor => { -// Assert.AreEqual ("\n", editor.Options.DefaultEolMarker); -// }); -// await InvokeEditConfigTest (@" -// root = true -// [*.cs] -// end_of_line = cr -// ", editor => { -// Assert.AreEqual ("\r", editor.Options.DefaultEolMarker); -// }); -// await InvokeEditConfigTest (@" -// root = true -// [*.cs] -// end_of_line = crlf -// ", editor => { -// Assert.AreEqual ("\r\n", editor.Options.DefaultEolMarker); -// }); -// } - -// [Test] -// public async Task Test_trim_trailing_whitespace () -// { -// await InvokeEditConfigTest (@" -// root = true -// [*.cs] -// trim_trailing_whitespace = true -// ", editor => { -// Assert.AreEqual (true, editor.Options.RemoveTrailingWhitespaces); -// }); - -// await InvokeEditConfigTest (@" -// root = true -// [*.cs] -// trim_trailing_whitespace = false -// ", editor => { -// Assert.AreEqual (false, editor.Options.RemoveTrailingWhitespaces); -// }); -// } - -// [Test] -// public async Task Test_max_line_length () -// { -// await InvokeEditConfigTest (@" -// root = true -// [*.cs] -// max_line_length = off -// ", editor => { -// Assert.AreEqual (false, editor.Options.ShowRuler); -// }); - -// await InvokeEditConfigTest (@" -// root = true -// [*.cs] -// max_line_length = 42 -// ", editor => { -// Assert.AreEqual (true, editor.Options.ShowRuler); -// Assert.AreEqual (42, editor.Options.RulerColumn); -// }); -// } - - - - -// } -// } +/* using System.IO; +using NUnit.Framework; +using UnitTests; +using System.Threading; +using GuiUnit; +using System; +using System.Threading.Tasks; +using MonoDevelop.Ide.TextEditing; + +namespace MonoDevelop.Ide.Editor +{ + [TestFixture] + [RequireService(typeof(TextEditorService))] + class EditorConfigTests : IdeTestBase + { + + static async Task InvokeEditConfigTest (string editConfig, Action test) + { + string tempPath; + int i = 0; + while (true) { + tempPath = Path.Combine (Path.GetTempPath (), Path.GetRandomFileName ()); + if (!File.Exists (tempPath)) + break; + if (i++ > 100) + Assert.Fail ("Can't create random path."); + } + + Directory.CreateDirectory (tempPath); + try { + string editorConfigFile = Path.Combine (tempPath, ".editorconfig"); + File.WriteAllText (editorConfigFile, editConfig); + var editor = TextEditorFactory.CreateNewEditor (); + string fileName = Path.Combine (tempPath, "a.cs"); + try { + using (var ctx = await EditorConfigService.GetEditorConfigContext (fileName)) { + ((DefaultSourceEditorOptions)editor.Options).SetContext (ctx); + test (editor); + } + } finally { + await EditorConfigService.RemoveEditConfigContext (fileName); + } + } finally { + Directory.Delete (tempPath, true); + } + } + + [Test] + public async Task Test_indent_style () + { + await InvokeEditConfigTest (@" +root = true +[*.cs] +indent_style = space +", editor => { + Assert.AreEqual (true, editor.Options.TabsToSpaces); + }); + await InvokeEditConfigTest (@" +root = true +[*.cs] +indent_style = tab +", editor => { + Assert.AreEqual (false, editor.Options.TabsToSpaces); + }); + } + + [Test] + public async Task Test_indent_size () + { + await InvokeEditConfigTest (@" +root = true +[*.cs] +indent_size = 42 +", editor => { + Assert.AreEqual (42, editor.Options.IndentationSize); + }); + } + + [Test] + public async Task Test_tab_width () + { + await InvokeEditConfigTest (@" +root = true +[*.cs] +tab_width = 42 +", editor => { + Assert.AreEqual (42, editor.Options.TabSize); + }); + } + + [Test] + public async Task Test_end_of_line () + { + await InvokeEditConfigTest (@" +root = true +[*.cs] +end_of_line = lf +", editor => { + Assert.AreEqual ("\n", editor.Options.DefaultEolMarker); + }); + await InvokeEditConfigTest (@" +root = true +[*.cs] +end_of_line = cr +", editor => { + Assert.AreEqual ("\r", editor.Options.DefaultEolMarker); + }); + await InvokeEditConfigTest (@" +root = true +[*.cs] +end_of_line = crlf +", editor => { + Assert.AreEqual ("\r\n", editor.Options.DefaultEolMarker); + }); + } + + [Test] + public async Task Test_trim_trailing_whitespace () + { + await InvokeEditConfigTest (@" +root = true +[*.cs] +trim_trailing_whitespace = true +", editor => { + Assert.AreEqual (true, editor.Options.RemoveTrailingWhitespaces); + }); + + await InvokeEditConfigTest (@" +root = true +[*.cs] +trim_trailing_whitespace = false +", editor => { + Assert.AreEqual (false, editor.Options.RemoveTrailingWhitespaces); + }); + } + + [Test] + public async Task Test_max_line_length () + { + await InvokeEditConfigTest (@" +root = true +[*.cs] +max_line_length = off +", editor => { + Assert.AreEqual (false, editor.Options.ShowRuler); + }); + + await InvokeEditConfigTest (@" +root = true +[*.cs] +max_line_length = 42 +", editor => { + Assert.AreEqual (true, editor.Options.ShowRuler); + Assert.AreEqual (42, editor.Options.RulerColumn); + }); + } + + + + + } +} + */ \ No newline at end of file From a0480614e748695de625a40ad58dcf0e9692e396 Mon Sep 17 00:00:00 2001 From: MakiWolf Date: Mon, 4 Sep 2023 23:36:13 +0200 Subject: [PATCH 4/6] comment out other sources --- NuGet.config | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/NuGet.config b/NuGet.config index 28f0a186b4d..1fd8b60b154 100644 --- a/NuGet.config +++ b/NuGet.config @@ -4,12 +4,12 @@ - + \ No newline at end of file From 8d2890808bb0b468ad3efb37808e2dc19fd3f9e7 Mon Sep 17 00:00:00 2001 From: MakiWolf Date: Mon, 4 Sep 2023 23:44:21 +0200 Subject: [PATCH 5/6] revert --- NuGet.config | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/NuGet.config b/NuGet.config index 1fd8b60b154..28f0a186b4d 100644 --- a/NuGet.config +++ b/NuGet.config @@ -4,12 +4,12 @@ - + \ No newline at end of file From 470a238044432851bd48f1162dfac258fae9ebd2 Mon Sep 17 00:00:00 2001 From: MakiWolf Date: Tue, 5 Sep 2023 00:11:46 +0200 Subject: [PATCH 6/6] comment out deprecated package --- main/msbuild/ReferencesVSEditor.Windows.props | 6 +++--- main/src/core/MonoDevelop.Core/MonoDevelop.Core.csproj | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/main/msbuild/ReferencesVSEditor.Windows.props b/main/msbuild/ReferencesVSEditor.Windows.props index f556230002d..fd4895e0de7 100644 --- a/main/msbuild/ReferencesVSEditor.Windows.props +++ b/main/msbuild/ReferencesVSEditor.Windows.props @@ -15,7 +15,7 @@ - + \ No newline at end of file diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Core.csproj b/main/src/core/MonoDevelop.Core/MonoDevelop.Core.csproj index 36139d27727..4dd6b3bb6df 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Core.csproj +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Core.csproj @@ -127,7 +127,7 @@ - +