在控制台上以编程方式更改字体类型和大小

Change font type and size programmatically on the console

当然,我可以进入设置并更改字体,这个问题已经在其他地方得到了很多很好的回答。这是一个完全不同的问题(或者至少,我还没有找到答案)。 4 年零 7 个月前,这个问题上有一个小 (虽然只是针对 PowerShell),但这似乎是一个死胡同(当然是在 WSL 和 Windows 终端存在之前) .

如果我在控制台中,我希望能够键入一个命令来更改我所在的控制台的字体(无论是通过注册表还是 json Windows 中的设置终端等)?

例如Resize-Console Consolas 14 在控制台内会立即将控制台更改为该字体大小,而无需进入设置面板等。

如果解决方案仅适用于 Windows 终端,我将非常高兴,因为这显然是微软针对 Windows 上的控制台所关注的千篇一律的未来,它有一个 json 设置结构,可能比其他控制台更容易修改。

据我所知,目前只能通过 settings.json 进行字体设置。通常我建议使用 jq 来编辑 json,但是 settings.json 包含注释,根据 jq,这使其“不是真正的 json”。

(旁白 - 这不是真正的 jq 问题。在数据结构中混合代码(注释)确实很难处理。我认为你真的必须从处理数据转移处理 AST 的结构。根据我的经验,大多数库都不会t/can保留数据内部的注释,无论数据类型是什么。)

如果您可以删除评论(我不是 - 它们非常有用),那么您可以使用相当简单的 jq query/set.

但是如果我们想保留评论,我们需要将 settings.json 视为简单的“文本”,并使用类似 sed 的老式方法。请注意,此示例假定您已添加 "fontFace""fontSize" inside your profiles.defaults`。如果您已经或希望在每个配置文件的基础上设置它,则需要相应地调整正则表达式。

这是我的部分,缩写为:

{
    "$schema": "https://aka.ms/terminal-profiles-schema",

...

    // A profile specifies a command to execute paired with information about how it should look and feel.
    // Each one of them will appear in the 'New Tab' dropdown,
    //   and can be invoked from the commandline with `wt.exe -p xxx`
    // To learn more about profiles, visit https://aka.ms/terminal-profile-settings
    "profiles":
    {
        "defaults":
        {
            // Put settings here that you want to apply to all profiles.

            // From Nerd Fonts
            // https://github.com/ryanoasis/nerd-fonts
            "fontFace": "CaskaydiaCove NF",
            //"fontFace": "CodeNewRoman NF",
            //"fontFace": "SauceCodePro NF",
            //"fontFace": "UbuntuMono NF",
            //"fontFace": "Consolas",
            "fontSize": 13,
            "cursorShape": "filledBox"
        },
...

考虑到这一点,我可以通过以下 sed 调用来更改 fontFace 和 fontSize:

winhome=$(powershell.exe -c 'Write-Host -NoNewLine  $env:userprofile' | xargs -0 wslpath)
cd ${winhome}/AppData/Local/Packages/Microsoft.WindowsTerminal_8wekyb3d8bbwe/LocalState
sed -i '/"defaults"/,/fontFace/s/^\(.*fontFace": \).*/"Consolas",/' settings.json
sed -i '/"defaults"/,/fontSize/s/\([^/]*fontSize": \)[0-9]*/5/' settings.json

当然,如果您想硬编码到您的用户路径,那么前两行并不是绝对必要的。

这些 sed 脚本的其他一些注意事项:

  • “真正的”fontFace 行必须是第一个 未注释的行。该脚本将更改它遇到的第一个脚本,无论它是否被注释。 fontSize当然也一样。

  • 调整脚本以不需要添加逗号。