├── DirectoryPredictor ├── DirectoryPredictor.psd1 ├── Enums.cs ├── Init.cs ├── ExceptionExtensions.cs ├── DirectoryPredictor.csproj ├── DirectoryPredictorStateSync.cs ├── Cmdlets.cs └── DirectoryPredictor.cs ├── DirectoryPredictor.sln ├── LICENSE ├── README.md └── .gitignore /DirectoryPredictor/DirectoryPredictor.psd1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ink230/DirectoryPredictor/HEAD/DirectoryPredictor/DirectoryPredictor.psd1 -------------------------------------------------------------------------------- /DirectoryPredictor/Enums.cs: -------------------------------------------------------------------------------- 1 | namespace DirectoryPredictor; 2 | 3 | public enum FileExtensions 4 | { 5 | None, 6 | Include, 7 | Exclude 8 | } 9 | 10 | public enum DirectoryMode 11 | { 12 | None, 13 | Files, 14 | Folders, 15 | Mixed, 16 | } 17 | 18 | public enum SortMixedResults 19 | { 20 | None, 21 | Files, 22 | Folders, 23 | } 24 | 25 | public enum ExtensionMode 26 | { 27 | None, 28 | Enabled, 29 | Disabled, 30 | } 31 | -------------------------------------------------------------------------------- /DirectoryPredictor/Init.cs: -------------------------------------------------------------------------------- 1 | using System.Management.Automation.Subsystem.Prediction; 2 | using System.Management.Automation; 3 | using System.Management.Automation.Subsystem; 4 | 5 | namespace DirectoryPredictor; 6 | 7 | public class Init : IModuleAssemblyInitializer, IModuleAssemblyCleanup 8 | { 9 | private const string Identifier = "843b51d0-55c8-4c1a-8116-f0728d419316"; 10 | 11 | public void OnImport() 12 | { 13 | var predictor = new DirectoryPredictor(Identifier); 14 | SubsystemManager.RegisterSubsystem(predictor); 15 | } 16 | 17 | public void OnRemove(PSModuleInfo psModuleInfo) 18 | { 19 | SubsystemManager.UnregisterSubsystem(new Guid(Identifier)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /DirectoryPredictor/ExceptionExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace DirectoryPredictor; 2 | static class ExceptionExtensions 3 | { 4 | public static IEnumerable Catch( 5 | this IEnumerable source, 6 | Type exceptionType) 7 | { 8 | using (var e = source.GetEnumerator()) 9 | while (true) 10 | { 11 | var ok = false; 12 | 13 | try 14 | { 15 | ok = e.MoveNext(); 16 | } 17 | catch (Exception ex) 18 | { 19 | if (ex.GetType() != exceptionType) 20 | throw; 21 | continue; 22 | } 23 | 24 | if (!ok) 25 | yield break; 26 | 27 | yield return e.Current; 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /DirectoryPredictor/DirectoryPredictor.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | none 11 | 12 | 13 | 14 | none 15 | 16 | 17 | 18 | 19 | contentFiles 20 | All 21 | 22 | 23 | 24 | 25 | 26 | Always 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /DirectoryPredictor.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.4.33103.184 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DirectoryPredictor", "DirectoryPredictor\DirectoryPredictor.csproj", "{D2D64C51-5340-4535-BD04-222F838B0579}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {D2D64C51-5340-4535-BD04-222F838B0579}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {D2D64C51-5340-4535-BD04-222F838B0579}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {D2D64C51-5340-4535-BD04-222F838B0579}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {D2D64C51-5340-4535-BD04-222F838B0579}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {B1E8A17A-68D9-4F8F-B2F6-8A300569E4F5} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 2-Clause License 2 | 3 | Copyright (c) 2023, Justin 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright notice, this 9 | list of conditions and the following disclaimer. 10 | 11 | 2. Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 16 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 19 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 20 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 21 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 22 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 23 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 24 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | -------------------------------------------------------------------------------- /DirectoryPredictor/DirectoryPredictorStateSync.cs: -------------------------------------------------------------------------------- 1 | using System.Management.Automation.Runspaces; 2 | using System.Management.Automation; 3 | 4 | namespace DirectoryPredictor; 5 | 6 | public partial class DirectoryPredictor 7 | { 8 | private void SyncRunspaceState(object? sender, RunspaceAvailabilityEventArgs e) 9 | { 10 | if (sender is null || e.RunspaceAvailability != RunspaceAvailability.Available) 11 | { 12 | return; 13 | } 14 | 15 | var pwshRunspace = (Runspace)sender; 16 | pwshRunspace.AvailabilityChanged -= SyncRunspaceState; 17 | 18 | try 19 | { 20 | using var ps = PowerShell.Create(); 21 | ps.Runspace = pwshRunspace; 22 | 23 | SyncCurrentValues(pwshRunspace); 24 | } 25 | finally 26 | { 27 | pwshRunspace.AvailabilityChanged += SyncRunspaceState; 28 | } 29 | } 30 | 31 | private void SyncCurrentValues(Runspace source) 32 | { 33 | PathInfo currentPath = source.SessionStateProxy.Path.CurrentLocation; 34 | _runspace.SessionStateProxy.Path.SetLocation(currentPath.Path); 35 | } 36 | 37 | private void RegisterEvents() 38 | { 39 | Runspace.DefaultRunspace.AvailabilityChanged += SyncRunspaceState; 40 | } 41 | 42 | private void UnregisterEvents() 43 | { 44 | Runspace.DefaultRunspace.AvailabilityChanged -= SyncRunspaceState; 45 | } 46 | } -------------------------------------------------------------------------------- /DirectoryPredictor/Cmdlets.cs: -------------------------------------------------------------------------------- 1 | using System.Management.Automation; 2 | 3 | namespace DirectoryPredictor; 4 | 5 | public sealed class DirectoryPredictorOptions 6 | { 7 | private static readonly DirectoryPredictorOptions _options = new DirectoryPredictorOptions(); 8 | public static DirectoryPredictorOptions Options => _options; 9 | static DirectoryPredictorOptions() { } 10 | private DirectoryPredictorOptions() { } 11 | 12 | public FileExtensions FileExtensions { get; set; } = FileExtensions.None; 13 | 14 | public bool IsEnabledFileExtensions() => (FileExtensions == FileExtensions.None || FileExtensions == FileExtensions.Include); 15 | 16 | public DirectoryMode DirectoryMode { get; set; } = DirectoryMode.None; 17 | 18 | public SortMixedResults SortMixedResults { get; set; } = SortMixedResults.None; 19 | 20 | public ExtensionMode ExtensionMode { get; set; } = ExtensionMode.None; 21 | 22 | public bool IsEnabledExtensionMode() => ExtensionMode == ExtensionMode.Enabled ? true : false; 23 | 24 | public int? ResultsLimit { get; set; } = 10; 25 | 26 | public string IgnoreCommands { get; set; } = string.Empty; 27 | 28 | public string[] GetIgnoreCommands() 29 | { 30 | return IgnoreCommands.Split(','); 31 | } 32 | } 33 | public class Cmdlets 34 | { 35 | [Cmdlet("Set", "DirectoryPredictorOption")] 36 | public class SetDirectoryPredictorOption : PSCmdlet 37 | { 38 | [Parameter] 39 | public FileExtensions FileExtensions 40 | { 41 | get => _fileExtensions.GetValueOrDefault(); 42 | set => _fileExtensions = value; 43 | } 44 | internal FileExtensions? _fileExtensions = FileExtensions.None; 45 | 46 | [Parameter] 47 | public DirectoryMode DirectoryMode 48 | { 49 | get => _directoryMode.GetValueOrDefault(); 50 | set => _directoryMode = value; 51 | } 52 | internal DirectoryMode? _directoryMode = DirectoryMode.None; 53 | 54 | [Parameter] 55 | public SortMixedResults SortMixedResults 56 | { 57 | get => _sortMixedResults.GetValueOrDefault(); 58 | set => _sortMixedResults = value; 59 | } 60 | internal SortMixedResults? _sortMixedResults = SortMixedResults.None; 61 | 62 | [Parameter] 63 | public ExtensionMode ExtensionMode 64 | { 65 | get => _extensionMode.GetValueOrDefault(); 66 | set => _extensionMode = value; 67 | } 68 | internal ExtensionMode? _extensionMode = ExtensionMode.None; 69 | 70 | [Parameter] 71 | [ValidateRange(1, 500)] 72 | public int ResultsLimit 73 | { 74 | get => _resultsLimit.GetValueOrDefault(); 75 | set => _resultsLimit = value; 76 | } 77 | internal int? _resultsLimit; 78 | 79 | [Parameter] 80 | [ValidateLength(0, 1000)] 81 | public string IgnoreCommands 82 | { 83 | get => _ignoreCommands ?? string.Empty; 84 | set => _ignoreCommands = value; 85 | } 86 | internal string? _ignoreCommands; 87 | 88 | private static readonly DirectoryPredictorOptions _options = DirectoryPredictorOptions.Options; 89 | public static DirectoryPredictorOptions Options => _options; 90 | 91 | protected override void EndProcessing() 92 | { 93 | if (FileExtensions != FileExtensions.None) 94 | { 95 | Options.FileExtensions = FileExtensions; 96 | } 97 | 98 | if (DirectoryMode != DirectoryMode.None) 99 | { 100 | Options.DirectoryMode = DirectoryMode; 101 | } 102 | 103 | if (SortMixedResults != SortMixedResults.None) 104 | { 105 | Options.SortMixedResults = SortMixedResults; 106 | } 107 | 108 | if (ExtensionMode != ExtensionMode.None) 109 | { 110 | Options.ExtensionMode = ExtensionMode; 111 | } 112 | 113 | if (ResultsLimit > 0) 114 | { 115 | Options.ResultsLimit = ResultsLimit; 116 | } 117 | 118 | if (!string.IsNullOrWhiteSpace(IgnoreCommands)) 119 | { 120 | Options.IgnoreCommands = IgnoreCommands; 121 | } 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ###

⚠️ EXPERIMENTAL IMPLEMENTATIONS ⚠️

2 | 3 | # Directory Predictor 4 | 5 | The Directory Predictor permits live directory file lookups for PSReadLine's auto-complete functionality. 6 | 7 | https://user-images.githubusercontent.com/29797557/212500726-26f98466-dd21-46e1-b793-a08c803e2c23.mp4 8 | 9 | 10 | **Features include...** 11 | - Pattern matching support (?, \*, |) 12 | - Search files, folders, or both 13 | - Hide or show file extensions 14 | - Search by file extension 15 | - Ignore specific commands 16 | - Sort results by files or folders 17 | - Limit the number of results 18 | 19 | # Installation 20 | 21 | ### PowerShell via [PSGallery](https://www.powershellgallery.com/packages/DirectoryPredictor/) 22 | 23 | ```Install-Module -Name DirectoryPredictor``` 24 | 25 | In your $profile add 26 | 27 | ```Import-Module DirectoryPredictor``` 28 | 29 | ### Filepath .dll 30 | 31 | Download the relevant .dll release and place where desired. In your $profile 32 | 33 | ```Import-Module 'path\to\folder\DirectoryPredictor.dll'``` 34 | 35 | ### PowerShell Configurations 36 | 37 | 1. Add the following to your $profile 38 | 39 | ```Enable-ExperimentalFeature PSSubsystemPluginModel``` 40 | 41 | 2. Check experimental features are enabled 42 | 43 | ```Get-PSSubsystem -Kind CommandPredictor``` 44 | 45 | 3. In $profile again 46 | 47 | ```Set-PSReadLineOption -PredictionSource HistoryAndPlugin``` 48 | 49 | 4. Restart or reload 50 | 51 | 5. Check the module is installed 52 | 53 | ```Get-PSSubsystem -Kind CommandPredictor``` 54 | 55 | 6. Test by typing in a directory 56 | 57 | ``` ``` 58 | 59 | # Configuration 60 | 61 | ### FileExtensions 62 | Determine if file extensions should show or not in the prediction and in the autocomplete result. 63 | 64 | ```Set-DirectoryPredictorOption -FileExtensions [Include | Exclude]``` 65 | 66 | ### DirectoryMode 67 | Search for files, folders, or both. 68 | 69 | ```Set-DirectoryPredictorOption -DirectoryMode [Files | Folders | Mixed]``` 70 | 71 | ### SortMixedResults 72 | Sort your results by Files or by Folders first. 73 | 74 | ```Set-DirectoryPredictorOption -SortMixedResults [Files | Folders]``` 75 | 76 | ### ExtensionMode 77 | Search file extensions. Does not work with -DirectoryMode Folders. 78 | 79 | ```Set-DirectoryPredictorOption -ExtensionMode [Enabled | Disabled]``` 80 | 81 | ### ResultsLimit 82 | Specify how many results, from 1 to 10, to display. 10 is a current limit by PSReadLine but the module will accept up to 500 currently. 83 | 84 | ```Set-DirectoryPredictorOption -ResultsLimit [1-10]``` 85 | 86 | ### IgnoreCommands 87 | Ignore specific commands in a comma separated string. This will cause those commands to not display [Directory] suggestions. 88 | 89 | ```Set-DirectoryPredictorOption -IgnoreCommands [comma separated list]``` 90 | 91 | ### Pattern Matching 92 | You have 3 pattern matching operators. 93 | 94 | - ? : Search anything that is available to be searched from the above cmdlet options 95 | - \* : Wildcard search. Before, after, or both. 96 | - | : OR pattern search. Search for results that match any number of the patterns provided. Supports multiple | operators. 97 | 98 | - Ex: 99 | ```ls 't|p``` or ```ls '*et|*pl``` or ```ls *ing``` or ```ls ?``` 100 | - *Note the ' or " is only required for multiple patterns* 101 | 102 | ### Tips 103 | * Each of these flags work great with aliases for fast on the fly adjustments 104 | * Example 105 | ``` 106 | Function ShowExtensions5 { 107 | Set-DirectoryPredictorOption -FileExtensions Include 108 | } 109 | Set-Alias -Name se -Value ShowExtensions 110 | 111 | Function HideExtensions { 112 | Set-DirectoryPredictorOption -FileExtensions Exclude 113 | } 114 | Set-Alias -Name he -Value HideExtensions 115 | ``` 116 | 117 | * You can disable the regular history results and only use the plugin with 118 | 119 | ```Set-PSReadLineOption -PredictionSource Plugin``` 120 | 121 | # Behaviour 122 | 123 | - All symbols but spaces are respected 124 | - Only the last word is used to search but previous input is respected 125 | - ```code -n hel``` will work and will match "hel" to filenames 126 | - Commands are ignored and no searching will display with just a command 127 | - Accepted completions are saved to the regular history at this time 128 | - Check the intro gif above for more insight 129 | 130 | # Roadmap 131 | 132 | As of v0.0.5, the plan is to gather even more user suggestions! 133 | 134 | If you have an idea, suggestion or want to contribute, please open an Issue! 135 | 136 | # Disclaimers 137 | 138 | 1. This is dabbling in ExperimentalFeatures that come with a warning of *breaking changes* or *unexpected behaviour*. 139 | 140 | 2. The intended purpose of PSReadLine predictive plugins are to be predictive. This predictor does not predict anything. 141 | 142 | # Credit / Resources 143 | ### [PSReadLine Github](https://github.com/PowerShell/PSReadLine) 144 | 145 | ### [CompletionPredictor Github](https://github.com/PowerShell/CompletionPredictor) 146 | 147 | ### [Microsoft Docs - Creating a Cmdlet](https://learn.microsoft.com/en-us/powershell/scripting/developer/cmdlet/creating-a-cmdlet-to-access-a-data-store?view=powershell-7.3) 148 | 149 | ### [Basic PSReadLine Configurations](https://jdhitsolutions.com/blog/powershell/8969/powershell-predicting-with-style/) 150 | 151 | ### [PowerShell - Experimental Features](https://learn.microsoft.com/en-us/powershell/scripting/learn/experimental-features?view=powershell-7.3) 152 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | /bin 34 | /obj 35 | bin/ 36 | obj/ 37 | .vs 38 | 39 | # Visual Studio 2015/2017 cache/options directory 40 | .vs/ 41 | # Uncomment if you have tasks that create the project's static files in wwwroot 42 | #wwwroot/ 43 | 44 | # Visual Studio 2017 auto generated files 45 | Generated\ Files/ 46 | 47 | # MSTest test Results 48 | [Tt]est[Rr]esult*/ 49 | [Bb]uild[Ll]og.* 50 | 51 | # NUnit 52 | *.VisualState.xml 53 | TestResult.xml 54 | nunit-*.xml 55 | 56 | # Build Results of an ATL Project 57 | [Dd]ebugPS/ 58 | [Rr]eleasePS/ 59 | dlldata.c 60 | 61 | # Benchmark Results 62 | BenchmarkDotNet.Artifacts/ 63 | 64 | # .NET Core 65 | project.lock.json 66 | project.fragment.lock.json 67 | artifacts/ 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Visual Studio code coverage results 146 | *.coverage 147 | *.coveragexml 148 | 149 | # NCrunch 150 | _NCrunch_* 151 | .*crunch*.local.xml 152 | nCrunchTemp_* 153 | 154 | # MightyMoose 155 | *.mm.* 156 | AutoTest.Net/ 157 | 158 | # Web workbench (sass) 159 | .sass-cache/ 160 | 161 | # Installshield output folder 162 | [Ee]xpress/ 163 | 164 | # DocProject is a documentation generator add-in 165 | DocProject/buildhelp/ 166 | DocProject/Help/*.HxT 167 | DocProject/Help/*.HxC 168 | DocProject/Help/*.hhc 169 | DocProject/Help/*.hhk 170 | DocProject/Help/*.hhp 171 | DocProject/Help/Html2 172 | DocProject/Help/html 173 | 174 | # Click-Once directory 175 | publish/ 176 | 177 | # Publish Web Output 178 | *.[Pp]ublish.xml 179 | *.azurePubxml 180 | # Note: Comment the next line if you want to checkin your web deploy settings, 181 | # but database connection strings (with potential passwords) will be unencrypted 182 | *.pubxml 183 | *.publishproj 184 | 185 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 186 | # checkin your Azure Web App publish settings, but sensitive information contained 187 | # in these scripts will be unencrypted 188 | PublishScripts/ 189 | 190 | # NuGet Packages 191 | *.nupkg 192 | # NuGet Symbol Packages 193 | *.snupkg 194 | # The packages folder can be ignored because of Package Restore 195 | **/[Pp]ackages/* 196 | # except build/, which is used as an MSBuild target. 197 | !**/[Pp]ackages/build/ 198 | # Uncomment if necessary however generally it will be regenerated when needed 199 | #!**/[Pp]ackages/repositories.config 200 | # NuGet v3's project.json files produces more ignorable files 201 | *.nuget.props 202 | *.nuget.targets 203 | 204 | # Microsoft Azure Build Output 205 | csx/ 206 | *.build.csdef 207 | 208 | # Microsoft Azure Emulator 209 | ecf/ 210 | rcf/ 211 | 212 | # Windows Store app package directories and files 213 | AppPackages/ 214 | BundleArtifacts/ 215 | Package.StoreAssociation.xml 216 | _pkginfo.txt 217 | *.appx 218 | *.appxbundle 219 | *.appxupload 220 | 221 | # Visual Studio cache files 222 | # files ending in .cache can be ignored 223 | *.[Cc]ache 224 | # but keep track of directories ending in .cache 225 | !?*.[Cc]ache/ 226 | 227 | # Others 228 | ClientBin/ 229 | ~$* 230 | *~ 231 | *.dbmdl 232 | *.dbproj.schemaview 233 | *.jfm 234 | *.pfx 235 | *.publishsettings 236 | orleans.codegen.cs 237 | 238 | # Including strong name files can present a security risk 239 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 240 | #*.snk 241 | 242 | # Since there are multiple workflows, uncomment next line to ignore bower_components 243 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 244 | #bower_components/ 245 | 246 | # RIA/Silverlight projects 247 | Generated_Code/ 248 | 249 | # Backup & report files from converting an old project file 250 | # to a newer Visual Studio version. Backup files are not needed, 251 | # because we have git ;-) 252 | _UpgradeReport_Files/ 253 | Backup*/ 254 | UpgradeLog*.XML 255 | UpgradeLog*.htm 256 | ServiceFabricBackup/ 257 | *.rptproj.bak 258 | 259 | # SQL Server files 260 | *.mdf 261 | *.ldf 262 | *.ndf 263 | 264 | # Business Intelligence projects 265 | *.rdl.data 266 | *.bim.layout 267 | *.bim_*.settings 268 | *.rptproj.rsuser 269 | *- [Bb]ackup.rdl 270 | *- [Bb]ackup ([0-9]).rdl 271 | *- [Bb]ackup ([0-9][0-9]).rdl 272 | 273 | # Microsoft Fakes 274 | FakesAssemblies/ 275 | 276 | # GhostDoc plugin setting file 277 | *.GhostDoc.xml 278 | 279 | # Node.js Tools for Visual Studio 280 | .ntvs_analysis.dat 281 | node_modules/ 282 | 283 | # Visual Studio 6 build log 284 | *.plg 285 | 286 | # Visual Studio 6 workspace options file 287 | *.opt 288 | 289 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 290 | *.vbw 291 | 292 | # Visual Studio LightSwitch build output 293 | **/*.HTMLClient/GeneratedArtifacts 294 | **/*.DesktopClient/GeneratedArtifacts 295 | **/*.DesktopClient/ModelManifest.xml 296 | **/*.Server/GeneratedArtifacts 297 | **/*.Server/ModelManifest.xml 298 | _Pvt_Extensions 299 | 300 | # Paket dependency manager 301 | .paket/paket.exe 302 | paket-files/ 303 | 304 | # FAKE - F# Make 305 | .fake/ 306 | 307 | # CodeRush personal settings 308 | .cr/personal 309 | 310 | # Python Tools for Visual Studio (PTVS) 311 | __pycache__/ 312 | *.pyc 313 | 314 | # Cake - Uncomment if you are using it 315 | # tools/** 316 | # !tools/packages.config 317 | 318 | # Tabs Studio 319 | *.tss 320 | 321 | # Telerik's JustMock configuration file 322 | *.jmconfig 323 | 324 | # BizTalk build output 325 | *.btp.cs 326 | *.btm.cs 327 | *.odx.cs 328 | *.xsd.cs 329 | 330 | # OpenCover UI analysis results 331 | OpenCover/ 332 | 333 | # Azure Stream Analytics local run output 334 | ASALocalRun/ 335 | 336 | # MSBuild Binary and Structured Log 337 | *.binlog 338 | 339 | # NVidia Nsight GPU debugger configuration file 340 | *.nvuser 341 | 342 | # MFractors (Xamarin productivity tool) working folder 343 | .mfractor/ 344 | 345 | # Local History for Visual Studio 346 | .localhistory/ 347 | 348 | # BeatPulse healthcheck temp database 349 | healthchecksdb 350 | 351 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 352 | MigrationBackup/ 353 | 354 | # Ionide (cross platform F# VS Code tools) working folder 355 | .ionide/ 356 | 357 | -------------------------------------------------------------------------------- /DirectoryPredictor/DirectoryPredictor.cs: -------------------------------------------------------------------------------- 1 | using System.Management.Automation.Language; 2 | using System.Management.Automation.Runspaces; 3 | using System.Management.Automation.Subsystem.Prediction; 4 | 5 | namespace DirectoryPredictor; 6 | 7 | public partial class DirectoryPredictor : ICommandPredictor, IDisposable 8 | { 9 | private readonly Guid _guid; 10 | private Runspace _runspace { get; } 11 | 12 | private DirectoryPredictorOptions Options { get => DirectoryPredictorOptions.Options; } 13 | private DirectoryMode DirectoryMode { get => Options.DirectoryMode; } 14 | private SortMixedResults SortMixedResults { get => Options.SortMixedResults; } 15 | private bool IncludeFileExtensions { get => Options.IsEnabledFileExtensions(); } 16 | private bool ExtensionMode { get => Options.IsEnabledExtensionMode(); } 17 | private int ResultsLimit { get => Options.ResultsLimit.GetValueOrDefault(); } 18 | private string[] IgnoreCommands { get => Options.GetIgnoreCommands(); } 19 | private Func FileNameFormat 20 | { 21 | get => IncludeFileExtensions ? 22 | (file => Path.GetFileName(file).ToLower()) : 23 | (file => Path.GetFileNameWithoutExtension(file).ToLower()); 24 | } 25 | 26 | public Guid Id => _guid; 27 | public string Name => "Directory"; 28 | public string Description => "Directory predictor"; 29 | 30 | internal DirectoryPredictor(string guid) 31 | { 32 | _guid = new Guid(guid); 33 | _runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault()); 34 | _runspace.Name = this.GetType().Name; 35 | _runspace.Open(); 36 | 37 | RegisterEvents(); 38 | } 39 | 40 | public SuggestionPackage GetSuggestion(PredictionClient client, PredictionContext context, CancellationToken cancellationToken) 41 | { 42 | var token = context.TokenAtCursor; 43 | var input = context.InputAst.Extent.Text.Replace("\"", "").Replace("\'", ""); 44 | 45 | if (!ValidInput(token, input)) return default; 46 | 47 | if (IsIgnoredCommand(input)) return default; 48 | 49 | var pattern = GetSearchPattern(input); 50 | var matches = GetDirectorySearchResults(pattern); 51 | var suggestions = BuildSuggestionPackage(input, matches); 52 | 53 | return suggestions; 54 | } 55 | 56 | private bool ValidInput(Token token, string input) 57 | { 58 | if (token is null) return false; 59 | 60 | if (token.TokenFlags.HasFlag(TokenFlags.CommandName)) return false; 61 | 62 | if (string.IsNullOrWhiteSpace(input)) return false; 63 | 64 | return true; 65 | } 66 | 67 | private bool IsIgnoredCommand(string input) 68 | { 69 | var firstWordIndex = input.IndexOf(' '); 70 | var command = input.Substring(0, firstWordIndex); 71 | 72 | if (IgnoreCommands.Any(c => c == command)) return true; 73 | 74 | return false; 75 | } 76 | 77 | private string GetSearchPattern(string input) 78 | { 79 | var lastWordIndex = input.LastIndexOf(' '); 80 | var inputSearchText = input.Substring(lastWordIndex + 1); 81 | string pattern = ""; 82 | 83 | var searchTexts = inputSearchText.Split("|", StringSplitOptions.RemoveEmptyEntries); 84 | 85 | foreach (var searchText in searchTexts) 86 | { 87 | 88 | if (ExtensionMode) 89 | { 90 | pattern += $"*.{searchText}*|"; 91 | } 92 | else 93 | { 94 | pattern += $"{searchText}*.*|"; 95 | } 96 | } 97 | 98 | return pattern; 99 | } 100 | 101 | private string[] GetDirectorySearchResults(string pattern) 102 | { 103 | var dir = _runspace.SessionStateProxy.Path.CurrentLocation.ToString(); 104 | var searchOptions = SearchOption.TopDirectoryOnly; 105 | 106 | var resultList = new List(); 107 | var collectedFiles = new HashSet(); 108 | 109 | var subPatterns = pattern.Split('|', StringSplitOptions.RemoveEmptyEntries); 110 | 111 | List DoSearch(string sub) 112 | { 113 | var subResultList = new List(); 114 | 115 | if (DirectoryMode == DirectoryMode.None || DirectoryMode == DirectoryMode.Files || DirectoryMode == DirectoryMode.Mixed) 116 | { 117 | subResultList.AddRange(Directory.GetFiles(dir, sub, searchOptions) 118 | .Catch(typeof(UnauthorizedAccessException)) 119 | .Where(file => 120 | { 121 | if (collectedFiles.Contains(file)) return false; 122 | 123 | collectedFiles.Add(file); 124 | return true; 125 | }) 126 | .Select(FileNameFormat) 127 | .Take(ResultsLimit)); 128 | 129 | } 130 | 131 | if (DirectoryMode == DirectoryMode.Folders || DirectoryMode == DirectoryMode.Mixed) 132 | { 133 | subResultList.AddRange(Directory.GetDirectories(dir, sub, searchOptions) 134 | .Catch(typeof(UnauthorizedAccessException)) 135 | .Where(folder => 136 | { 137 | if (collectedFiles.Contains(folder)) return false; 138 | 139 | collectedFiles.Add(folder); 140 | return true; 141 | }) 142 | .Select(FileNameFormat) 143 | .Select(x => DirectoryMode == DirectoryMode.Mixed ? x + " #folder" : x) 144 | .Take(ResultsLimit)); 145 | } 146 | 147 | return subResultList; 148 | } 149 | 150 | foreach (var subPattern in subPatterns) 151 | { 152 | resultList.AddRange(DoSearch(subPattern)); 153 | } 154 | 155 | if (DirectoryMode == DirectoryMode.Mixed && SortMixedResults == SortMixedResults.Folders) 156 | { 157 | resultList.Sort((a, b) => 158 | { 159 | if (a.EndsWith("#folder") && !b.EndsWith("#folder")) 160 | { 161 | return -1; 162 | } 163 | else if (!a.EndsWith("#folder") && b.EndsWith("#folder")) 164 | { 165 | return 1; 166 | } 167 | else 168 | { 169 | return a.CompareTo(b); 170 | } 171 | }); 172 | } 173 | 174 | return resultList.ToArray(); 175 | } 176 | 177 | private SuggestionPackage BuildSuggestionPackage(string input, string[] matches) 178 | { 179 | if (DirectoryMode == DirectoryMode.Folders && ExtensionMode) 180 | { 181 | List shortCircuitMessage = new List(); 182 | shortCircuitMessage.Add(new PredictiveSuggestion($"You have both Folder mode and Extension mode enabled. Disable one to see results.")); 183 | return new SuggestionPackage(shortCircuitMessage); 184 | } 185 | var lastWordIndex = input.LastIndexOf(' '); 186 | var returnInput = input.Substring(0, lastWordIndex); 187 | 188 | List suggestions = matches.Select(file => new PredictiveSuggestion($"{returnInput} {file}")).ToList(); 189 | 190 | return new SuggestionPackage(suggestions); 191 | } 192 | 193 | public void Dispose() 194 | { 195 | UnregisterEvents(); 196 | _runspace.Dispose(); 197 | } 198 | 199 | #region CommandPredictor 200 | /// 201 | /// Gets a value indicating whether the predictor accepts a specific kind of feedback. 202 | /// 203 | /// Represents the client that initiates the call. 204 | /// A specific type of feedback. 205 | /// True or false, to indicate whether the specific feedback is accepted. 206 | public bool CanAcceptFeedback(PredictionClient client, PredictorFeedbackKind feedback) => false; 207 | 208 | /// 209 | /// One or more suggestions provided by the predictor were displayed to the user. 210 | /// 211 | /// Represents the client that initiates the call. 212 | /// The mini-session where the displayed suggestions came from. 213 | /// 214 | /// When the value is greater than 0, it's the number of displayed suggestions from the list 215 | /// returned in , starting from the index 0. When the value is 216 | /// less than or equal to 0, it means a single suggestion from the list got displayed, and 217 | /// the index is the absolute value. 218 | /// 219 | public void OnSuggestionDisplayed(PredictionClient client, uint session, int countOrIndex) { } 220 | 221 | /// 222 | /// The suggestion provided by the predictor was accepted. 223 | /// 224 | /// Represents the client that initiates the call. 225 | /// Represents the mini-session where the accepted suggestion came from. 226 | /// The accepted suggestion text. 227 | public void OnSuggestionAccepted(PredictionClient client, uint session, string acceptedSuggestion) { } 228 | 229 | /// 230 | /// A command line was accepted to execute. 231 | /// The predictor can start processing early as needed with the latest history. 232 | /// 233 | /// Represents the client that initiates the call. 234 | /// History command lines provided as references for prediction. 235 | public void OnCommandLineAccepted(PredictionClient client, IReadOnlyList history) { } 236 | 237 | /// 238 | /// A command line was done execution. 239 | /// 240 | /// Represents the client that initiates the call. 241 | /// The last accepted command line. 242 | /// Shows whether the execution was successful. 243 | public void OnCommandLineExecuted(PredictionClient client, string commandLine, bool success) { } 244 | #endregion; 245 | } --------------------------------------------------------------------------------