Skip to content

Commit

Permalink
Support VS 2022
Browse files Browse the repository at this point in the history
  • Loading branch information
Shauren committed Jan 27, 2022
1 parent 76b88f7 commit 9b973e7
Show file tree
Hide file tree
Showing 14 changed files with 296 additions and 40 deletions.
9 changes: 9 additions & 0 deletions Shared/ITextReplacer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using EnvDTE;

namespace Shared
{
public interface ITextReplacer
{
void Replace(string whatRegex, string with, Document document);
}
}
20 changes: 0 additions & 20 deletions Shared/LICENSE

This file was deleted.

19 changes: 18 additions & 1 deletion Shared/SaveCommandPackage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using System;
using System.Diagnostics.CodeAnalysis;
Expand Down Expand Up @@ -44,11 +45,15 @@ namespace WhitespaceCleanerExtension
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_string, PackageAutoLoadFlags.BackgroundLoad)]
public sealed class SaveCommandPackage : AsyncPackage
{
public static SaveCommandPackage Instance { get; private set; }

/// <summary>
/// SaveCommandPackage GUID string.
/// </summary>
public const string PackageGuidString = "90ab0a97-fa71-411d-918e-28d82a7a9173";

public IComponentModel ComponentModel { get; private set; }

private SaveEventHandler _saveHandler;

/// <summary>
Expand All @@ -74,8 +79,20 @@ protected override async System.Threading.Tasks.Task InitializeAsync(Cancellatio

var dte = await GetServiceAsync(typeof(DTE)) as DTE2;

ComponentModel = GetGlobalService(typeof(SComponentModel)) as IComponentModel;

await JoinableTaskFactory.SwitchToMainThreadAsync();

#if VS2022
var textReplacer = new WhitespaceCleanerExtension2022.TextReplacer();
#else
var textReplacer = new TextReplacer(dte);
#endif

_saveHandler = new SaveEventHandler();
_saveHandler.OnConnection(dte);
_saveHandler.OnConnection(dte, textReplacer);

Instance = this;
}

#endregion
Expand Down
23 changes: 11 additions & 12 deletions Shared/SaveEventHandler.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
using Shared;
using System;
using System.Globalization;

Expand All @@ -10,24 +12,30 @@ public sealed class SaveEventHandler
private DTE2 _applicationObject;
private DocumentEvents _documentEvents;
private string _whitespaceRegex;
private ITextReplacer _textReplacer;
private bool _saved;

public void OnConnection(DTE2 application)
public void OnConnection(DTE2 application, ITextReplacer textReplacer)
{
ThreadHelper.ThrowIfNotOnUIThread();

_applicationObject = application;
_documentEvents = _applicationObject.Events.DocumentEvents;
_whitespaceRegex = ":Zs+$";
if (double.TryParse(_applicationObject.Version, NumberStyles.Number, CultureInfo.InvariantCulture, out double version))
if (version >= 11.0)
_whitespaceRegex = "[^\\S\\r\\n]+(?=\\r?$)";

_textReplacer = textReplacer;
_saved = false;

_documentEvents.DocumentSaved += DocumentEvents_DocumentSaved;
}

private void DocumentEvents_DocumentSaved(Document document)
{
ThreadHelper.ThrowIfNotOnUIThread();

if (!_saved)
{
try
Expand All @@ -41,20 +49,11 @@ private void DocumentEvents_DocumentSaved(Document document)
{
var tabSize = (short)props.Item("TabSize").Value;

_applicationObject.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, "\t",
(int)vsFindOptions.vsFindOptionsRegularExpression,
new string(' ', tabSize),
vsFindTarget.vsFindTargetCurrentDocument, string.Empty, string.Empty,
vsFindResultsLocation.vsFindResultsNone);
_textReplacer.Replace("\t", new string(' ', tabSize), document);
}

// Remove all the trailing whitespaces.
_applicationObject.Find.FindReplace(vsFindAction.vsFindActionReplaceAll,
_whitespaceRegex,
(int)vsFindOptions.vsFindOptionsRegularExpression,
string.Empty,
vsFindTarget.vsFindTargetCurrentDocument, string.Empty, string.Empty,
vsFindResultsLocation.vsFindResultsNone);
_textReplacer.Replace(_whitespaceRegex, string.Empty, document);

_saved = true;
document.Save();
Expand Down
2 changes: 1 addition & 1 deletion Shared/Shared.projitems
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
</PropertyGroup>
<ItemGroup>
<None Include="$(MSBuildThisFileDirectory)ExtensionKey.pfx" />
<None Include="$(MSBuildThisFileDirectory)LICENSE" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)ITextReplacer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SaveCommandPackage.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SaveEventHandler.cs" />
</ItemGroup>
Expand Down
7 changes: 7 additions & 0 deletions WhitespaceCleaner.sln
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WhitespaceCleanerExtension"
EndProject
Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Shared", "Shared\Shared.shproj", "{5DBA3B95-A4E9-4CA9-8EDB-D1CD707AF7BB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WhitespaceCleanerExtension2022", "WhitespaceCleanerExtension2022\WhitespaceCleanerExtension2022.csproj", "{2F77D666-4729-4CB5-95D7-A800BE80590F}"
EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
Shared\Shared.projitems*{2f77d666-4729-4cb5-95d7-a800be80590f}*SharedItemsImports = 4
Shared\Shared.projitems*{3a5eacc9-1e83-4d1c-bc07-f76eb241eb0d}*SharedItemsImports = 4
Shared\Shared.projitems*{5dba3b95-a4e9-4ca9-8edb-d1cd707af7bb}*SharedItemsImports = 13
EndGlobalSection
Expand All @@ -20,6 +23,10 @@ Global
{3A5EACC9-1E83-4D1C-BC07-F76EB241EB0D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3A5EACC9-1E83-4D1C-BC07-F76EB241EB0D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3A5EACC9-1E83-4D1C-BC07-F76EB241EB0D}.Release|Any CPU.Build.0 = Release|Any CPU
{2F77D666-4729-4CB5-95D7-A800BE80590F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2F77D666-4729-4CB5-95D7-A800BE80590F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2F77D666-4729-4CB5-95D7-A800BE80590F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2F77D666-4729-4CB5-95D7-A800BE80590F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
4 changes: 2 additions & 2 deletions WhitespaceCleanerExtension/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,5 @@
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.0.4")]
[assembly: AssemblyFileVersion("1.0.0.4")]
25 changes: 25 additions & 0 deletions WhitespaceCleanerExtension/TextReplacer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using EnvDTE;
using EnvDTE80;
using Shared;

namespace WhitespaceCleanerExtension
{
public sealed class TextReplacer : ITextReplacer
{
private DTE2 _applicationObject;

public TextReplacer(DTE2 applicationObject)
{
_applicationObject = applicationObject;
}

public void Replace(string whatRegex, string with, Document document)
{
_applicationObject.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, whatRegex,
(int)vsFindOptions.vsFindOptionsRegularExpression,
with,
vsFindTarget.vsFindTargetCurrentDocument, string.Empty, string.Empty,
vsFindResultsLocation.vsFindResultsNone);
}
}
}
13 changes: 10 additions & 3 deletions WhitespaceCleanerExtension/WhitespaceCleanerExtension.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DefineConstants>TRACE;DEBUG;VS2015</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
Expand All @@ -49,17 +49,21 @@
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\bin\Release\</OutputPath>
<DefineConstants>
</DefineConstants>
<DefineConstants>VS2015</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
<RunCodeAnalysis>false</RunCodeAnalysis>
</PropertyGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TextReplacer.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="..\LICENSE">
<Link>LICENSE</Link>
<IncludeInVSIX>true</IncludeInVSIX>
</Content>
<None Include="ExtensionKey.pfx" />
<None Include="source.extension.vsixmanifest">
<SubType>Designer</SubType>
Expand All @@ -72,6 +76,9 @@
<PackageReference Include="envdte80">
<Version>8.0.0</Version>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.ComponentModelHost">
<Version>14.0.25424</Version>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Shell.14.0">
<Version>14.3.25407</Version>
</PackageReference>
Expand Down
2 changes: 1 addition & 1 deletion WhitespaceCleanerExtension/source.extension.vsixmanifest
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<Metadata>
<Identity Id="WhitespaceCleanerExtension.Krzysztof Rapacki.876ffc7a-66dc-4aa0-8c52-971819604b60" Version="1.0.3" Language="en-US" Publisher="Krzysztof Rapacki" />
<Identity Id="WhitespaceCleanerExtension.Krzysztof Rapacki.876ffc7a-66dc-4aa0-8c52-971819604b60" Version="1.0.4" Language="en-US" Publisher="Krzysztof Rapacki" />
<DisplayName>WhitespaceCleanerExtension</DisplayName>
<Description xml:space="preserve">WhitespaceCleaner Extension for Visual Studio 2015 and newer

Expand Down
33 changes: 33 additions & 0 deletions WhitespaceCleanerExtension2022/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WhitespaceCleanerExtension2022")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WhitespaceCleanerExtension2022")]
[assembly: AssemblyCopyright("[email protected]")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(true)]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.4")]
[assembly: AssemblyFileVersion("1.0.0.4")]
56 changes: 56 additions & 0 deletions WhitespaceCleanerExtension2022/TextReplacer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using EnvDTE;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.TextManager.Interop;
using Shared;
using System;
using WhitespaceCleanerExtension;

