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
FuzzyBot (talk | contribs)
Updating to match new version of source page
Tags: Mobile edit Mobile web edit
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 ===
<span lang="en" dir="ltr" class="mw-content-ltr">=== Shorthands for fonts ===</span>
<div lang="en" dir="ltr" class="mw-content-ltr">
* <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>: 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.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>: 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.
</div>


=== Using fonts from TexLive ===
<span lang="en" dir="ltr" class="mw-content-ltr">=== Using fonts from TexLive ===</span>
<div lang="en" dir="ltr" class="mw-content-ltr">
You can make use of all TeX/LaTeX fonts from CTAN and [[TexLive]] by passing
You can make use of all TeX/LaTeX fonts from CTAN and [[TexLive]] by passing
the <code>fonts</code> attribute of your TexLive package to <code>fonts.package</code>:
the <code>fonts</code> attribute of your TexLive package to <code>fonts.package</code>:
</div>


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


=== Installing <code>nerdfonts</code> ===
<span lang="en" dir="ltr" class="mw-content-ltr">=== Installing <code>nerdfonts</code> ===</span>


<div lang="en" dir="ltr" class="mw-content-ltr">
Individual Nerd Fonts can be installed like so:
Individual Nerd Fonts can be installed like so:
</div>


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




 
<div lang="en" dir="ltr" class="mw-content-ltr">
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">
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>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
==== Installing all <code>nerdfonts</code> ====
==== Installing all <code>nerdfonts</code> ====
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
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>
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>
{  
{  
   fonts.packages = builtins.filter lib.attrsets.isDerivation (builtins.attrValues pkgs.nerd-fonts);
   fonts.packages = builtins.filter lib.attrsets.isDerivation (builtins.attrValues pkgs.nerd-fonts);
}
}
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
# or if you already have fonts.packages set
# or if you already have fonts.packages set
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
{
{
   fonts.packages = [
   fonts.packages = [
Line 80: Line 93:
}
}
</nowiki>|name=/etc/nixos/configuration.nix|lang=nix}}
</nowiki>|name=/etc/nixos/configuration.nix|lang=nix}}
</div>


=== Patching nerdfonts into fonts ===
<span lang="en" dir="ltr" class="mw-content-ltr">=== Patching nerdfonts into fonts ===</span>
<div lang="en" dir="ltr" class="mw-content-ltr">
Not all fonts have Nerd Fonts variants, thankfully you can easily patch them in yourself.
Not all fonts have Nerd Fonts variants, thankfully you can easily patch them in yourself.
{{File|3=(pkgs.scientifica.overrideAttrs (o: {
{{File|3=(pkgs.scientifica.overrideAttrs (o: {
Line 93: Line 108:
   '';
   '';
}))|name=/etc/nixos/configuration.nix|lang=nix}}
}))|name=/etc/nixos/configuration.nix|lang=nix}}
</div>


=== Let Fontconfig know the fonts within your Nix profile ===
<span lang="en" dir="ltr" class="mw-content-ltr">=== Let Fontconfig know the fonts within your Nix profile ===</span>
<div lang="en" dir="ltr" class="mw-content-ltr">
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 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>.
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
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>):
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>):
<syntaxhighlight lang="xml">
<syntaxhighlight lang="xml">
Line 108: Line 127:
</syntaxhighlight>
</syntaxhighlight>
and run <code>fc-cache</code>.
and run <code>fc-cache</code>.
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Alternatively, [https://nix-community.github.io/home-manager/options.xhtml#opt-fonts.fontconfig.enable enable Fontconfig configuration] in your Home Manager configuration.
Alternatively, [https://nix-community.github.io/home-manager/options.xhtml#opt-fonts.fontconfig.enable enable Fontconfig configuration] in your Home Manager configuration.
</div>


=== Imperative installation of user fonts ===
<span lang="en" dir="ltr" class="mw-content-ltr">=== Imperative installation of user fonts ===</span>
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 145:




=== 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 174:
</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>


<span lang="en" dir="ltr" class="mw-content-ltr">== Configuring fonts ==</span>


== Configuring fonts ==
<div lang="en" dir="ltr" class="mw-content-ltr">
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>


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.
<span lang="en" dir="ltr" class="mw-content-ltr">=== Set multiple fonts for different languages ===</span>
 
<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 199:
     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 210:
   };
   };
};|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 ===
<span lang="en" dir="ltr" class="mw-content-ltr">=== Use custom font substitutions ===</span>


