如何创建命令行预测器
PSReadLine 2.1.0 通过实现预测 IntelliSense 功能引入了智能命令行预测器的概念。 PSReadLine 2.2.2 通过添加插件模型来扩展该功能,以便创建自己的命令行预测器。
预测 IntelliSense 会在你键入时在命令行上提供建议,以此增强 Tab 自动补全功能。 预测建议在光标后显示为彩色文本。 这样,便可以根据命令历史记录或其他特定于域的插件的匹配预测发现、编辑和执行完整命令。
系统要求
若要创建和使用插件预测器,必须使用以下版本的软件:
- PowerShell 7.2 (或更高版本) - 提供创建命令预测器所需的 API
- PSReadLine 2.2.2 (或更高版本) - 允许配置 PSReadLine 以使用插件
预测器概述
预测器是 PowerShell 二进制模块。 模块必须实现 System.Management.Automation.Subsystem.Prediction.ICommandPredictor
接口。 此接口声明用于查询预测结果和提供反馈的方法。
预测器模块必须在加载时使用 PowerShell 的 CommandPredictor
注册 SubsystemManager
子系统,并在卸载时取消注册。
下图显示了 PowerShell 中预测器的体系结构。
创建代码
若要创建预测器,必须为平台安装 .NET 6 SDK。 有关 SDK 的详细信息,请参阅 下载 .NET 6.0。
按照以下步骤创建新的 PowerShell 模块项目:
使用
dotnet
命令行工具创建初学者 classlib 项目。dotnet new classlib --name SamplePredictor
编辑
SamplePredictor.csproj
以包含以下信息:<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.0" /> </ItemGroup> </Project>
删除
dotnet
创建的默认Class1.cs
文件,并将以下代码复制到项目文件夹中的SamplePredictorClass.cs
文件。using System; using System.Collections.Generic; using System.Threading; using System.Management.Automation; using System.Management.Automation.Subsystem; using System.Management.Automation.Subsystem.Prediction; namespace PowerShell.Sample { public class SamplePredictor : ICommandPredictor { private readonly Guid _guid; internal SamplePredictor(string guid) { _guid = new Guid(guid); } /// <summary> /// Gets the unique identifier for a subsystem implementation. /// </summary> public Guid Id => _guid; /// <summary> /// Gets the name of a subsystem implementation. /// </summary> public string Name => "SamplePredictor"; /// <summary> /// Gets the description of a subsystem implementation. /// </summary> public string Description => "A sample predictor"; /// <summary> /// Get the predictive suggestions. It indicates the start of a suggestion rendering session. /// </summary> /// <param name="client">Represents the client that initiates the call.</param> /// <param name="context">The <see cref="PredictionContext"/> object to be used for prediction.</param> /// <param name="cancellationToken">The cancellation token to cancel the prediction.</param> /// <returns>An instance of <see cref="SuggestionPackage"/>.</returns> public SuggestionPackage GetSuggestion(PredictionClient client, PredictionContext context, CancellationToken cancellationToken) { string input = context.InputAst.Extent.Text; if (string.IsNullOrWhiteSpace(input)) { return default; } return new SuggestionPackage(new List<PredictiveSuggestion>{ new PredictiveSuggestion(string.Concat(input, " HELLO WORLD")) }); } #region "interface methods for processing feedback" /// <summary> /// Gets a value indicating whether the predictor accepts a specific kind of feedback. /// </summary> /// <param name="client">Represents the client that initiates the call.</param> /// <param name="feedback">A specific type of feedback.</param> /// <returns>True or false, to indicate whether the specific feedback is accepted.</returns> public bool CanAcceptFeedback(PredictionClient client, PredictorFeedbackKind feedback) => false; /// <summary> /// One or more suggestions provided by the predictor were displayed to the user. /// </summary> /// <param name="client">Represents the client that initiates the call.</param> /// <param name="session">The mini-session where the displayed suggestions came from.</param> /// <param name="countOrIndex"> /// When the value is greater than 0, it's the number of displayed suggestions from the list /// returned in <paramref name="session"/>, starting from the index 0. When the value is /// less than or equal to 0, it means a single suggestion from the list got displayed, and /// the index is the absolute value. /// </param> public void OnSuggestionDisplayed(PredictionClient client, uint session, int countOrIndex) { } /// <summary> /// The suggestion provided by the predictor was accepted. /// </summary> /// <param name="client">Represents the client that initiates the call.</param> /// <param name="session">Represents the mini-session where the accepted suggestion came from.</param> /// <param name="acceptedSuggestion">The accepted suggestion text.</param> public void OnSuggestionAccepted(PredictionClient client, uint session, string acceptedSuggestion) { } /// <summary> /// A command line was accepted to execute. /// The predictor can start processing early as needed with the latest history. /// </summary> /// <param name="client">Represents the client that initiates the call.</param> /// <param name="history">History command lines provided as references for prediction.</param> public void OnCommandLineAccepted(PredictionClient client, IReadOnlyList<string> history) { } /// <summary> /// A command line was done execution. /// </summary> /// <param name="client">Represents the client that initiates the call.</param> /// <param name="commandLine">The last accepted command line.</param> /// <param name="success">Shows whether the execution was successful.</param> public void OnCommandLineExecuted(PredictionClient client, string commandLine, bool success) { } #endregion; } /// <summary> /// Register the predictor on module loading and unregister it on module un-loading. /// </summary> public class Init : IModuleAssemblyInitializer, IModuleAssemblyCleanup { private const string Identifier = "843b51d0-55c8-4c1a-8116-f0728d419306"; /// <summary> /// Gets called when assembly is loaded. /// </summary> public void OnImport() { var predictor = new SamplePredictor(Identifier); SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, predictor); } /// <summary> /// Gets called when the binary module is unloaded. /// </summary> public void OnRemove(PSModuleInfo psModuleInfo) { SubsystemManager.UnregisterSubsystem(SubsystemKind.CommandPredictor, new Guid(Identifier)); } } }
以下示例代码返回所有用户输入的预测结果的字符串“HELLO WORLD”。 由于示例预测器不处理任何反馈,代码不会从接口实现反馈方法。 更改预测和反馈代码以满足预测器的需求。
注意
PSReadLine 的列表视图不支持多行建议。 每个建议都应是一行。 如果代码具有多行建议,则应将行拆分为单独的建议,或者将行与分号(
;
)联接。运行
dotnet build
以生成程序集。 可以在项目文件夹的bin/Debug/net6.0
位置中找到已编译的程序集。注意
为了确保响应式用户体验,ICommandPredictor 接口针对从预测器获取响应设定了 20 毫秒的超时时间。 要显示您的预测器代码,必须在 20 毫秒以内返回结果。
使用预测器插件
若要试用新的预测器,请打开新的 PowerShell 7.2 会话并运行以下命令:
Set-PSReadLineOption -PredictionSource HistoryAndPlugin
Import-Module .\bin\Debug\net6.0\SamplePredictor.dll
在会话中加载程序集后,在终端中键入时,会看到文本“HELLO WORLD”。 可以按 F2 在 Inline
视图和 List
视图之间切换。
有关 PSReadLine 选项的详细信息,请参阅 Set-PSReadLineOption。
可以使用以下命令获取已安装的预测器列表:
Get-PSSubsystem -Kind CommandPredictor
Kind SubsystemType IsRegistered Implementations
---- ------------- ------------ ---------------
CommandPredictor ICommandPredictor True {SamplePredictor}
注意
Get-PSSubsystem
是 PowerShell 7.1 中引入的实验性 cmdlet,必须启用 PSSubsystemPluginModel
实验性功能才能使用此 cmdlet。 有关详细信息,请参阅使用实验性功能。