namespace WhitespaceCleanerExtension2022
{
public sealed class TextReplacer : ITextReplacer
{
public void Replace(string whatRegex, string with, Document document)
{
ThreadHelper.ThrowIfNotOnUIThread();

if (TryGetTextBufferAt(document.FullName, out var textBuffer))
{
var findService = SaveCommandPackage.Instance.ComponentModel.GetService<IFindService>();

var finderFactory = findService.CreateFinderFactory(whatRegex, with, FindOptions.UseRegularExpressions);
var finder = finderFactory.Create(textBuffer.CurrentSnapshot);

using (var edit = textBuffer.CreateEdit())
{
foreach (var match in finder.FindForReplaceAll())
edit.Replace(match.Match, match.Replace);

edit.Apply();
}
}
}

private static bool TryGetTextBufferAt(string filePath, out ITextBuffer textBuffer)
{
if (VsShellUtilities.IsDocumentOpen(SaveCommandPackage.Instance, filePath, Guid.Empty, out var _, out var _, out var windowFrame))
{
IVsTextView view = VsShellUtilities.GetTextView(windowFrame);
if (view.GetBuffer(out var lines) == 0)
{
if (lines is IVsTextBuffer buffer)
{
var editorAdapterFactoryService = SaveCommandPackage.Instance.ComponentModel.GetService<IVsEditorAdaptersFactoryService>();
textBuffer = editorAdapterFactoryService.GetDataBuffer(buffer);
return true;
}
}
}

textBuffer = null;
return false;
}
}
}
Loading

0 comments on commit 9b973e7

Please sign in to comment.