Skip to content

Windows Powershell 的改进

原来的Windows Powershell使用oh-my-posh进行了Prompt美化,直接在官网使用了默认方案,但启动速度一直不是很理想。

后面才知道oh-my-posh 3用Golang重写了,原因是想用到不同终端上(疯了,别的终端为什么要用powershell的东西),才变得又卡又慢,体积还增大了。

根据上面的速度测试结果,我打算在两个Powershell上都换用starship作为Prompt工具,Windows Powershell就不做过多配置。

首先卸载现在的oh-my-posh,先用(Get-Command oh-my-posh).Source 得到exe的目录,然后找到卸载程序,直接运行即可。

根据官网提示安装starship:

https://starship.rs/zh-cn/guide/

bash
scoop install starship

https://github.com/starship/starship/releases/tag/v1.18.1

也可以通过shell脚本快速安装。

bash
curl -sS https://starship.rs/install.sh | sh

或者使用Rust的包管理器cargo安装,前提是已经安装了Rust。

bash
cargo install starship --locked

启用

要使 Starship 在终端中产生效果,需要在各个终端的配置文件中启用。例如对于 Bash,需要执行:

bash
echo 'eval "$(starship init bash)"' >> ~/.profile

对于 Powershell,可以使用 VS Code 直接编辑$PROFILE:

bash
code $PROFILE

并在打开的文件最后,加入一行:

text
Invoke-Expression (&starship init powershell)

Powershell 7的改进

除了在Windows Powershell中的Prompt工具外,Powershell 7 作为开发终端,我还需求一些额外的zsh功能:

Bash-like Tab 补全 自动命令建议(IntelliSense) 基于历史记录的搜索 经过调研发现,上述这些功能都在Powershell官方提供的PSReadLine包中提供了,更巧的是这个包在Windows Powershell 5.1 和Powershell 7中都已经内置了,只需要使用选项激活即可。

事不宜迟,立刻编辑$PROFILE :

text
Invoke-Expression (&starship init powershell)

Set-PSReadLineOption -PredictionSource History # 设置预测文本来源为历史记录
Set-PSReadLineOption -Colors @{ InlinePrediction = '#875f5f'} # 增加预测内容在亚克力背景下的可读性

Set-PSReadlineKeyHandler -Key Tab -Function Complete # 设置 Tab 键补全
Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete # 设置 Ctrl+d 为菜单补全和 Intellisense
Set-PSReadLineKeyHandler -Key "Ctrl+z" -Function Undo # 设置 Ctrl+z 为撤销
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward # 设置向上键为后向搜索历史记录
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward # 设置向下键为前向搜索历史纪录

根据我的习惯,我做了以下定制:

Tab映射为补全和菜单补全(只有一项时就直接补全) 上下箭头映射为历史记录搜索,没有输入则是默认行为 最重要的是,将预测文本来源为历史记录,提供了命令建议,这个键位是右箭头

检测是否有配置好文件

bash
Test-path $profile

安装字体

在Nerd font网站下载字体文件压缩包。https://www.nerdfonts.com/

解压字体到~/.fonts文件夹内。

运行fc-cache -fv添加字体。

为了显示效果完美呈现,可以在使用终端的系统中安装一个 Nerd Font 字体,用来显示一些图标字符。例如在 Windows 中可以执行:

bash
choco install firacodenf

并在 Windows Terminal 中启用该字体:

Starship 使用 Rust 编写,对性能的影响很小

Starship 的配置全部放在一个名为 starship.toml 的文件中

参考

https://sspai.com/post/72888?utm_source=twitter&utm_medium=social

工欲善其事,必先利其器——打造自己趁手的终端体验

windows terminal加powershell7美化命令行操作

Contributors

作者:Long Mo
字数统计:875 字
阅读时长:3 分钟
Long Mo
文章作者:Long Mo
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Longmo Docs