Windows命令行代码自动补全详细步骤

121 阅读2分钟

在 Linux 或 macOS 上,很多开发者喜欢使用 zsh + oh-my-zsh 来获得强大的命令补全、历史搜索和美化提示。在 Windows 上,我们也可以打造类似体验,利用 PowerShell 7 + Oh My Posh + PSReadLine + posh-git,并让 VS Code 终端完美适配。本文将详细介绍安装与配置步骤。

一、安装 Nerd Fonts 字体

Oh My Posh 使用了大量图标和 Git 状态符号,如果字体不支持就会出现乱码。推荐字体包括:

  • Cascadia Code PL
  • MesloLGS NF
  • JetBrainsMono Nerd Font

下载地址:Nerd Fonts 官网

安装步骤:

  1. 下载你喜欢的 Nerd Font。
  2. 双击字体文件 → 点击“安装”。
  3. 在终端或 VS Code 设置中选择该字体。

二、安装 PowerShell 7

PowerShell 7 是新版跨平台 PowerShell,提供更多特性和兼容性。

官方安装指南:Installing PowerShell on Windows

安装完成后,可以在命令行确认版本:

pwsh --version

如果显示 7.x.x,说明安装成功。

注意Windows 默认仍保留 PowerShell 5.1,VS Code 或 CMD 可能默认启动的是旧版,需要手动设置。

安装完之后到设置如果看不到PowerShell 7,那么手动添加一个配置文件

三、安装 Oh My Posh、posh-git 和 PSReadLine

在 PowerShell 7 中执行:

# 更新 PowerShellGet
Install-Module -Name PowerShellGet -Force

# 安装 Oh My Posh
winget install JanDeDobbeleer.OhMyPosh -s winget

# 安装 posh-git(Git 自动补全)
Install-Module posh-git -Scope CurrentUser -Force

# 安装 PSReadLine(增强自动补全)
Install-Module PSReadLine

四、修改 PowerShell 配置文件

PowerShell 配置文件路径:

$PROFILE

可以用 VS Code 打开:

code $PROFILE

在文件末尾加入:

# Tab 键显示自动补全菜单
Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete

# 上下方向键搜索历史命令
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward

# 启动 Oh My Posh
oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH/jandedobbeleer.omp.json" | Invoke-Expression

# 启用 Git 自动补全
Import-Module posh-git

保存并重启 PowerShell,就可以啦。

五、VS Code 终端配置

为了在 VS Code 内部也能使用 PowerShell 7 和 Oh My Posh,需要修改 VS Code 的 settings.json

打开 settings.json

  1. 按快捷键:
Ctrl + Shift + P
  1. 输入:
settings json

或者点击右上角的按钮转换成json

添加配置

{
    "terminal.integrated.defaultProfile.windows": "PowerShell 7",
    "terminal.integrated.profiles.windows": {
        "PowerShell 7": {
            "path": "D:\\Program Files (x86)\\PowerShell\\7\\pwsh.exe",
            "icon": "terminal-powershell"
        }
    },
    "terminal.integrated.fontFamily": "JetBrainsMono Nerd Font"
}

注意:路径根据实际安装位置调整。
字体名称必须和安装的 Nerd Font 对应。

保存并重启 VS Code 终端

  1. 关闭所有终端
  2. 打开新终端

大功告成!

📚推荐阅读

Git安装教程及常用命令!

Cursor使用教程!

TensorBoard最全使用教程!

多个 GitHub 账户SSH 密钥配置全攻略

关于深度学习和大模型相关的知识和前沿技术更新,请关注公众号aicoting!