<div lang="en" dir="ltr" class="mw-content-ltr">
Sometimes, documents may appear to have bad kerning or hard-to-read letter spacing, due to a bad substitution.
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.
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.
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Adding this to your <code>/etc/nixos/configuration.nix</code> should prompt it to use the more similar (and nicer) serif ''Schola'' font instead:
Adding this to your <code>/etc/nixos/configuration.nix</code> should prompt it to use the more similar (and nicer) serif ''Schola'' font instead:
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
{{File|3=fonts = {
{{File|3=fonts = {
   packages = with pkgs; [ gyre-fonts ];
   packages = with pkgs; [ gyre-fonts ];
Line 201: Line 243:
   };
   };
};|name=/etc/nixos/configuration.nix|lang=nix}}
};|name=/etc/nixos/configuration.nix|lang=nix}}
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
For more information and examples on the xml configuration language:
For more information and examples on the xml configuration language:
</div>


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


<div lang="en" dir="ltr" class="mw-content-ltr">
For a list of suitable replacement fonts:
For a list of suitable replacement fonts:
</div>
* https://wiki.archlinux.org/title/Metric-compatible_fonts
* https://wiki.archlinux.org/title/Metric-compatible_fonts


== Troubleshooting ==
<span lang="en" dir="ltr" class="mw-content-ltr">== Troubleshooting ==</span>


=== What font names can be used in <code>fonts.fontconfig.defaultFonts.monospace</code>? ===
<span lang="en" dir="ltr" class="mw-content-ltr">=== What font names can be used in <code>fonts.fontconfig.defaultFonts.monospace</code>? ===</span>


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 269:
</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 313:
}
}
</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 325:
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 339:
</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 346:
</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 355:
</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 409:
     "/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 418:
   ];
   ];
</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]]

Revision as of 12:48, 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

=== Shorthands for fonts ===

  • fonts.enableDefaultPackages: when set to true, causes some "basic" fonts to be installed for reasonable Unicode coverage. Set to true if you are unsure about what languages you might end up reading.
  • fonts.enableGhostscriptFonts: affects the ghostscript package. Ghostscript packages some URW fonts for the standard PostScript typefaces. If true, these fonts will be visible to GUI applications. You could set it to true if you want these fonts, but gyre-fonts (part of fonts.enableDefaultPackages) might be higher-quality depending on your judgement.

=== Using fonts from TexLive ===

You can make use of all TeX/LaTeX fonts from CTAN and TexLive by passing the fonts attribute of your TexLive package to fonts.package:

❄︎ /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 ];
}

=== Installing nerdfonts ===

Individual Nerd Fonts can be installed like so:

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


The available Nerd Font subpackages can be listed by searching for nerd-fonts.* on the NixOS Package Search or by running the following command:
$ nix-instantiate --eval --expr "with (import <nixpkgs> {}); lib.attrNames (lib.filterAttrs (_: lib.isDerivation) nerd-fonts)"

Installing all nerdfonts

Installing all fonts from the 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 nerd-font attribute:
❄︎ /etc/nixos/configuration.nix
{ 
  fonts.packages = builtins.filter lib.attrsets.isDerivation (builtins.attrValues pkgs.nerd-fonts);
}
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
# or if you already have fonts.packages set
&lt;/div&gt;

&lt;div lang="en" dir="ltr" class="mw-content-ltr"&gt;
{
  fonts.packages = [
     # ... some fonts
  ] 
  ++ builtins.filter lib.attrsets.isDerivation (builtins.attrValues pkgs.nerd-fonts);
}

=== Patching nerdfonts into fonts ===

Not all fonts have Nerd Fonts variants, thankfully you can easily patch them in yourself.

❄︎ /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
  '';
}))

=== Let Fontconfig know the fonts within your Nix profile ===

Nix inserts its user profile path into $XDG_DATA_DIRS, which Fontconfig by default doesn't look in. This cause graphical applications like KDE Plasma not able to recognize the fonts installed via nix-env or nix profile.

To solve this, add the file 100-nix.conf to your Fontconfig user configuration directory (usually $XDG_CONFIG_HOME/fontconfig/conf.d):

<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">
<fontconfig>
  <!-- NIX_PROFILE is the path to your Nix profile. See Nix Reference Manual for details. -->
  <dir>NIX_PROFILE/lib/X11/fonts</dir>
  <dir>NIX_PROFILE/share/fonts</dir>
</fontconfig>

and run fc-cache.

Alternatively, enable Fontconfig configuration in your Home Manager configuration.

=== Imperative installation of user fonts === 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.

== Configuring fonts ==

The nixos key fonts.fontconfig (click to see the full list!) handles the fontconfig options. Some options are nicely wrapped in nix; there's always localConf to go straight to the XML.

=== 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

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.

=== 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". fc-match NewCenturySchlbk would display similiar info.

Adding this to your /etc/nixos/configuration.nix should prompt it to use the more similar (and nicer) serif Schola font instead:

❄︎ /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>
    '';
  };
};

For more information and examples on the xml configuration language:

For a list of suitable replacement fonts:

== Troubleshooting ==

=== What font names can be used in 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;