oh-my-posh & posh-git 提升在 windows 环境的开发体验

1,453 阅读2分钟

迁移到使用 windows 环境有了一段时间,经过一些列的配置之后,发现开发体验跟 mac 没有多大的区别了,在开发体验配置中,感觉最为明显的是让 PowerShell 有使用 zsh 的体验,这就要提到 oh-my-poshposh-git 了。

oh-my-zsh 和 oh-my-posh 是用于自定义 PowerShell 主题和配色的工具,它们提供了丰富的选项。另外,posh-git 则是为 PowerShell 提供了方便的 git 状态显示和命令补全功能。

Let's Go

首先确保安装好了 PowerShell 7

其次需要安装一个下载器 winget , 这个可以直接在 Microsoft Store 中直接安装。

打开 PowerShell 7(后面简写成 PS7):

# 本命令会下载 oh-my-posh.exe 和 最新的主题包 themes
winget install JanDeDobbeleer.OhMyPosh -s winget

# 安装 posh-git
Install-Module posh-git -Scope CurrentUser -Force

安装完成之后,最后重启一下 PS7。

安装必要的字体

因为主题中大量使用了 Nerd Fonts 家族字体,不安装的话,显示效果会不忍直视。

我们依然使用配套的命令安装字体即可(该命令需要管理员权限打开 PS7):

oh-my-posh font install

命令执行之后,会有列表选择安装哪种字体,可以先随便挑几个安装。

安装完字体之后,需要修改 PS7 的字体,在右上角点击设置进入到配置中,选择安装好的字体,比如 MesloLGM NF

编写配置文件

使用 notepad 来编辑我们的配置文件:

notepad $PROFILE

# 如果提示文件没有找到可以使用下面的命令创建一个
# New-Item -Path $PROFILE -Type File -Force
# 引入 posh-git
Import-Module posh-git

# 初始化 oh-my-posh 并指定主题,主题配置文件可以到 themes 目录中进行挑选,更多明细的配置可以参考官方文档
oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH/cobalt2.omp.json" | Invoke-Expression

# Shows navigable menu of all options when hitting Tab
Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete

# Autocompletion for arrow keys
Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward

# PSReadLine 是一个内置的模块,可以通过上下键和tab键来快速输入历史记录
Import-Module PSReadLine
Set-PSReadLineOption -PredictionSource History

编辑完成之后,需要重新载入一下配置文件键:

. $PROFILE

到此,配置已经完成,命令行UI发生了很大的变化。