Jump to content

Fonts/zh-cn: Difference between revisions

From Official NixOS Wiki
ZhX589 (talk | contribs)
Created page with "尽管这些字体包看起来与普通包无异,但仅将它们添加到 `environment.systemPackages` 并不会让应用程序能够访问这些字体。要实现这一点,应将它们放入 NixOS 的 `[https://search.nixos.org/options?channel=unstable&show=fonts.packages&from=0&size=50&sort=relevance&type=packages&query=fonts.packages fonts.packages]` 选项列表中。"
Tags: Mobile edit Mobile web edit
ZhX589 (talk | contribs)
Created page with "=== 在 <code>fonts.fontconfig.defaultFonts.monospace</code> 中可以使用哪些字体名称? ==="
 
(28 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<languages/>
<languages/>
NixOS 处理字体就像处理系统中许多不同部分一样:除非明确标记为环境的一部分,否则它们不会出现在环境中。本指南涵盖字体的安装、配置和故障排除。  
NixOS 处理字体就像处理系统中许多不同部分一样:除非明确标记为环境的一部分,否则它们不会出现在环境中。本指南涵盖字体的安装、配置和故障排除。  


Line 23: Line 22:
];|name=/etc/nixos/configuration.nix|lang=nix}}{{Note|Be aware that sometimes font names and packages name differ and there is no universal convention in NixOS. </br>See: [https://discourse.nixos.org/t/guidelines-on-packaging-fonts/7683/2 Guidelines for font packaging]}}
];|name=/etc/nixos/configuration.nix|lang=nix}}{{Note|Be aware that sometimes font names and packages name differ and there is no universal convention in NixOS. </br>See: [https://discourse.nixos.org/t/guidelines-on-packaging-fonts/7683/2 Guidelines for font packaging]}}


=== Shorthands for fonts ===
=== 启用预置字体集合 ===
* <code>fonts.enableDefaultPackages</code>: when set to <code>true</code>, causes some "basic" fonts to be installed for reasonable Unicode coverage. Set to <code>true</code> if you are unsure about what languages you might end up reading.
* <code>fonts.enableDefaultPackages</code>:当设为 <code>true</code> 时,会安装一些“基础”字体以提供合理的 Unicode 覆盖范围。如果您不确定自己可能会阅读哪些语言,可将其设为 <code>true</code>
* <code>fonts.enableGhostscriptFonts</code>: affects the <code>ghostscript</code> package. Ghostscript packages some URW fonts for the standard PostScript typefaces. If <code>true</code>, these fonts will be visible to GUI applications. You could set it to <code>true</code> if you want these fonts, but <code>gyre-fonts</code> (part of <code>fonts.enableDefaultPackages</code>) might be higher-quality depending on your judgement.
* <code>fonts.enableGhostscriptFonts</code>:影响 <code>ghostscript</code> 包。Ghostscript 为标准的 PostScript 字型打包了一些 URW 字体。若设为 <code>true</code>,这些字体将对 GUI 应用程序可见。如果您需要这些字体,可以设为 <code>true</code>,但 <code>gyre-fonts</code>(属于 <code>fonts.enableDefaultPackages</code> 的一部分)根据您的判断可能质量更高。


=== Using fonts from TexLive ===
=== 使用来自 TexLive 的字体 ===
You can make use of all TeX/LaTeX fonts from CTAN and [[TexLive]] by passing
您可以将 TexLive 包中的 `fonts` 属性传递给 `fonts.packages`,从而使用来自 CTAN [[TexLive]] 的所有 TeX/LaTeX 字体:
the <code>fonts</code> attribute of your TexLive package to <code>fonts.package</code>:


{{File|3={ pkgs, ... }:
{{File|3={ pkgs, ... }:
Line 49: Line 47:
}|name=/etc/nixos/configuration.nix|lang=nix}}
}|name=/etc/nixos/configuration.nix|lang=nix}}


=== Installing <code>nerdfonts</code> ===
=== 安装 <code> Nerd Fonts </code> ===


Individual Nerd Fonts can be installed like so:
单个Nerd Fonts可以像这样安装:


{{File|3=fonts.packages = with pkgs; [
{{File|3=fonts.packages = with pkgs; [
Line 59: Line 57:




 
可用的 Nerd Fonts 子包可以通过在 [[Searching packages|NixOS Package Search]] 中搜索 {{nixos:package|nerd-fonts.*}} 来列出,或者运行以下命令:<syntaxhighlight lang="console">
The available Nerd Font subpackages can be listed by searching for {{nixos:package|nerd-fonts.*}} on the [[Searching packages|NixOS Package Search]] or by running the following command: <syntaxhighlight lang="console">
$ nix-instantiate --eval --expr "with (import <nixpkgs> {}); lib.attrNames (lib.filterAttrs (_: lib.isDerivation) nerd-fonts)"
$ nix-instantiate --eval --expr "with (import <nixpkgs> {}); lib.attrNames (lib.filterAttrs (_: lib.isDerivation) nerd-fonts)"
</syntaxhighlight>
</syntaxhighlight>


==== Installing all <code>nerdfonts</code> ====
<span id="Installing_all_nerdfonts"></span>
==== 安装所有 <code>Nerd Fonts</code> ====


Installing all fonts from the [https://www.nerdfonts.com/ Nerd Fonts repository] is as simple as adding all of the individual packages to the NixOS configuration. The following line will do exactly that, by searching for all derivations under the <code>nerd-font</code> attribute:{{file|||<nowiki>
要安装来自 Nerd Fonts 仓库 的所有字体,只需将所有独立的包添加到 NixOS 配置中即可。以下代码行通过搜索 `nerd-fonts` 属性下的所有派生,精确实现这一目的:{{file|||<nowiki>
{  
{  
   fonts.packages = builtins.filter lib.attrsets.isDerivation (builtins.attrValues pkgs.nerd-fonts);
   fonts.packages = builtins.filter lib.attrsets.isDerivation (builtins.attrValues pkgs.nerd-fonts);
}
}


# or if you already have fonts.packages set
# 或者如果您已经设置了 fonts.packages 集合


{
{
Line 81: Line 79:
</nowiki>|name=/etc/nixos/configuration.nix|lang=nix}}
</nowiki>|name=/etc/nixos/configuration.nix|lang=nix}}


=== Patching nerdfonts into fonts ===
=== nerdfonts 补丁应用到字体中 ===
Not all fonts have Nerd Fonts variants, thankfully you can easily patch them in yourself.
并非所有字体都有 Nerd Fonts 变体,但幸运的是,您可以轻松地自行打补丁。
{{File|3=(pkgs.scientifica.overrideAttrs (o: {
{{File|3=(pkgs.scientifica.overrideAttrs (o: {
   nativeBuildInputs = [ pkgs.nerd-font-patcher ];
   nativeBuildInputs = [ pkgs.nerd-font-patcher ];
Line 94: Line 92:
}))|name=/etc/nixos/configuration.nix|lang=nix}}
}))|name=/etc/nixos/configuration.nix|lang=nix}}


=== Let Fontconfig know the fonts within your Nix profile ===
=== Fontconfig 识别 Nix 配置文件中的字体 ===
Nix inserts its user profile path into <code>$XDG_DATA_DIRS</code>, which Fontconfig by default doesn't look in. This cause graphical applications like KDE Plasma not able to recognize the fonts installed via <code>nix-env</code> or <code>nix profile</code>.
Nix 会将其用户配置文件路径插入到 <code>$XDG_DATA_DIRS</code> 中,而 Fontconfig 默认并不在此路径中查找。这会导致 KDE Plasma 等图形应用程序无法识别通过 <code>nix-env</code> <code>nix profile</code> 安装的字体。


To solve this, add the file <code>100-nix.conf</code> to your Fontconfig user configuration directory (usually <code>$XDG_CONFIG_HOME/fontconfig/conf.d</code>):
要解决此问题,请将 <code>100-nix.conf</code> 文件添加到 Fontconfig 用户配置目录中(通常为 <code>$XDG_CONFIG_HOME/fontconfig/conf.d</code>):
<syntaxhighlight lang="xml">
<syntaxhighlight lang="xml">
<?xml version="1.0"?>
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">
<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">
<fontconfig>
<fontconfig>
   <!-- NIX_PROFILE is the path to your Nix profile. See Nix Reference Manual for details. -->
   <!-- NIX_PROFILE 是您的 Nix 配置文件的路径。详见 Nix 参考手册。 -->
   <dir>NIX_PROFILE/lib/X11/fonts</dir>
   <dir>NIX_PROFILE/lib/X11/fonts</dir>
   <dir>NIX_PROFILE/share/fonts</dir>
   <dir>NIX_PROFILE/share/fonts</dir>
</fontconfig>
</fontconfig>
</syntaxhighlight>
</syntaxhighlight>
and run <code>fc-cache</code>.
然后运行 <code>fc-cache</code>


Alternatively, [https://nix-community.github.io/home-manager/options.xhtml#opt-fonts.fontconfig.enable enable Fontconfig configuration] in your Home Manager configuration.
或者,在您的 Home Manager 配置 <code>opt-fonts.fontconfig.enable</code> 中启用 Fontconfig 配置。


=== Imperative installation of user fonts ===
=== 命令式安装用户字体 ===
This is useful for quick font experiments.
<span lang="en" dir="ltr" class="mw-content-ltr">This is useful for quick font experiments.</span>


''Example'': Install <code>SourceCodePro-Regular</code>.
''Example'': Install <code>SourceCodePro-Regular</code>.
Line 123: Line 121:




=== Install fonts in nix-shells ===
<span lang="en" dir="ltr" class="mw-content-ltr">=== Install fonts in nix-shells ===</span>


<code>fonts</code> is not available as set-valued option in <code>mkshell</code> (gives you an error because it tries to coerce an attribute set into a string). Instead, insert the following:<ref>https://programming.dev/post/32484220</ref>
<div lang="en" dir="ltr" class="mw-content-ltr">
<code>fonts</code> is not available as set-valued option in <code>mkshell</code> (gives you an error because it tries to coerce an attribute set into a string). Instead, insert the following:
</div><ref>https://programming.dev/post/32484220</ref>


<div lang="en" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
{pkgs ? import <nixpkgs> {} }:
{pkgs ? import <nixpkgs> {} }:
Line 149: Line 150:
</syntaxhighlight>
</syntaxhighlight>
Then <code>typst fonts</code> finds the installed fonts in the nix-shell.
Then <code>typst fonts</code> finds the installed fonts in the nix-shell.
</div>


== 配置字体 ==


== Configuring fonts ==
NixOS 的 [https://search.nixos.org/options?channel=unstable&from=0&size=50&sort=relevance&type=packages&query=fonts.fontconfig <code>fonts.fontconfig</code>] 配置项(点击查看完整列表!)用于处理 fontconfig 选项。部分选项已被 nix 很好地封装;此外始终可以使用 <code>localConf</code> 直接编写 XML 配置。


The nixos key [https://search.nixos.org/options?channel=unstable&from=0&size=50&sort=relevance&type=packages&query=fonts.fontconfig <code>fonts.fontconfig</code>] (click to see the full list!) handles the fontconfig options. Some options are nicely wrapped in nix; there's always <code>localConf</code> to go straight to the XML.
=== 为不同语言设置多种字体 ===
 
<div lang="en" dir="ltr" class="mw-content-ltr">
=== Set multiple fonts for different languages ===
If you want to use other languages alongside English, you may want to set appropriate fonts for each language in your whole OS. For example, a Persian speaker might want to use the
If you want to use other languages alongside English, you may want to set appropriate fonts for each language in your whole OS. For example, a Persian speaker might want to use the [https://rastikerdar.github.io/vazirmatn/ Vazirmatn] font for Persian texts, but [https://design.ubuntu.com/font/ Ubuntu] and Liberation Serif fonts for English texts. Just put these lines into your <code>configuration.nix</code>:
</div> [https://rastikerdar.github.io/vazirmatn/ Vazirmatn] <span lang="en" dir="ltr" class="mw-content-ltr">font for Persian texts, but</span> [https://design.ubuntu.com/font/ Ubuntu] <div lang="en" dir="ltr" class="mw-content-ltr">
and Liberation Serif fonts for English texts. Just put these lines into your <code>configuration.nix</code>:
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
{{File|3=#----=[ Fonts ]=----#
{{File|3=#----=[ Fonts ]=----#
fonts = {
fonts = {
Line 167: Line 173:
     vazir-fonts
     vazir-fonts
   ];
   ];
</div>


   fontconfig = {
   <div lang="en" dir="ltr" class="mw-content-ltr">
fontconfig = {
     defaultFonts = {
     defaultFonts = {
       serif = [  "Liberation Serif" "Vazirmatn" ];
       serif = [  "Liberation Serif" "Vazirmatn" ];
Line 176: Line 184:
   };
   };
};|name=/etc/nixos/configuration.nix|lang=nix}}
};|name=/etc/nixos/configuration.nix|lang=nix}}
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
NB:
NB:
* This actually just sets the font fallback order so that fontconfig tries using the English font first, then falls back to another font if the character set is not covered. You ''usually'' want to write the English font ''before'' the other-language font, because the other-language font might cover Latin characters too, preventing the English font from showing up.
* This actually just sets the font fallback order so that fontconfig tries using the English font first, then falls back to another font if the character set is not covered. You ''usually'' want to write the English font ''before'' the other-language font, because the other-language font might cover Latin characters too, preventing the English font from showing up.
* <code>defaultFonts</code> translates to <code>&lt;prefer&gt;</code> in the actual fontconfig file. See https://github.com/NixOS/nixpkgs/blob/nixos-23.11/nixos/modules/config/fonts/fontconfig.nix for how NixOS does it, and the links below for how fontconfig interpret it.
* <code>defaultFonts</code> translates to <code>&lt;prefer&gt;</code> in the actual fontconfig file. See https://github.com/NixOS/nixpkgs/blob/nixos-23.11/nixos/modules/config/fonts/fontconfig.nix for how NixOS does it, and the links below for how fontconfig interpret it.
* Vazirmatn is actually a "sans-serif" font; using it for <code>serif</code> is not a good visual match. You might need not one, but two (or if you count monospace, three!) font packages for a language.
* Vazirmatn is actually a "sans-serif" font; using it for <code>serif</code> is not a good visual match. You might need not one, but two (or if you count monospace, three!) font packages for a language.
</div>


=== Use custom font substitutions ===
=== 使用自定义字体替换 ===


Sometimes, documents may appear to have bad kerning or hard-to-read letter spacing, due to a bad substitution.
有时,由于不恰当的替换,文档可能会出现字距不佳或字间距难以阅读的问题。
For example, Okular may show in the ''Document Properties'' dialog that it has substituted DejaVu Sans Mono (a sans-serif font) in place of "NewCenturySchlbk". <code>fc-match NewCenturySchlbk</code> would display similiar info.
例如,Okular 可能在“文档属性”对话框中显示已将 DejaVu Sans Mono(一种无衬线字体)替换为 "NewCenturySchlbk"。运行 <code>fc-match NewCenturySchlbk</code> 会显示类似信息。


Adding this to your <code>/etc/nixos/configuration.nix</code> should prompt it to use the more similar (and nicer) serif ''Schola'' font instead:
将此添加到您的 <code>/etc/nixos/configuration.nix</code> 中,应能促使其改用更相似(且更美观)的衬线字体 ''Schola'' 作为替代:


{{File|3=fonts = {
{{File|3=fonts = {
Line 202: Line 213:
};|name=/etc/nixos/configuration.nix|lang=nix}}
};|name=/etc/nixos/configuration.nix|lang=nix}}


For more information and examples on the xml configuration language:
有关 XML 配置语言的更多信息和示例:


* https://www.mankier.com/5/fonts-conf
* https://www.mankier.com/5/fonts-conf
Line 208: Line 219:
* https://wiki.archlinux.org/index.php/Font_configuration/Examples
* https://wiki.archlinux.org/index.php/Font_configuration/Examples


For a list of suitable replacement fonts:
有关合适的替代字体列表:
* https://wiki.archlinux.org/title/Metric-compatible_fonts
* https://wiki.archlinux.org/title/Metric-compatible_fonts


== Troubleshooting ==
== 故障排除 ==


=== What font names can be used in <code>fonts.fontconfig.defaultFonts.monospace</code>? ===
=== <code>fonts.fontconfig.defaultFonts.monospace</code> 中可以使用哪些字体名称? ===


Those that fontconfig will understand. This can be queried from a font file using <code>fc-query</code>.
<span lang="en" dir="ltr" class="mw-content-ltr">Those that fontconfig will understand. This can be queried from a font file using <code>fc-query</code>.</span>


<syntaxhighlight lang="console">
<syntaxhighlight lang="console">
Line 222: Line 233:
</syntaxhighlight>
</syntaxhighlight>


<div lang="en" dir="ltr" class="mw-content-ltr">
Note that you may need to set <code>fonts.fontDir.enable = true;</code> for that X11/fonts directory to exist.
Note that you may need to set <code>fonts.fontDir.enable = true;</code> for that X11/fonts directory to exist.
</div>


=== Adding personal fonts to <code>~/.fonts</code> doesn't work ===
<span lang="en" dir="ltr" class="mw-content-ltr">=== Adding personal fonts to <code>~/.fonts</code> doesn't work ===</span>


The <code>~/.fonts</code> directory is being deprecated upstream<ref>https://lists.freedesktop.org/archives/fontconfig/2014-July/005269.html</ref>. It already doesn't work in NixOS.  
<div lang="en" dir="ltr" class="mw-content-ltr">
The <code>~/.fonts</code> directory is being deprecated upstream<ref>https://lists.freedesktop.org/archives/fontconfig/2014-July/005269.html</ref>. It already doesn't work in NixOS.
</div>


The new preferred location is in <code>$XDG_DATA_HOME/fonts</code>, which for most users will resolve to <code>~/.local/share/fonts</code><ref>https://lists.freedesktop.org/archives/fontconfig/2014-July/005270.html</ref>
<div lang="en" dir="ltr" class="mw-content-ltr">
The new preferred location is in <code>$XDG_DATA_HOME/fonts</code>, which for most users will resolve to <code>~/.local/share/fonts</code>
</div><ref>https://lists.freedesktop.org/archives/fontconfig/2014-July/005270.html</ref>


=== Flatpak applications can't find system fonts ===
<span lang="en" dir="ltr" class="mw-content-ltr">=== Flatpak applications can't find system fonts ===</span>


To expose available fonts under <code>/run/current-system/sw/share/X11/fonts</code>, enable <code>fontDir</code> in your NixOS configuration.
<span lang="en" dir="ltr" class="mw-content-ltr">To expose available fonts under <code>/run/current-system/sw/share/X11/fonts</code>, enable <code>fontDir</code> in your NixOS configuration.</span>


{{File|3=fonts.fontDir.enable = true;|name=/etc/nixos/configuration.nix|lang=nix}}
{{File|3=fonts.fontDir.enable = true;|name=/etc/nixos/configuration.nix|lang=nix}}


You will then need to link/copy this folder to one of the Flatpak-supported locations - see below.
<span lang="en" dir="ltr" class="mw-content-ltr">You will then need to link/copy this folder to one of the Flatpak-supported locations - see below.</span>


==== Solution 1: Copy fonts to <code>$HOME/.local/share/fonts</code> ====
<span lang="en" dir="ltr" class="mw-content-ltr">==== Solution 1: Copy fonts to <code>$HOME/.local/share/fonts</code> ====</span>
<div lang="en" dir="ltr" class="mw-content-ltr">
Create fonts directory <code>$HOME/.local/share/fonts</code> and copy system fonts with option <code>-L, --dereference</code>. You will need to repeat this step whenever the fonts change.<syntaxhighlight lang="console">
Create fonts directory <code>$HOME/.local/share/fonts</code> and copy system fonts with option <code>-L, --dereference</code>. You will need to repeat this step whenever the fonts change.<syntaxhighlight lang="console">
$ mkdir $HOME/.local/share/fonts && cp -L /run/current-system/sw/share/X11/fonts/* $HOME/.local/share/fonts/
$ mkdir $HOME/.local/share/fonts && cp -L /run/current-system/sw/share/X11/fonts/* $HOME/.local/share/fonts/
</syntaxhighlight>Note: There is no need to grant flatpak applications access to <code>$HOME/.local/share/fonts</code>.  
</syntaxhighlight>Note: There is no need to grant flatpak applications access to <code>$HOME/.local/share/fonts</code>.
</div>


Instead, if you do that, some applications (for example, steam) won't work.<blockquote>Internals: How it works?
<span lang="en" dir="ltr" class="mw-content-ltr">Instead, if you do that, some applications (for example, steam) won't work.<blockquote>Internals: How it works?</span>


Flatpak applications run in sandboxes. When you start a flatpak application, flatpak builds a rootfs for it with bubblewrap.
<span lang="en" dir="ltr" class="mw-content-ltr">Flatpak applications run in sandboxes. When you start a flatpak application, flatpak builds a rootfs for it with bubblewrap.</span>


With <code>findmnt --task {PID of flatpak app}</code> , you can explore the details of its rootfs.
<span lang="en" dir="ltr" class="mw-content-ltr">With <code>findmnt --task {PID of flatpak app}</code> , you can explore the details of its rootfs.</span>


<div lang="en" dir="ltr" class="mw-content-ltr">
By default, flatpak mounts <code>$HOME/.local/share/fonts</code> to <code>/run/host/user-fonts</code> in rootfs of an flatpak application.<syntaxhighlight lang="json">
By default, flatpak mounts <code>$HOME/.local/share/fonts</code> to <code>/run/host/user-fonts</code> in rootfs of an flatpak application.<syntaxhighlight lang="json">
{
{
Line 257: Line 277:
}
}
</syntaxhighlight>Then flatpak application can read fonts from that to display contents correctly.</blockquote>
</syntaxhighlight>Then flatpak application can read fonts from that to display contents correctly.</blockquote>
</div>


==== Solution 2: Symlink to system fonts at  <code>$HOME/.local/share/fonts</code> ====
<span lang="en" dir="ltr" class="mw-content-ltr">==== Solution 2: Symlink to system fonts at  <code>$HOME/.local/share/fonts</code> ====</span>
<blockquote>'''Note:''' this method doesn't work for some flatpak applications (for example, steam)!  
<span lang="en" dir="ltr" class="mw-content-ltr"><blockquote>'''Note:''' this method doesn't work for some flatpak applications (for example, steam)!</span>


Error: <syntaxhighlight lang="console">
Error: <syntaxhighlight lang="console">
Line 268: Line 289:
mkdir $HOME/.local/share/fonts && ln -s /run/current-system/sw/share/X11/fonts ~/.local/share/fonts/
mkdir $HOME/.local/share/fonts && ln -s /run/current-system/sw/share/X11/fonts ~/.local/share/fonts/
</syntaxhighlight>
</syntaxhighlight>
Now you have two options.
<span lang="en" dir="ltr" class="mw-content-ltr">Now you have two options.</span>


<div lang="en" dir="ltr" class="mw-content-ltr">
===== Option 1: Allow access to the fonts folder and <code>/nix/store</code> =====
===== Option 1: Allow access to the fonts folder and <code>/nix/store</code> =====
</div>
<div lang="en" dir="ltr" class="mw-content-ltr">
By using the Flatpak CLI or the Flatseal Flatpak make the following directory available to all Flatpaks <code>$HOME/.local/share/fonts</code> and <code>$HOME/.icons</code> the appropriate commands for this are:
By using the Flatpak CLI or the Flatseal Flatpak make the following directory available to all Flatpaks <code>$HOME/.local/share/fonts</code> and <code>$HOME/.icons</code> the appropriate commands for this are:
</div>


<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
Line 278: Line 303:
</syntaxhighlight>
</syntaxhighlight>


And, because <code>~/.local/share/fonts</code> is linked to <code>/run/current-system/sw/share/X11/fonts</code>, which in turn is linked to content in <code>/nix/store</code>. You need to grant flatpak applications access to the <code>/nix/store</code> directory, so that they can load fonts correctly. You may need to reboot for this to fully take effect.
<span lang="en" dir="ltr" class="mw-content-ltr">And, because <code>~/.local/share/fonts</code> is linked to <code>/run/current-system/sw/share/X11/fonts</code>, which in turn is linked to content in <code>/nix/store</code>. You need to grant flatpak applications access to the <code>/nix/store</code> directory, so that they can load fonts correctly. You may need to reboot for this to fully take effect.</span>


<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
Line 285: Line 310:
</syntaxhighlight>
</syntaxhighlight>


===== Option 2: Allow access to the WHOLE filesystem =====
<span lang="en" dir="ltr" class="mw-content-ltr">===== Option 2: Allow access to the WHOLE filesystem =====</span>
<div lang="en" dir="ltr" class="mw-content-ltr">
Allow them access the WHOLE filesystem of yours: <code>All system files</code> in Flatseal or equivalently <code>filesystem=host</code> available to your application, the command for this is:
Allow them access the WHOLE filesystem of yours: <code>All system files</code> in Flatseal or equivalently <code>filesystem=host</code> available to your application, the command for this is:
</div>


<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
Line 292: Line 319:
</syntaxhighlight>
</syntaxhighlight>


It is important to keep in mind that some flatpak apps may refuse to launch if given certain permissions, such as the Steam flatpak.  
<div lang="en" dir="ltr" class="mw-content-ltr">
It is important to keep in mind that some flatpak apps may refuse to launch if given certain permissions, such as the Steam flatpak.
</div>


==== Solution 3: Configure bindfs for fonts/cursors/icons support ====
<span lang="en" dir="ltr" class="mw-content-ltr">==== Solution 3: Configure bindfs for fonts/cursors/icons support ====</span>
<div lang="en" dir="ltr" class="mw-content-ltr">
Alternatively, you can expose relevant packages directly under <code>/usr/share/...</code> paths. This will also enable Flatpak to use a custom cursor theme if you have one. This solution doesn't require <code>fonts.fontDir.enable</code> to be enabled.<syntaxhighlight lang="nix">
Alternatively, you can expose relevant packages directly under <code>/usr/share/...</code> paths. This will also enable Flatpak to use a custom cursor theme if you have one. This solution doesn't require <code>fonts.fontDir.enable</code> to be enabled.<syntaxhighlight lang="nix">
   system.fsPackages = [ pkgs.bindfs ];
   system.fsPackages = [ pkgs.bindfs ];
Line 343: Line 373:
     "/usr/share/fonts" = mkRoSymBind (x11Fonts + "/share/fonts");
     "/usr/share/fonts" = mkRoSymBind (x11Fonts + "/share/fonts");
   };
   };
</div>


   fonts.packages = with pkgs; [
   <div lang="en" dir="ltr" class="mw-content-ltr">
fonts.packages = with pkgs; [
     noto-fonts
     noto-fonts
     noto-fonts-color-emoji
     noto-fonts-color-emoji
Line 350: Line 382:
   ];
   ];
</syntaxhighlight>Note that font cache inside flatpak container may not be recreated after changes to fonts in <code>/usr/share/fonts</code>, because font cache seem to be relying on file timestamps that are missing in <code>/nix/store</code>.
</syntaxhighlight>Note that font cache inside flatpak container may not be recreated after changes to fonts in <code>/usr/share/fonts</code>, because font cache seem to be relying on file timestamps that are missing in <code>/nix/store</code>.
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
You can make sure that font directory is bind-mounted properly inside flatpak container by running <code>flatpak enter <instance> findmnt  | grep /run/host/fonts</code>, or by running <code>flatpak enter <instance> ls -alh /run/host/fonts</code> and compare it to <code>ls -alh /usr/share/fonts</code>.
You can make sure that font directory is bind-mounted properly inside flatpak container by running <code>flatpak enter <instance> findmnt  | grep /run/host/fonts</code>, or by running <code>flatpak enter <instance> ls -alh /run/host/fonts</code> and compare it to <code>ls -alh /usr/share/fonts</code>.
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
If everything is mounted properly, but you still do not see fonts in flatpak app - force font cache recreation inside flatpak container: <code>flatpak run --command=fc-cache <application id> -f -v</code>
If everything is mounted properly, but you still do not see fonts in flatpak app - force font cache recreation inside flatpak container: <code>flatpak run --command=fc-cache <application id> -f -v</code>
</div>


=== Noto Color Emoji doesn't render on Firefox ===
<span lang="en" dir="ltr" class="mw-content-ltr">=== Noto Color Emoji doesn't render on Firefox ===</span>


<div lang="en" dir="ltr" class="mw-content-ltr">
Enable <code>useEmbeddedBitmaps</code> in your NixOS configuration.
Enable <code>useEmbeddedBitmaps</code> in your NixOS configuration.
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
fonts.fontconfig.useEmbeddedBitmaps = true;
fonts.fontconfig.useEmbeddedBitmaps = true;
</syntaxhighlight>
</syntaxhighlight>
 
</div>
<hr />
<hr />
[[Category:Configuration]]
[[Category:Configuration]]
[[Category:Desktop]]
[[Category:Desktop]]
[[Category:Fonts]]
[[Category:Fonts]]

Latest revision as of 13:02, 9 July 2026

NixOS 处理字体就像处理系统中许多不同部分一样:除非明确标记为环境的一部分,否则它们不会出现在环境中。本指南涵盖字体的安装、配置和故障排除。

在 NixOS 上安装字体

NixOS 有许多可用的字体包,你可以轻松地在这里搜索并使用他们: NixOS packages site.

尽管这些字体包看起来与普通包无异,但仅将它们添加到 `environment.systemPackages` 并不会让应用程序能够访问这些字体。要实现这一点,应将它们放入 NixOS 的 `fonts.packages` 选项列表中。

For example:

❄︎ /etc/nixos/configuration.nix
fonts.packages = with pkgs; [
  noto-fonts
  noto-fonts-cjk-sans
  noto-fonts-color-emoji
  liberation_ttf
  fira-code
  fira-code-symbols
  mplus-outline-fonts.githubRelease
  dina-font
  proggyfonts
];
Note: Be aware that sometimes font names and packages name differ and there is no universal convention in NixOS.
See: Guidelines for font packaging

启用预置字体集合

  • fonts.enableDefaultPackages:当设为 true 时,会安装一些“基础”字体以提供合理的 Unicode 覆盖范围。如果您不确定自己可能会阅读哪些语言,可将其设为 true
  • fonts.enableGhostscriptFonts:影响 ghostscript 包。Ghostscript 为标准的 PostScript 字型打包了一些 URW 字体。若设为 true,这些字体将对 GUI 应用程序可见。如果您需要这些字体,可以设为 true,但 gyre-fonts(属于 fonts.enableDefaultPackages 的一部分)根据您的判断可能质量更高。

使用来自 TexLive 的字体

您可以将 TexLive 包中的 `fonts` 属性传递给 `fonts.packages`,从而使用来自 CTAN 和 TexLive 的所有 TeX/LaTeX 字体:

❄︎ /etc/nixos/configuration.nix
{ pkgs, ... }:
let
  mytex =
    pkgs.texliveConTeXt.withPackages
      (ps: with ps; [ 
        fandol
        libertinus-fonts
      ]);
in {
  fonts.packages = builtins.attrValues {
    inherit (pkgs)
      dejavu_fonts 
      noto-fonts-cjk-serif
      noto-fonts-cjk-sans
      julia-mono;
  } ++ [ mytex.fonts ];
}

安装 Nerd Fonts

单个Nerd Fonts可以像这样安装:

❄︎ /etc/nixos/configuration.nix
fonts.packages = with pkgs; [
  nerd-fonts.fira-code
  nerd-fonts.droid-sans-mono
];


可用的 Nerd Fonts 子包可以通过在 NixOS Package Search 中搜索 nerd-fonts.* 来列出,或者运行以下命令:

$ nix-instantiate --eval --expr "with (import <nixpkgs> {}); lib.attrNames (lib.filterAttrs (_: lib.isDerivation) nerd-fonts)"

安装所有 Nerd Fonts

要安装来自 Nerd Fonts 仓库 的所有字体,只需将所有独立的包添加到 NixOS 配置中即可。以下代码行通过搜索 `nerd-fonts` 属性下的所有派生,精确实现这一目的:

❄︎ /etc/nixos/configuration.nix
{ 
  fonts.packages = builtins.filter lib.attrsets.isDerivation (builtins.attrValues pkgs.nerd-fonts);
}

# 或者如果您已经设置了 fonts.packages 集合

{
  fonts.packages = [
     # ... some fonts
  ] 
  ++ builtins.filter lib.attrsets.isDerivation (builtins.attrValues pkgs.nerd-fonts);
}

将 nerdfonts 补丁应用到字体中

并非所有字体都有 Nerd Fonts 变体,但幸运的是,您可以轻松地自行打补丁。

❄︎ /etc/nixos/configuration.nix
(pkgs.scientifica.overrideAttrs (o: {
  nativeBuildInputs = [ pkgs.nerd-font-patcher ];
  postInstall = ''
    mkdir -p $out/share/fonts/truetype/{scientifica,scientifica-nerd}
    mv $out/share/fonts/truetype/*.ttf $out/share/fonts/truetype/scientifica/
    for f in $out/share/fonts/truetype/scientifica/*.ttf; do
      nerd-font-patcher --complete --outputdir $out/share/fonts/truetype/scientifica-nerd/ $f
    done
  '';
}))

让 Fontconfig 识别 Nix 配置文件中的字体

Nix 会将其用户配置文件路径插入到 $XDG_DATA_DIRS 中,而 Fontconfig 默认并不在此路径中查找。这会导致 KDE Plasma 等图形应用程序无法识别通过 nix-envnix profile 安装的字体。

要解决此问题,请将 100-nix.conf 文件添加到 Fontconfig 用户配置目录中(通常为 $XDG_CONFIG_HOME/fontconfig/conf.d):

<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">
<fontconfig>
  <!-- NIX_PROFILE 是您的 Nix 配置文件的路径。详见 Nix 参考手册。 -->
  <dir>NIX_PROFILE/lib/X11/fonts</dir>
  <dir>NIX_PROFILE/share/fonts</dir>
</fontconfig>

然后运行 fc-cache

或者,在您的 Home Manager 配置 opt-fonts.fontconfig.enable 中启用 Fontconfig 配置。

命令式安装用户字体

This is useful for quick font experiments.

Example: Install SourceCodePro-Regular.

font=$(nix-build --no-out-link '<nixpkgs>' -A source-code-pro)/share/fonts/opentype/SourceCodePro-Regular.otf
cp $font ~/.local/share/fonts
fc-cache
# Verify that the font has been installed
fc-list -v | grep -i source


=== Install fonts in nix-shells ===

fonts is not available as set-valued option in mkshell (gives you an error because it tries to coerce an attribute set into a string). Instead, insert the following:

[1]

{pkgs ? import <nixpkgs> {} }:
let
  fontsConf = pkgs.makeFontsConf {
    fontDirectories = [
      # your needed fonts here, e.g.:
      pkgs.font-awesome
      pkgs.atkinson-hyperlegible-next
    ];
  };
in
  pkgs.mkShell {
    packages = with pkgs; [
      # your font-dependent packages, e.g.:
      typst
    ];
    shellHook = ''
      export FONTCONFIG_FILE="${fontsConf}"
    '';
  }

Then typst fonts finds the installed fonts in the nix-shell.

配置字体

NixOS 的 fonts.fontconfig 配置项(点击查看完整列表!)用于处理 fontconfig 选项。部分选项已被 nix 很好地封装;此外始终可以使用 localConf 直接编写 XML 配置。

为不同语言设置多种字体

If you want to use other languages alongside English, you may want to set appropriate fonts for each language in your whole OS. For example, a Persian speaker might want to use the

Vazirmatn font for Persian texts, but Ubuntu

and Liberation Serif fonts for English texts. Just put these lines into your configuration.nix:

❄︎ /etc/nixos/configuration.nix
#----=[ Fonts ]=----#
fonts = {
  enableDefaultPackages = true;
  packages = with pkgs; [ 
    ubuntu-classic
    liberation_ttf
    # Persian Font
    vazir-fonts
  ];
</div>

  <div lang="en" dir="ltr" class="mw-content-ltr">
fontconfig = {
    defaultFonts = {
      serif = [  "Liberation Serif" "Vazirmatn" ];
      sansSerif = [ "Ubuntu" "Vazirmatn" ];
      monospace = [ "Ubuntu Mono" ];
    };
  };
};

NB:

  • This actually just sets the font fallback order so that fontconfig tries using the English font first, then falls back to another font if the character set is not covered. You usually want to write the English font before the other-language font, because the other-language font might cover Latin characters too, preventing the English font from showing up.
  • defaultFonts translates to <prefer> in the actual fontconfig file. See https://github.com/NixOS/nixpkgs/blob/nixos-23.11/nixos/modules/config/fonts/fontconfig.nix for how NixOS does it, and the links below for how fontconfig interpret it.
  • Vazirmatn is actually a "sans-serif" font; using it for serif is not a good visual match. You might need not one, but two (or if you count monospace, three!) font packages for a language.

使用自定义字体替换

有时,由于不恰当的替换,文档可能会出现字距不佳或字间距难以阅读的问题。 例如,Okular 可能在“文档属性”对话框中显示已将 DejaVu Sans Mono(一种无衬线字体)替换为 "NewCenturySchlbk"。运行 fc-match NewCenturySchlbk 会显示类似信息。

将此添加到您的 /etc/nixos/configuration.nix 中,应能促使其改用更相似(且更美观)的衬线字体 Schola 作为替代:

❄︎ /etc/nixos/configuration.nix
fonts = {
  packages = with pkgs; [ gyre-fonts ];
  fontconfig = {
    localConf = ''
      <match target="pattern">
        <test qual="any" name="family"><string>NewCenturySchlbk</string></test>
        <edit name="family" mode="assign" binding="same"><string>TeX Gyre Schola</string></edit>
      </match>
    '';
  };
};

有关 XML 配置语言的更多信息和示例:

有关合适的替代字体列表:

故障排除

fonts.fontconfig.defaultFonts.monospace 中可以使用哪些字体名称?

Those that fontconfig will understand. This can be queried from a font file using fc-query.

$ cd /nix/var/nix/profiles/system/sw/share/X11/fonts
$ fc-query DejaVuSans.ttf | grep '^\s\+family:' | cut -d'"' -f2

Note that you may need to set fonts.fontDir.enable = true; for that X11/fonts directory to exist.

=== Adding personal fonts to ~/.fonts doesn't work ===

The ~/.fonts directory is being deprecated upstream[2]. It already doesn't work in NixOS.

The new preferred location is in $XDG_DATA_HOME/fonts, which for most users will resolve to ~/.local/share/fonts

[3]

=== Flatpak applications can't find system fonts ===

To expose available fonts under /run/current-system/sw/share/X11/fonts, enable fontDir in your NixOS configuration.

❄︎ /etc/nixos/configuration.nix
fonts.fontDir.enable = true;

You will then need to link/copy this folder to one of the Flatpak-supported locations - see below.

==== Solution 1: Copy fonts to $HOME/.local/share/fonts ====

Create fonts directory $HOME/.local/share/fonts and copy system fonts with option -L, --dereference. You will need to repeat this step whenever the fonts change.
$ mkdir $HOME/.local/share/fonts && cp -L /run/current-system/sw/share/X11/fonts/* $HOME/.local/share/fonts/
Note: There is no need to grant flatpak applications access to $HOME/.local/share/fonts.
Instead, if you do that, some applications (for example, steam) won't work.

Internals: How it works?

Flatpak applications run in sandboxes. When you start a flatpak application, flatpak builds a rootfs for it with bubblewrap.

With findmnt --task {PID of flatpak app} , you can explore the details of its rootfs.

By default, flatpak mounts $HOME/.local/share/fonts to /run/host/user-fonts in rootfs of an flatpak application.
{
  "target": "/run/host/user-fonts",
  "source": "/dev/disk/by-uuid/b2e1e6b5-738b-410b-b736-6d5c3dbbe31f[/home/username/.local/share/fonts]",
  "fstype": "ext4",
  "options": "ro,nosuid,nodev,relatime"
}
Then flatpak application can read fonts from that to display contents correctly.

==== Solution 2: Symlink to system fonts at $HOME/.local/share/fonts ====

Note: this method doesn't work for some flatpak applications (for example, steam)! Error:

$ flatpak run com.valvesoftware.Steam
bwrap: Can't make symlink at /home/username/.local/share/fonts: File exists
Create a symlink in XDG_DATA_HOME/fonts pointing to /run/current-system/sw/share/X11/fonts, e. g.
mkdir $HOME/.local/share/fonts && ln -s /run/current-system/sw/share/X11/fonts ~/.local/share/fonts/

Now you have two options.

Option 1: Allow access to the fonts folder and /nix/store

By using the Flatpak CLI or the Flatseal Flatpak make the following directory available to all Flatpaks $HOME/.local/share/fonts and $HOME/.icons the appropriate commands for this are:

flatpak --user override --filesystem=$HOME/.local/share/fonts:ro
flatpak --user override --filesystem=$HOME/.icons:ro

And, because ~/.local/share/fonts is linked to /run/current-system/sw/share/X11/fonts, which in turn is linked to content in /nix/store. You need to grant flatpak applications access to the /nix/store directory, so that they can load fonts correctly. You may need to reboot for this to fully take effect.

flatpak --user override --filesystem=/nix/store:ro
flatpak --user override --filesystem=/run/current-system/sw/share/X11/fonts:ro

===== Option 2: Allow access to the WHOLE filesystem =====

Allow them access the WHOLE filesystem of yours: All system files in Flatseal or equivalently filesystem=host available to your application, the command for this is:

flatpak --user override --filesystem=host

It is important to keep in mind that some flatpak apps may refuse to launch if given certain permissions, such as the Steam flatpak.

==== Solution 3: Configure bindfs for fonts/cursors/icons support ====

Alternatively, you can expose relevant packages directly under /usr/share/... paths. This will also enable Flatpak to use a custom cursor theme if you have one. This solution doesn't require fonts.fontDir.enable to be enabled.
  system.fsPackages = [ pkgs.bindfs ];
  fileSystems = let
    mkRoSymBind = path: {
      device = path;
      fsType = "fuse.bindfs";
      options = [ "ro" "resolve-symlinks" "x-gvfs-hide" ];
    };
    fontsPkgs = config.fonts.packages ++ (with pkgs; [
        # Add your cursor themes and icon packages here
        bibata-cursors
        gnome-themes-extra
        # etc.
      ]);
    x11Fonts = pkgs.runCommand "X11-fonts"
      {
        preferLocalBuild = true;
        nativeBuildInputs = with pkgs; [
          gzip
          mkfontdir
        ];
      }
      (''
        mkdir -p "$out/share/fonts"
        font_regexp='.*\.\(ttf\|ttc\|otb\|otf\|pcf\|pfa\|pfb\|bdf\)\(\.gz\)?'
      ''
      + (builtins.concatStringsSep "\n" (builtins.map (pkg: ''
          find ${toString pkg} -regex "$font_regexp" \
            -exec ln -sf -t "$out/share/fonts" '{}' \;
        '') fontsPkgs
        ))
      + ''
        cd "$out/share/fonts"
        mkfontscale
        mkfontdir
        cat $(find ${pkgs.font-alias}/ -name fonts.alias) >fonts.alias
      '');
    aggregatedIcons = pkgs.buildEnv {
      name = "system-icons";
      paths = fontsPkgs;
      pathsToLink = [
        "/share/icons"
      ];
    };
  in {
    "/usr/share/icons" = mkRoSymBind (aggregatedIcons + "/share/icons");
    "/usr/share/fonts" = mkRoSymBind (x11Fonts + "/share/fonts");
  };
</div>

  <div lang="en" dir="ltr" class="mw-content-ltr">
fonts.packages = with pkgs; [
    noto-fonts
    noto-fonts-color-emoji
    noto-fonts-cjk-sans
  ];
Note that font cache inside flatpak container may not be recreated after changes to fonts in /usr/share/fonts, because font cache seem to be relying on file timestamps that are missing in /nix/store.

You can make sure that font directory is bind-mounted properly inside flatpak container by running flatpak enter <instance> findmnt | grep /run/host/fonts, or by running flatpak enter <instance> ls -alh /run/host/fonts and compare it to ls -alh /usr/share/fonts.

If everything is mounted properly, but you still do not see fonts in flatpak app - force font cache recreation inside flatpak container: flatpak run --command=fc-cache <application id> -f -v

=== Noto Color Emoji doesn't render on Firefox ===

Enable useEmbeddedBitmaps in your NixOS configuration.

fonts.fontconfig.useEmbeddedBitmaps = true;