https://wiki.archlinux.org/api.php?action=feedcontributions&user=Garison&feedformat=atomArchWiki - User contributions [en]2024-03-29T05:42:32ZUser contributionsMediaWiki 1.41.0https://wiki.archlinux.org/index.php?title=Emacs&diff=785603Emacs2023-08-16T20:08:03Z<p>Garison: Removed an extra "or"</p>
<hr />
<div>[[Category:Text editors]]<br />
[[Category:Console applications]]<br />
[[Category:GNU]]<br />
[[de:Emacs]]<br />
[[fr:Emacs]]<br />
[[ja:Emacs]]<br />
[[pt:Emacs]]<br />
[[Wikipedia:Emacs|Emacs]] is an extensible, customizable, self-documenting real-time display editor. At the core of Emacs lies an [[Wikipedia:Emacs Lisp|Emacs Lisp]] interpreter, the language in which the majority of Emacs' built-in functionality and extensions are implemented. GNU Emacs uses GTK as its X toolkit, though it functions equally well within a CLI environment.<br />
<br />
== Installation ==<br />
<br />
For the stable version of GNU Emacs, [[install]] the {{Pkg|emacs}} package. Variants can be searched for, for example {{AUR|emacs-git}} for the development branch of GNU Emacs.<br />
<br />
=== Forks ===<br />
<br />
{{Accuracy|Most of these share no code with emacs and should be relegated to [[#Alternatives]] at best, or removed.}}<br />
<br />
{{Style|Does not use [[Template:App]]}}<br />
<br />
* {{AUR|emacs-pgtk-native-comp-git}} or {{AUR|emacs-native-comp-git}} or {{AUR|emacs-native-comp-git-enhanced}}: An unofficial fork combining the development branch of GNU Emacs (including native compilation) with the new rendering engine PGTK.<br />
* {{AUR|emacs-ng}} - A new approach to Emacs - Including TypeScript, Threading, Async I/O, and WebRender.<br />
* {{AUR|emacs-ng-git}} - A new approach to Emacs - Including TypeScript, Threading, Async I/O, and WebRender. Git version<br />
* {{Pkg|mg}} - mg, also known as Micro GNU Emacs, is a lightweight text editor that is designed to be used in a terminal environment. It is based on GNU Emacs, but it has a smaller code base and a simplified user interface. mg is particularly useful for editing configuration files and other text files on remote servers.<br />
* {{AUR|qemacs}} - qemacs, also known as Quick Emacs, is a text editor that is designed to be fast and lightweight. It is based on the Emacs Lisp interpreter, but it has a smaller code base and a simplified user interface. qemacs is particularly useful for editing large files and for performing complex text operations.<br />
* {{AUR|qemacs-git}} - QEmacs (Quick Emacs) is a very small editor with Emacs look and feel, syntax highlighting, UTF-8, dired mode with preview window, and many other features.<br />
* {{AUR|texmacs}} - Free scientific text editor, inspired by TeX and GNU Emacs. WYSIWYG editor TeX-fonts and CAS-interface (Giac, GTybalt, Macaulay 2, Maxima, Octave, Pari, Qcl, R and Yacas) in one.<br />
* {{AUR|sxemacs-git}} - sxemacs is a variant of XEmacs, which is another popular text editor that is based on the Emacs Lisp interpreter. sxemacs is designed to be more user-friendly and to have a more modern user interface than GNU Emacs. It includes many features that are not available in GNU Emacs, such as support for TrueType fonts and integration with external programs.<br />
* {{AUR|uemacs-git}} - also known as MicroEMACS (MicroEMACS/PK 4.0.15), customized by Linus Torvalds, is a text editor that is designed to be small, fast, and portable. It is based on the original Emacs code base, but it has been significantly modified to reduce its size and to improve its performance. uemacs is particularly useful for embedded systems and other resource-constrained environments.<br />
* {{AUR|femto-emacs-git}} - femto-emacs is a text editor that is designed to be small, fast, and portable. It is based on the MicroEMACS 3.9 code base, but it has been significantly modified to improve performance and to add new features. femto-emacs is particularly useful for embedded systems and other resource-constrained environments.<br />
* {{AUR|jove}} - Jonathan's Own Version of Emacs is an Emacs-like editor without Lisp.<br />
<br />
== Running Emacs ==<br />
<br />
Before launching emacs, you should know how to close it (especially if you run it in a terminal): use the<br />
{{ic|Ctrl+x}}{{ic|Ctrl+c}} key sequence.<br />
<br />
To start Emacs run:<br />
<br />
$ emacs<br />
<br />
or, to use it from the console:<br />
<br />
$ emacs -nw<br />
<br />
or, for fast loading (no .emacs) and editing within CLI:<br />
<br />
$ emacs -Q -nw<br />
<br />
If you installed the nox version, 'emacs' and 'emacs -nw' will be the same.<br />
<br />
A file name can also be provided to open that file immediately:<br />
<br />
$ emacs filename.txt<br />
<br />
=== No colors ===<br />
<br />
By default, Emacs starts with a color theme showing hyperlinks in dark blue. To start Emacs on a text terminal without any color theme or scheme:<br />
<br />
$ emacs -nw --color=no<br />
<br />
This will cause all text to appear in the foreground color of the terminal — normally white text on a black background, or black text on a white background.<br />
<br />
=== As a daemon ===<br />
<br />
In order to avoid reloading the Emacs configuration file every time Emacs starts, you can run Emacs as a daemon:<br />
<br />
$ emacs --daemon<br />
<br />
You may then connect to the daemon by running: <br />
<br />
$ emacsclient -nc<br />
<br />
Which creates a new frame {{ic|-c}} (use {{ic|-t}} if you prefer to use it in the terminal) and does not hog the terminal {{ic|-n}} ({{ic|--no-wait}}).<br />
Note that some programs such as Mutt or Git (for commit messages) wait for the editor to finish, so you cannot use the {{ic|-n}} parameter.<br />
If your default editor is set to use it, you will have to specify an alternate editor (''e.g.'' {{ic|emacsclient -a "" -t}}) for those programs.<br />
<br />
=== As a systemd unit ===<br />
<br />
A systemd unit is included in Emacs 26.1. The unit is installed with Emacs, but it must be [[enabled]] as a [[user unit]] (not a system-wide) after installing Emacs. <br />
<br />
After the service is started, Emacs is ready. <br />
<br />
Note that systemd user units do not inherit environment variables from a login shell (like {{ic|~/.bash_profile}}). See [[Systemd/User#Environment variables]] for more information.<br />
<br />
If you start emacs as a daemon, you may want to set the {{ic|VISUAL}} and {{ic|EDITOR}} environment variables to {{ic|emacsclient}} so that programs that start an editor use emacsclient instead of starting a new full instance of the editor. Programs that use an external editor include email programs (for editing the message), Git (for editing the commit message), and less (the {{ic|v}} command for editing the displayed file). Do not use the {{ic|-n}} ({{ic|--nowait}}) option to emacsclient, since programs typically expect editing to be finished when the editor exits.<br />
<br />
It is also recommended to change any GUI start menu entries (or equivalent) for Emacs to point to emacsclient instead of emacs, so that the emacs daemon is used instead of starting a new emacs process.<br />
<br />
== Getting help ==<br />
<br />
Emacs has a built-in tutorial which can be accessed by clicking the first link on the splash screen and selecting ''Help>Emacs Tutorial'' from the menu or by pressing {{ic|C-h t}}.<br />
<br />
To read the tutorial in a language other than english, use the command {{ic|Alt x}}, and enter {{ic|help-with-tutorial-spec-language}}<br />
<br />
Emacs is self-documenting by design. As such, a great deal of information is available to determine the name of a specific command or its keybinding, for example. See all contextual help bindings with {{ic|C-h C-h}}.<br />
<br />
Emacs also includes a set of reference cards, useful for beginners and experts alike, see {{ic|/usr/share/emacs/''version''/etc/refcards/}}.<br />
<br />
=== The manuals ===<br />
<br />
If you really want to master Emacs, the most recommended source of documentation remains the official manuals:<br />
<br />
* Emacs: the complete Emacs user manual.<br />
* Emacs FAQ.<br />
* Emacs Lisp Intro: if you never used any programming language before.<br />
* Elisp: if you are already familiar with a programming language.<br />
<br />
You can access them as PDFs from [https://www.gnu.org/software/emacs/manual/ GNU.org] or directly from Emacs itself thanks to the embedded 'info' reader: {{ic|C-h i}}. Press {{ic|m}} to choose a book.<br />
<br />
Some users prefer to read books using 'info' because of its convenient shortcuts, its paragraphs adapting to window width and the font adapted to current screen resolution. Some find it less irritating to the eyes. Finally you can easily copy content from the book to any Emacs buffer, and you can even execute Lisp code snippets directly from the examples.<br />
<br />
You may want to read the '''Info''' book to know more about it: {{ic|C-h i m info <RET>}}.<br />
Press {{ic|?}} while in info mode for a quick list of shortcuts.<br />
<br />
== Customization ==<br />
<br />
One of Emacs's main features is its extensibility and the ease of configuration. Emacs has a built-in customization engine. You can do {{ic|M-x customize}} which displays a list of customization options. For how to use this interface, see the Easy Customization info node: {{ic|(info "(emacs) Easy Customization")}}. You can set customization opens just for one Emacs session or save them into a [[#Configuration file]] so that they are saved across Emacs sessions. Note that this is what the customization interface does if you select "Apply and Save."<br />
<br />
=== Configuration file ===<br />
<br />
When Emacs is started, it normally tries to load a Lisp program from an "initialization file", or "init file" for short. This file, if it exists, specifies how to initialize Emacs for you. Emacs looks for your init file at {{ic|~/.emacs}}, {{ic|~/.emacs.el}},{{ic|~/.emacs.d/init.el}},or {{ic|~/.config/emacs/init.el}} . See the info node "Init File" for more: {{ic| (info "(emacs) Init File")}}<br />
<br />
== Tips and tricks ==<br />
<br />
=== TRAMP ===<br />
<br />
TRAMP (Transparent Remote Access, Multiple Protocols) is an extension which, as its name suggests, provides transparent access to remote files across a number of protocols. When prompted for a filename, entering a specific form will invoke TRAMP. Some examples:<br />
<br />
To prompt for the root password before opening {{ic|/etc/hosts}} with root permissions:<br />
<br />
C-x C-f /sudo::/etc/hosts<br />
<br />
To connect to 'remotehost' as 'you' via SSH and open the file {{ic|~/example.txt}}:<br />
<br />
C-x C-f /ssh:you@remotehost:~/example.txt<br />
<br />
The path for TRAMP is typically of the form '/[protocol]:[[user@]host]:<file>'. <br />
<br />
To connect to 'myhost' as 'you' and edit {{ic|/etc/hosts}} with ''sudo'':<br />
<br />
/ssh:you@remotehost|sudo:remotehost:/etc/hosts<br />
<br />
TRAMP supports much more than the examples above might indicate. For more information refer to the TRAMP info manual, which is distributed with Emacs.<br />
<br />
=== Using Emacs as git mergetool ===<br />
<br />
By default, Git provides support for using Emacs' Emerge mode as a merge tool. However you may prefer the Ediff mode. Unfortunately this mode is not supported by git for technical reasons. There is still a way to use it by evaluating some elisp code upon emacs call.<br />
<br />
{{hc|.gitconfig|<nowiki><br />
[mergetool.ediff]<br />
cmd = emacs --eval \" (progn (defun ediff-write-merge-buffer () (let ((file ediff-merge-store-file)) (set-buffer ediff-buffer-C) (write-region (point-min) (point-max) file) (message \\\"Merge buffer saved in: %s\\\" file) (set-buffer-modified-p nil) (sit-for 1))) (setq ediff-quit-hook 'kill-emacs ediff-quit-merge-hook 'ediff-write-merge-buffer) (ediff-merge-files-with-ancestor \\\"$LOCAL\\\" \\\"$REMOTE\\\" \\\"$BASE\\\" nil \\\"$MERGED\\\"))\" <br />
<br />
[merge]<br />
tool = ediff<br />
</nowiki>}}<br />
<br />
Note that the command has to be on a single line.<br />
In the above example, we launch a new instance of Emacs. You might want to use emacsclient for quicker startup; it is not recommended though since the Ediff call is not really clean: it could mess with your current Emacs session.<br />
<br />
If you want an instant startup you can use the {{ic|-q}} parameter. If you want to launch Emacs quickly while preserving at least a part of your configuration, you can call Emacs with<br />
<br />
emacs -q -l ~/.emacs-light<br />
<br />
where the light configuration file loads only what you need for Ediff.<br />
<br />
See [https://web.archive.org/web/20090210145607/http://kerneltrap.org/mailarchive/git/2007/7/1/250424 kerneltrap.org] and [https://stackoverflow.com/questions/1817370/using-ediff-as-git-mergetool stackoverflow] for more details on this trick and the Ediff issue.<br />
<br />
=== Using Caps Lock as Control key ===<br />
<br />
Some users like this behavior to avoid the so-called "emacs pinky". If you want to try it on X, just run <br />
<br />
$ setxkbmap -option 'ctrl:nocaps'<br />
<br />
Alternatively, to '''swap''' these keys, run<br />
<br />
$ setxkbmap -option 'ctrl:swapcaps'<br />
<br />
To set this permanently, consider adding it to your {{ic|.xinitrc}} file. <br />
<br />
Now, if you ever need to uppercase a region, just use the default {{ic|C-x C-u}} keybinding, which calls the {{ic|upcase-region}} function.<br />
<br />
See [http://ergoemacs.org/emacs/swap_CapsLock_Ctrl.html] for an alternative approach.<br />
<br />
If you are missing your Caps Lock function, map it as both "Shift" at same time.<br />
<br />
$ setxkbmap -option "shift:both_capslock"<br />
<br />
Some desktop environments include graphical tools to simplify keyboard remappings. For example, in [[Plasma|Plasma 5]] open System Settings and click on Input Devices. Select Keyboard and in the Advanced tab you will find the setting Caps Lock behaviour under which you can select Caps Lock is also a Ctrl.<br />
<br />
=== Multiplexing emacs and emacsclient ===<br />
<br />
Opening a new file in the same {{ic|emacs-session}} requires the use of {{ic|emacsclient}}. {{ic|emacs}} command can be itself wrapped to do the smarter job to open the file if the session exists.<br />
<br />
To start session you need to {{ic|start-server}}. This snippet will create server in first session of emacs. Add this to your {{ic|emacs}} configuration file.<br />
<br />
{{hc|.emacs or .emacs.d/init.el|<br />
(require 'server)<br />
(unless (server-running-p)<br />
(server-start))<br />
}}<br />
<br />
Shell alias method is not adequate for this since you also need to pass variables or start the independent session of your own. Add this to the {{ic|.bashrc}} or any rc file of your shell. This will make your {{ic|emacs}} command behave like emacsclient if the argument is passed.<br />
<br />
{{bc|<nowiki><br />
function emacs {<br />
if [[ $# -eq 0 ]]; then<br />
/usr/bin/emacs # "emacs" is function, will cause recursion<br />
return<br />
fi<br />
args=($*)<br />
for ((i=0; i <= ${#args}; i++)); do<br />
local a=${args[i]}<br />
# NOTE: -c for creating new frame<br />
if [[ ${a:0:1} == '-' && ${a} != '-c' && ${a} != '--' ]]; then<br />
/usr/bin/emacs ${args[*]}<br />
return<br />
fi<br />
done<br />
setsid emacsclient -n -a /usr/bin/emacs ${args[*]}<br />
}<br />
</nowiki>}}<br />
<br />
If you want to run it in a new session just do {{ic|emacs ''file'' -}}.<br />
<br />
=== Multiple configurations ===<br />
<br />
You can use several configurations and tell Emacs to load one or the other.<br />
<br />
For example, let us define two configuration files.<br />
<br />
{{hc|.emacs|<br />
(load "~/.emacs.d/main" nil t)<br />
(load "~/.emacs.d/functions" nil t)<br />
(load "~/.emacs.d/modes" nil t)<br />
(load "~/.emacs.d/plugins" nil t)<br />
(load "~/.emacs.d/theme" nil t)<br />
}}<br />
<br />
This is the full configuration we load for the daemon. But the ''plugins'' file is huge and slow to load. If we want to spawn a new Emacs instance that does not need the ''plugins'' features, it can be cumbersome to load it every time in the long run.<br />
<br />
{{hc|.emacs-light|<br />
(load "~/.emacs.d/main" nil t)<br />
(load "~/.emacs.d/functions" nil t)<br />
(load "~/.emacs.d/modes" nil t)<br />
(load "~/.emacs.d/theme" nil t)<br />
}}<br />
<br />
And now we launch Emacs with<br />
<br />
emacs -q -l ~/.emacs-light<br />
<br />
You can create an alias to ease the call.<br />
<br />
=== Local and custom variables ===<br />
<br />
You can define variables in your configuration file that can be later one modified locally for a file.<br />
<br />
(defcustom my-compiler "gcc" "Some documentation")<br />
<br />
Now in any file you can define local variables in two ways, see [https://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html the manual for complete details ]<br />
<br />
* Using {{ic| M-x add-file-local-variable-prop-line}}, which adds a commented line at the beginning similar to:<br />
// -*- my-compiler:g++; mode:c++ -*-<br />
* Or you can use {{ic| M-x add-file-local-variable}} to add lines near the end of the file:<br />
// Local Variables:<br />
// my-compiler: g++<br />
// mode: c++<br />
// End:<br />
<br />
Note that for the values to take effect, you will need to call {{ic|M-x revert-buffer}}.<br />
<br />
Custom variables are considered unsafe by default. If you try to open a file that contains local variable redefining custom variables, Emacs will ask you for confirmation.<br />
<br />
You can declare the variable as secure, thus removing the Emacs prompt for confirmation. You need to specify a predicate that any new value has to verify so that it can be considered safe.<br />
<br />
(defcustom my-compiler "gcc" "Some documentation" :safe 'stringp)<br />
<br />
In the previous example, if you attempt to set anything else than a string, Emacs will consider it insecure.<br />
<br />
=== Custom colors and theme ===<br />
<br />
Colors can be easily customized using the ''face'' facility.<br />
<br />
(set-face-background 'region "color-17")<br />
(set-face-foreground 'region "white")<br />
(set-face-bold-p 'font-lock-builtin-face t ) <br />
<br />
You can have let Emacs tell you the name of the face where the point is. Use the ''customize-face'' function for that. The facility will show you how to set colors, bold, underline, etc.<br />
<br />
Emacs in console can handle 256 colors, but you will have to use an appropriate terminal for that. For instance URxvt has support for 256 colors. You can use the ''list-colors-display'' for a comprehensive list of supported colors. This is highly terminal-dependent.<br />
<br />
See also:<br />
<br />
* https://www.emacswiki.org/emacs/ColorThemes<br />
* https://www.gnu.org/software/emacs/manual/html_node/emacs/Custom-Themes.html<br />
<br />
=== SyncTeX support ===<br />
<br />
Emacs is a powerful LaTeX editor. This is mostly due to the fact you can adapt or create a LaTeX mode to fit your needs best.<br />
<br />
Still, there might be some challenges, like SyncTeX support. First you need to make sure your TeX distribution has it. If you installed TeX Live manually, you may need to install the ''synctex'' package.<br />
<br />
# umask 022 && tlmgr install synctex<br />
<br />
SyncTeX support is viewer-dependent. Here we will use Zathura as an example, so the code needs to be adapted if you want to use another PDF viewer.<br />
<br />
{{bc|<br />
(defcustom tex-my-viewer "zathura --fork -s -x \"emacsclient --eval '(progn (switch-to-buffer (file-name-nondirectory \"'\"'\"%{input}\"'\"'\")) (goto-line %{line}))'\"" <br />
"PDF Viewer for TeX documents. You may want to fork the viewer<br />
so that it detects when the same document is launched twice, and<br />
persists when Emacs gets closed.<br />
<br />
Simple command:<br />
<br />
zathura --fork<br />
<br />
We can use<br />
<br />
emacsclient --eval '(progn (switch-to-buffer (file-name-nondirectory \"%{input}\")) (goto-line %{line}))'<br />
<br />
to reverse-search a pdf using SyncTeX. Note that the quotes and double-quotes matter and must be escaped appropriately."<br />
:safe 'stringp)<br />
}}<br />
<br />
Here we define our custom variable. If you are using AucTeX or Emacs default LaTeX-mode, you will have to set the viewer accordingly.<br />
<br />
Now open a LaTeX source file with Emacs, compile the document, and launch the viewer. Zathura will spawn. If you press {{ic|Ctrl+Left click}} Emacs should place the point at the corresponding position.<br />
<br />
=== Syntax highlighting for systemd Files ===<br />
<br />
You can use [https://github.com/holomorph/systemd-mode systemd-mode].<br />
<br />
Alternatively, you can simply tell emacs to colour systemd files (services, timer, etc.), by adding this to your init file:<br />
<br />
{{bc|<br />
(add-to-list 'auto-mode-alist '("\\.service\\'" . conf-unix-mode))<br />
(add-to-list 'auto-mode-alist '("\\.timer\\'" . conf-unix-mode))<br />
(add-to-list 'auto-mode-alist '("\\.target\\'" . conf-unix-mode))<br />
(add-to-list 'auto-mode-alist '("\\.mount\\'" . conf-unix-mode))<br />
(add-to-list 'auto-mode-alist '("\\.automount\\'" . conf-unix-mode))<br />
(add-to-list 'auto-mode-alist '("\\.slice\\'" . conf-unix-mode))<br />
(add-to-list 'auto-mode-alist '("\\.socket\\'" . conf-unix-mode))<br />
(add-to-list 'auto-mode-alist '("\\.path\\'" . conf-unix-mode))<br />
(add-to-list 'auto-mode-alist '("\\.netdev\\'" . conf-unix-mode))<br />
(add-to-list 'auto-mode-alist '("\\.network\\'" . conf-unix-mode))<br />
(add-to-list 'auto-mode-alist '("\\.link\\'" . conf-unix-mode))<br />
}}<br />
<br />
=== Clipboard support for emacs-nox ===<br />
<br />
To use the [[Xorg]] clipboard in emacs-nox, [[install]] {{Pkg|xclip}} and add the following function to {{ic|~/.emacs}} [https://lists.gnu.org/archive/html/help-gnu-emacs/2014-08/msg00189.html]<br />
<br />
{{bc|1=<br />
;; use xclip to copy/paste in emacs-nox<br />
(unless window-system<br />
(when (getenv "DISPLAY")<br />
(defun xclip-cut-function (text &optional push)<br />
(with-temp-buffer<br />
(insert text)<br />
(call-process-region (point-min) (point-max) "xclip" nil 0 nil "-i" "-selection" "clipboard")))<br />
(defun xclip-paste-function()<br />
(let ((xclip-output (shell-command-to-string "xclip -o -selection clipboard")))<br />
(unless (string= (car kill-ring) xclip-output)<br />
xclip-output )))<br />
(setq interprogram-cut-function 'xclip-cut-function)<br />
(setq interprogram-paste-function 'xclip-paste-function)<br />
))<br />
}}<br />
<br />
{{Tip|You may also enable terminal mouse support by adding:<br />
<br />
{{bc|1=<br />
;; xterm mouse support<br />
(require 'mouse)<br />
(xterm-mouse-mode t)<br />
}}<br />
<br />
See also [https://www.opensource.apple.com/source/emacs/emacs-51/emacs/lisp/mwheel.el mwheel.el].<br />
}}<br />
<br />
== Packages ==<br />
<br />
Emacs's functionality can be extended with third-party packages. The built-in package manager {{ic|package.el}} is the officially supported way to do this, though there are several other package managers written by members of the Emacs community. {{ic|package.el}} relies on the variable {{ic|package-archives}} to find packages. By default, this includes the [https://elpa.gnu.org/ Emacs Lisp Package Archive (ELPA)]. {{ic|M-x list-packages}} will create a buffer listing all the packages your Emacs knows about. The manual ({{ic|[https://www.gnu.org/software/emacs/manual/html_node/emacs/Packages.html (info "(emacs) Packages")]}}) contains much more information. <br />
<br />
Third-party package archives can be added. The most widely used of these is [https://melpa.org/ MELPA].<br />
<br />
A number of popular extensions are available as packages in the official repositories, and more still, via the [[AUR]]. The name of such packages usually have a 'emacs-' prefix (for example, {{Pkg|emacs-lua-mode}}), though not always (for example, {{AUR|auctex}}).<br />
<br />
Some packages may require you to make changes to your configuration file in order to activate them so that their features are available during an Emacs session. For example, if you install {{AUR|auctex}}, you will need to add <br />
<br />
{{bc|<br />
(load "auctex.el" nil t t)<br />
(load "preview-latex.el" nil t t)<br />
}}<br />
<br />
to your configuration file. Other packages should let you know how to activate them in the commentary section of their source code or in their README.<br />
<br />
== Troubleshooting ==<br />
<br />
=== Emacs fails to start with the error message 'Undefined color: "WINDOW_FOREGROUND"' ===<br />
<br />
You need to install either the {{Pkg|mcpp}} package or the {{Pkg|gcc}} package. The C preprocessor ''cpp'' is used to preprocess [[X resources]] by ''xrdb''. If a C preprocessor is not installed on the system, ''xrdb'' silently skips running the C preprocessor and the symbol WINDOW_FOREGROUND is not expanded to a hexadecimal color code.<br />
<br />
=== Emacs systemd service fails to start when using Gccemacs ===<br />
<br />
When using Gccemacs (either the branch {{ic|emacs-native-comp}} or {{ic|pgtk-nativecomp}}) and trying to start a systemd service for it, an error message informing that a {{ic|.eln}} file was not found might be logged:<br />
<br />
{{hc|$ journalctl --user -xb -g eln|<nowiki><br />
emacs[7507]: emacs: ../native-lisp/28.0.50-x86_64-pc-linux-gnu-fc9c33938bf279333039c28064d363e8/lisp-mode-410874a46ab8852855281f021ca61fe7-1738806322de892570d69dfc55b437c2.eln: cannot open shared object file: No such file or directory<br />
</nowiki>}}<br />
<br />
As a workaround, [[edit]] the {{ic|WorkingDirectory}} line of {{ic|emacs.service}} in the {{ic|[Service]}} section.<br />
<br />
{{hc|emacs.service|<nowiki><br />
[Service]<br />
...<br />
WorkingDirectory=/usr/lib/emacs/28.0.50/x86_64-pc-linux-gnu/<br />
...<br />
</nowiki>}}<br />
<br />
{{Note|The {{ic|WorkingDirectory}} parameter has to be defined ''before'' a possible existing {{ic|Restart}} parameter.}}<br />
<br />
=== Colored output issues ===<br />
<br />
By default, the Emacs shell will show raw escape sequences used to print colors. In other words, it will display strange symbols in place of the desired colored output.<br />
<br />
Including the following into {{ic|~/.emacs}} amends the problem:<br />
<br />
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)<br />
<br />
=== Problems displaying characters in X Windows ===<br />
<br />
If when you start emacs in X windows all the characters in the main window are white boxes with black borders (the ones you see if you try to view characters for which you do not have the correct font installed), you need to install {{Pkg|xorg-fonts-75dpi}} and/or {{Pkg|xorg-fonts-100dpi}} and restart X windows.<br />
<br />
=== Slow startup ===<br />
<br />
{{Tip|To eliminate startup time, users may want to consider running Emacs [[#As a systemd unit]].}}<br />
<br />
Slow startup times are often caused by one of two things.<br />
<br />
To determine which it might be, run Emacs with:<br />
<br />
$ emacs -q<br />
<br />
* Mistakes, particularly in {{ic|/etc/hosts}}, will often result in a 5+ second delay when starting Emacs. Refer to '[[Configuring network#Set the hostname|set the hostname]]' in the network configuration guide for information. <br />
* You may need to monitor any network packets sent from your computer (using a program like Wireshark) to see if there is any strange behavior.<br />
* A simple way to search for the cause is to comment-out (i.e., prefix lines with ';') suspect sections of your {{ic|~/.emacs}} (or {{ic|~/.emacs.d/init.el}}) then start Emacs again to see if there is any change. Keep in mind use of "require" and "load" can slow the startup down, especially when used with larger extensions. They should, as a rule, only be used when their target is either: needed once Emacs starts or provides little more than "autoloads" for an extension. Otherwise, use the 'autoload function directly. For example, instead of: {{bc|(require 'anything)}} you might use: {{bc|(autoload 'anything "anything" "Select anything" t)}}<br />
<br />
=== Cannot open load file: ... ===<br />
<br />
The most common cause of this error is the 'load-path' variable not including the path to the directory within which the extension is located. To solve this, add the appropriate path to the list to be searched prior to attempting to load the extension:<br />
<br />
(add-to-list 'load-path "''/path/to/directory/''")<br />
<br />
When attempting to use packages for extensions and Emacs has been configured with a prefix other than {{ic|/usr}}, the load-path will need to be updated. Place the following in {{ic|~/.emacs}} prior to the instructions provided by the package:<br />
<br />
(add-to-list 'load-path "/usr/share/emacs/site-lisp")<br />
<br />
If compiling Emacs by hand, keep in mind that the default prefix is {{ic|/usr/local}}.<br />
<br />
=== Dead-accent keys problem: '<dead-acute> is undefined' ===<br />
<br />
Searching about this bug on Google, we find this link: https://lists.gnu.org/archive/html/help-gnu-emacs/2009-05/msg00167.html explaining the problem. The normal way to use accent keys does not work as expected. Trying to accent a word like 'fiancé' will produce the message above.<br />
<br />
A way to solve it is just put the line below on your startup file, {{ic|~/.emacs}}:<br />
<br />
(require 'iso-transl)<br />
<br />
And no, it is not a bug, but a feature of new Emacs versions. Reading the subsequent messages about it on the mail list, we found it [https://lists.gnu.org/archive/html/help-gnu-emacs/2009-05/msg00179.html]:<br />
<br />
:It seems that nothing is loaded automatically because there is a choice betwee iso-transl and iso-acc. Both seem to provide an input method with C-x 8 or Alt-<accent> prefix, but what you and I are doing is just pressing a dead key (^, ´, `, ~, ¨) for the accent and then another key to "compose" the accented character. And there is no Alt key used in this! And according to documentation it seems be appropriate for 8-bit encodings, so it should be pretty useless in UTF-8. I reported this bug when it was introduced, but the bug seems to be classified as a feature ... Maybe it's just because the file is auto-loaded though pretty useless.<br />
<br />
=== C-M-% and some other bindings do not work in emacs nox ===<br />
<br />
This is because terminals are more limited than Xorg. Some terminals may handle more bindings than other, though. Two solutions:<br />
<br />
* either use the graphical version,<br />
* or change the binding to a supported one.<br />
<br />
Example:<br />
<br />
{{hc|.emacs|(global-set-key (kbd "C-M-y") 'query-replace-regexp)}}<br />
<br />
=== Emacs hangs ===<br />
<br />
Due to its single-threaded nature, many operations block Emacs. This could happen in a few ways. For example, Emacs may be waiting for input from you (e.g. you have opened the minibuffer in one frame but are trying to work in another). Alternatively, Emacs could be running code that simply takes a while to finish. Or perhaps you have run across a bug. There are several ways of trying to unblock Emacs without killing the Emacs process. <br />
<br />
* Try pressing {{ic|C-g}}. Depending on what Emacs is doing, you may need to press it multiple times.<br />
* Try pressing {{ic|ESC ESC ESC}}.<br />
* From another terminal, run {{ic|killall -SIGUSR2 emacs}}<br />
<br />
=== Emacs-nox output gets messy ===<br />
<br />
When working in a terminal, the color, indentation, or anything related to the output might become crazy. This is (probably?) because Emacs was sent a special character at some point which may conflict with the current terminal.<br />
If this happens you can do {{ic|M-x redraw-display}}, which will redraw the terminal's display. If this problem happens frequently, you might want to bind the command to a key, e.g. by putting something like: <br />
<br />
(global-set-key (kbd "<f7>") 'redraw-display)<br />
<br />
in your {{ic|.emacs}} file.<br />
<br />
Graphical Emacs does not suffer from this issue.<br />
<br />
=== Weird escaped numbers (utf-8) displaying in emacs terminal ===<br />
<br />
Export these values in your {{ic|.bashrc}} or {{ic|.zshrc}}:<br />
<br />
{{hc|$ ~/.bashrc or ~/.zshrc |2=export LANG\='en_US.UTF-8'<br />
export LC_ALL\="en_US.UTF-8"<br />
export TERM\=xterm-256color<br />
}}<br />
<br />
It can be a source of errors since in Linux distributions the correct values use lowercase utf (e.g. {{ic|en_US.utf-8}})<br />
<br />
To view all available locales use {{ic|locale -a}}.<br />
<br />
=== Shift + Arrow keys not working in emacs within tmux ===<br />
<br />
Enable xterm-keys in your [[tmux]] configuration:<br />
<br />
{{hc|~/.tmux.conf|<br />
setw -g xterm-keys on<br />
}}<br />
<br />
Because this will break other key combinations, put the following in your emacs config.<br />
<br />
{{hc|~/.emacs|<br />
(defadvice terminal-init-screen<br />
;; The advice is named `tmux', and is run before `terminal-init-screen' runs.<br />
(before tmux activate)<br />
;; Docstring. This describes the advice and is made available inside emacs;<br />
;; for example when doing C-h f terminal-init-screen RET<br />
"Apply xterm keymap, allowing use of keys passed through tmux."<br />
;; This is the elisp code that is run before `terminal-init-screen'.<br />
(if (getenv "TMUX")<br />
(let ((map (copy-keymap xterm-function-map)))<br />
(set-keymap-parent map (keymap-parent input-decode-map))<br />
(set-keymap-parent input-decode-map map))))<br />
}}<br />
<br />
See [https://github.com/tmux/tmux/wiki/FAQ#how-do-i-make-modified-function-and-arrow-keys-like-c-up-m-pageup-work-inside-tmux tmux FAQ] for details.<br />
<br />
=== Improper window resizing in KDE ===<br />
<br />
{{Merge|KDE|Applicable to other applications}}<br />
<br />
KDE users may observe that the Emacs window does not resize properly, but rather, the resized portion is transparent and mouse clicks are sent to the underlying window. To correct this behavior, change KDE's GTK3 theme to something other than oxygen-gtk. For instance, use the Emacs theme which is included with {{Pkg|gtk3}}.<br />
<br />
To force Emacs to maximize completely in KDE, click the Emacs icon in the title bar, and select ''More Actions > Special Window Settings''. Then in the ''Size & Position'' tab, select ''Obey geometry restrictions'', choose ''Force'' in the dropdown menu, and select ''No'' from the radio buttons on the right.<br />
<br />
== Alternatives ==<br />
<br />
There are numerous "smaller" implementations of Emacs. GNU/Emacs is probably the most popular. Some lightweight Emacs compatible alternatives will be listed here:<br />
<br />
* {{App|mg|Lightweight implementation of Emacs written in C. Note that it does not support UTF-8.|https://github.com/hboetes/mg|{{Pkg|mg}}}}<br />
* {{App|Zile|"Zile Is Lossy Emacs", a lightweight clone written to be as similar as possible to Emacs. Zile has no UTF-8 support.|https://www.gnu.org/software/zile/|{{AUR|zile}}}}<br />
* {{App|uemacs|A "Micro-emacs" version customized by Linus Torvalds.|https://git.kernel.org/pub/scm/editors/uemacs/uemacs.git|{{AUR|uemacs-git}}}}<br />
* {{App|emacs-ng|A new approach to Emacs - Including TypeScript, Threading, Async I/O, and WebRender.|https://github.com/emacs-ng/emacs-ng|{{AUR|emacs-ng-git}}}}<br />
<br />
=== Emacs distros ===<br />
<br />
* [[Spacemacs]] - A community-driven Emacs distribution - The best editor is neither Emacs nor Vim, it's Emacs *and* Vim!<br />
* [https://github.com/doomemacs/doomemacs/ Doom Emacs] - An Emacs framework for the stubborn martian hacker <br />
* [https://github.com/snackon/Witchmacs/ Witchmacs] - The cutest Emacs distribution<br />
* [https://github.com/pprobst/yukimacs/ Yukimacs] - A GNU/Emacs config built from the ground up (no Spacemacs or Doom Emacs), heavily inspired by Uncle Dave’s Emacs and Witchmacs.<br />
<br />
More: [https://www.emacswiki.org/emacs/StarterKits Starter Kits]<br />
<br />
== See also ==<br />
<br />
* [https://www.gnu.org/software/emacs/ GNU Emacs home page]<br />
* [https://www.gnu.org/software/emacs/manual/emacs.html GNU Emacs manual]<br />
* [https://www.emacswiki.org/ Emacs Wiki]<br />
* [https://wikemacs.org WikEmacs - a more readable, but less complete Emacs wiki]{{Dead link|2023|07|30|status=SSL error}}<br />
* [https://www2.lib.uchicago.edu/keith/tcl-course/emacs-tutorial.html Useful introduction to Emacs and its shortcuts]<br />
* [https://web.archive.org/web/20160506064817/https://d0edfcdc0ccc1cd13cdab5eb986fb92e8660dbef.googledrive.com/host/0B6LMD0u8OhYYZEotN2QyR1hwR1k/ The Church of Emacs (via Google drive)]<br />
* [https://www.gnu.org/software/emacs/refcards/pdf/refcard.pdf Official reference card]<br />
* [[EXWM]], the Emacs X Window Manager</div>Garisonhttps://wiki.archlinux.org/index.php?title=NVIDIA_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=741834NVIDIA (Русский)2022-08-16T20:38:37Z<p>Garison: Changed the name of the kernel parameter from nvidia-drm.modeset to nvidia_drm.modeset due to inconsistency with the original version of the article.</p>
<hr />
<div>[[Category:Graphics (Русский)]]<br />
[[Category:X server (Русский)]]<br />
[[de:Nvidia]]<br />
[[en:NVIDIA]]<br />
[[fa:اِنویدیا]]<br />
[[fr:NVIDIA]]<br />
[[ja:NVIDIA]]<br />
[[pt:NVIDIA]]<br />
[[zh-hans:NVIDIA]]<br />
{{TranslationStatus (Русский)|NVIDIA|8 февраля 2022|717384}}<br />
{{Related articles start (Русский)}}<br />
{{Related|NVIDIA/Советы и рекомендации}}<br />
{{Related|NVIDIA/Решение проблем}}<br />
{{Related|Nouveau (Русский)}}<br />
{{Related|NVIDIA Optimus (Русский)}}<br />
{{Related|PRIME}}<br />
{{Related|Bumblebee (Русский)}}<br />
{{Related|nvidia-xrun (Русский)}}<br />
{{Related|Xorg (Русский)}}<br />
{{Related|Vulkan (Русский)}}<br />
{{Related articles end}}<br />
<br />
Данная статья описывает процесс установки и настройки проприетарного драйвера графических карт [https://www.nvidia.com/ru-ru/ NVIDIA]. Для получения информации о драйверах с открытым исходным кодом обратитесь к статье [[Nouveau (Русский)]]. Также есть отдельная статья для обладателей ноутбуков с гибридной графикой Intel и NVIDIA, см. [[NVIDIA Optimus (Русский)]].<br />
<br />
== Установка ==<br />
<br />
{{Warning (Русский)|Избегайте установки драйвера с сайта NVIDIA. Установка через [[pacman (Русский)|pacman]] позволяет обновлять драйвер вместе с остальными компонентами системы.}}<br />
<br />
Данные инструкции предназначены для предоставляемых в дистрибутиве пакетов ядра {{Pkg|linux}} и {{Pkg|linux-lts}}. Пользователи других пакетов ядра могут сразу перейти к [[#Собственное ядро|следующему]] подразделу.<br />
<br />
1. Если вы не знаете модель установленной графической карты, воспользуйтесь следующей командой:<br />
:{{bc|$ lspci -k {{!}} grep -A 2 -E "(VGA{{!}}3D)"}}<br />
<br />
2. Определите версию драйвера, необходимую для вашей видеокарты:<br />
:* Используя поиск по кодовому имени (например, NV50, NVC0 и т.д.) на [https://nouveau.freedesktop.org/wiki/CodeNames/ странице Nouveau с кодовыми именами] или [https://gitlab.freedesktop.org/nouveau/wiki/-/blob/master/sources/CodeNames.mdwn].<br />
:* Просмотрев модели в [https://www.nvidia.com/object/IO_32667.html списке устаревших графических карт] NVIDIA: если вашей карты нет в списке, используйте последний доступный драйвер.<br />
:* Посетив [https://www.nvidia.com/Download/index.aspx?lang=ru страницу загрузки драйверов] NVIDIA.<br />
<br />
3. Установите подходящий драйвер для своей карты:<br />
:* Для карт Maxwell (NV110) и новее, в том числе: GeForce 930~, 10-20, Quadro/Tesla/Tegra и новее (подробный список есть в [https://download.nvidia.com/XFree86/Linux-x86_64/495.44/README/supportedchips.html официальном Readme]), [[установите]] пакет {{Pkg|nvidia}} (для ядра {{Pkg|linux}}) или {{Pkg|nvidia-lts}} (для ядра {{Pkg|linux-lts}}).<br />
::* Если эти пакеты не работают, в {{AUR|nvidia-beta}} может быть более новый драйвер с поддержкой вашего оборудования.<br />
:* Для видеокарт Kepler (NVE0) (в том числе GeForce 630-920) примерно из 2013-2014, [[установите]] пакет {{AUR|nvidia-470xx-dkms}}.<br />
:* Для видеокарт серии GeForce 400/500/600 [NVCx и NVDx] примерно из 2010-2011, [[установите]] пакет {{AUR|nvidia-390xx-dkms}}.<br />
:* Для установки драйвера более старых моделей (выпущеных в 2010 или раньше), обратитесь к разделу [[#Неподдерживаемые драйвера]].<br />
<br />
4. Для поддержки 32-разрядных приложений также необходимо установить соответствующий пакет nvidia ''lib32'' из репозитория [[Multilib (Русский)|multilib]] (например, {{Pkg|lib32-nvidia-utils}} или {{AUR|lib32-nvidia-390xx-utils}}).<br />
<br />
5. Перезагрузите систему. Пакет {{Pkg|nvidia}} содержит файл, который добавляет модуль ''nouveau'' в чёрный список, поэтому перезагрузка необходима.<br />
<br />
После установки драйвера можно перейти к разделу [[#Настройка Xorg]] или [[#Wayland]].<br />
<br />
=== Неподдерживаемые драйвера ===<br />
<br />
Если у вас установлена видеокарта серии GeForce 300 или старее (выпущенная в 2010 или раньше), Nvidia больше не поддерживает драйвера для данной карты. Это означает, что указанные драйвера [https://nvidia.custhelp.com/app/answers/detail/a_id/3142/ не поддерживают текущую версию Xorg]. В таком случае проще использовать драйвер [[Nouveau (Русский)|Nouveau]], который поддерживает старые видеокарты с текущей версией Xorg.<br />
<br />
Однако устаревшие драйверы Nvidia ещё доступны и могут предоставлять лучшую стабильность или 3D-производительность, если вы готовы откатить версию [[Xorg (Русский)|Xorg]]:<br />
<br />
* Для карт серий GeForce 8/9, ION и 100-300 [NV5x, NV8x, NV9x and NVAx], [[установите]] пакет {{AUR|nvidia-340xx-dkms}}. Последняя поддерживаемая версия Xorg 1.20.<br />
* Карты GeForce 7 series и более старые [NV6x, NV4x и ниже] не имеют пакетов для Arch Linux.<br />
<br />
=== Собственное ядро ===<br />
<br />
Если вы используете собственное ядро, то сборка модулей Nvidia может быть автоматизированна при помощи [[Dynamic Kernel Module Support (Русский)|DKMS]]. [[Установите]] пакет {{Pkg|nvidia-dkms}} (или специфичную ветку, например, {{AUR|nvidia-340xx-dkms}}).<br />
<br />
Убедитесь, что ядро собрано с опцией {{ic|1=CONFIG_DRM_SIMPLEDRM=y}}, а при использовании {{ic|CONFIG_DEBUG_INFO_BTF}} в PKGBUILD должно быть это (начиная с ядра 5.16):<br />
<br />
install -Dt "$builddir/tools/bpf/resolve_btfids" tools/bpf/resolve_btfids/resolve_btfids<br />
<br />
Модуль будет пересобираться после каждого обновления драйвера или ядра благодаря DKMS [[Pacman (Русский)#Хуки|Pacman Hook]].<br />
<br />
=== DRM kernel mode setting ===<br />
<br />
Для включения DRM ([[Wikipedia:ru:Direct Rendering Manager|Direct Rendering Manager]]) [[Kernel mode setting (Русский)|kernel mode setting]] добавьте [[параметр ядра]] {{ic|1=nvidia_drm.modeset=1}}.<br />
<br />
{{Note (Русский)|1=<nowiki/><br />
* Драйвер Nvidia '''не''' предоставляет драйвер {{ic|fbdev}} для высокого разрешения в консоли для скомпилированного модуля ядра {{ic|vesafb}}. Тем не менее, скомпилированный в ядро модуль {{ic|efifb}} поддерживает высокое разрешение в консоли на EFI системах. Этот метод требует GRUB или rEFInd и описан в разделе [[NVIDIA (Русский)/Tips and tricks (Русский)#Исправление разрешения терминала]].[https://forums.fedoraforum.org/showthread.php?t=306271][https://www.reddit.com/r/archlinux/comments/4gwukx/nvidia_drivers_and_high_resolution_tty_possible/][https://www.reddit.com/r/archlinux/comments/86lqc5/tty_resolution_nvidia_psaish/].<br />
* Драйвера Nvidia до версии 470 (например {{AUR|nvidia-390xx-dkms}}) не поддерживают аппаратное ускорение в XWayland, так что у приложений, не являющихся родными для Wayland, может быть плохая производительность в Wayland-сеансах.<br />
}}<br />
<br />
==== Ранняя загрузка ====<br />
<br />
Для базовой функциональности достаточно добавить параметр ядра. Если вы хотите, чтобы он загружался как можно раньше, или замечаете проблемы с запуском (например, модуль ядра {{ic|nvidia}} загружается после [[Display manager (Русский)|экранного менеджера]]), вы можете добавить {{ic|nvidia}}, {{ic|nvidia_modeset}}, {{ic|nvidia_uvm}} и {{ic|nvidia_drm}} в initramfs. <br />
<br />
===== mkinitcpio =====<br />
<br />
Если вы используете [[mkinitcpio (Русский)|mkinitcpio]], добавьте модули как описано в разделе [[mkinitcpio (Русский)#MODULES]].<br />
<br />
После добавления не забывайте запускать [[mkinitcpio (Русский)|mkinitcpio]] каждый раз после обновления пакета {{Pkg|nvidia}}. Можно использовать [[#pacman hook]] для автоматизации этого действия.<br />
<br />
===== Booster =====<br />
<br />
Если вы используете [[Booster]], смотрите [[Booster#Early module loading]].<br />
<br />
===== pacman hook =====<br />
<br />
Для того, чтобы не забывать обновлять initramfs после обновления nvidia, вы можете использовать pacman hook следующим образом:<br />
<br />
{{hc|/etc/pacman.d/hooks/nvidia.hook|2=<br />
[Trigger]<br />
Operation=Install<br />
Operation=Upgrade<br />
Operation=Remove<br />
Type=Package<br />
Target=nvidia<br />
Target=linux<br />
# Измените "linux" в строках Target и Exec, если вы используете другое ядро<br />
<br />
[Action]<br />
Description=Update Nvidia module in initcpio<br />
Depends=mkinitcpio<br />
When=PostTransaction<br />
NeedsTargets<br />
Exec=/bin/sh -c 'while read -r trg; do case $trg in linux) exit 0; esac; done; /usr/bin/mkinitcpio -P'<br />
}}<br />
<br />
Пропишите в {{ic|Target}} тот пакет, который вы установили в шагах выше (то есть {{ic|nvidia}}, {{ic|nvidia-dkms}}, {{ic|nvidia-lts}} или {{ic|nvidia-ck-''что-нибудь''}}).<br />
<br />
{{Note (Русский)|Усложнение в строке {{ic|Exec}} сделано для того, чтобы избежать многократного запуска mkinitcpio в случае одновременного обновления пакетов {{ic|nvidia}} и {{ic|linux}}. Если вас это не беспокоит, строки {{ic|1=Target=linux}} и {{ic|NeedsTargets}} можно убрать, а строку {{ic|Exec}} сократить до простого {{ic|1=Exec=/usr/bin/mkinitcpio -P}}.}}<br />
<br />
=== Аппаратное декодирование видео ===<br />
<br />
Аппаратное декодирование видео с помощью VDPAU поддерживается на картах серии GeForce 8 и новее. Аппаратное декодирование видео с помощью NVDEC поддерживается на картах Fermi (~400 серии) и новее. Подробности смотрите в статье [[Аппаратное ускорение видео]].<br />
<br />
=== Аппаратное кодирование видео с помощью NVENC ===<br />
<br />
Для NVENC нужен модуль {{ic|nvidia_uvm}} и файлы устройств в {{ic|/dev}}.<br />
<br />
Пакеты с последней версией драйвера содержат [[udev (Русский)#О правилах udev|правила udev]], которые создают нужные файлы автоматически, так что дополнительные действия не требуются.<br />
<br />
Если у вас старый драйвер (например, {{AUR|nvidia-340xx-dkms}}), вам нужно создать файлы устройств самостоятельно. Вызов утилиты {{ic|nvidia-modprobe}} создаст их. Вы можете создать {{ic|/etc/udev/rules.d/70-nvidia.rules}} для автоматического её запуска:<br />
<br />
{{hc|/etc/udev/rules.d/70-nvidia.rules|2=<br />
ACTION=="add", DEVPATH=="/bus/pci/drivers/nvidia", RUN+="/usr/bin/nvidia-modprobe -c0 -u"<br />
}}<br />
<br />
== Настройка Xorg ==<br />
<br />
Проприетарный драйвер видеокарты NVIDIA не нуждается в файле конфигурации сервера Xorg. Вы можете [[Xorg (Русский)#Запуск|запустить X]] для проверки корректной работы сервера Xorg без файла конфигурации. Однако может потребоваться создать файл (предпочтительнее {{ic|/etc/X11/xorg.conf.d/20-nvidia.conf}}, чем {{ic|/etc/X11/xorg.conf}}) для тонкой настройки некоторых параметров. Эта конфигурация может быть сгенерирована инструментом конфигурации NVIDIA Xorg или создана вручную. Если она создаётся вручную, она может быть минимальной (в том смысле, что она будет содержать только базовые настройки сервера Xorg), или она может включать в себя ряд настроек, которые могут обходить автоматически найденные или предварительно заданные настройки.<br />
<br />
{{Tip (Русский)|Больше информации о настройках можно прочитать в статье [[NVIDIA/Решение проблем]].}}<br />
<br />
=== Автоматическая настройка ===<br />
<br />
Пакет NVIDIA, включает в себя автоматический инструмент для создания файла конфигурации сервера Xorg ({{ic|xorg.conf}}) и может быть запущен путем выполнения:<br />
# nvidia-xconfig<br />
<br />
Данная команда автоматически обнаруживает и создаёт (или изменяет существующую) конфигурацию {{ic|/etc/X11/xorg.conf}} в соответствии с текущим аппаратным обеспечением.<br />
<br />
Если есть строка с указанием загрузки DRI, убедитесь, что она закомментирована:<br />
# Load "dri"<br />
Проверьте ещё раз {{ic|/etc/X11/xorg.conf}}, убедитесь, что глубина по умолчанию, горизонтальная синхронизация, частота кадров и разрешение допустимы.<br />
<br />
=== nvidia-settings ===<br />
<br />
Пакет {{Pkg|nvidia-settings}} позволяет редактировать большинство опций через консоль или графическую оболочку. Запуск {{ic|nvidia-settings}} без параметров запустит графический интерфейс; опции командной строки можно узнать в {{man|1|nvidia-settings}}.<br />
<br />
Также, вы можете запустить настройки от обычного пользователя и сохранить в {{ic|~/.nvidia-settings-rc}} или сохранить их в [[Xorg (Русский)#Через файл xorg.conf|xorg.conf]] с помощью ''Save to X configuration File''.<br />
<br />
Чтобы загрузить настройки из {{ic|~/.nvidia-settings-rc}} для текущего пользователя:<br />
<br />
$ nvidia-settings --load-config-only<br />
<br />
Можно добавить эту команду в [[автозапуск]].<br />
<br />
{{Note (Русский)|X-сервер может перестать запускаться после сохранения изменений в {{ic|nvidia-settings}}. Изменение или удаление сгенерированных файлов {{ic|~/.nvidia-settings-rc}} и/или Xorg поможет восстановить работоспособность.}}<br />
<br />
{{Note (Русский)|[[Cinnamon (Русский)|Cinnamon]] может переопределять настройки, сделанные в {{ic|nvidia-settings}}. Вы можете [[Cinnamon#Cinnamon overrides settings in xorg.conf|настроить запуск Cinnamon, чтобы предотвратить это]].}}<br />
<br />
=== Ручная настройка ===<br />
<br />
Некоторые настройки (которые не могут быть включены [[#Автоматическая настройка|автоматически]] или с помощью [[#nvidia-settings|nvidia-settings]]) можно изменить через файл конфигурации. Для применения изменений нужно будет перезапустить сервер Xorg.<br />
<br />
Подробности и доступные опции описаны в [https://download.nvidia.com/XFree86/Linux-x86_64/470.63.01/README/ NVIDIA Accelerated Linux Graphics Driver README and Installation Guide].<br />
<br />
==== Минимальная настройка ====<br />
<br />
Минимальный блок настроек {{ic|20-nvidia.conf}} может выглядеть так:<br />
<br />
{{hc|/etc/X11/xorg.conf.d/20-nvidia.conf|<br />
Section "Device"<br />
Identifier "Nvidia Card"<br />
Driver "nvidia"<br />
VendorName "NVIDIA Corporation"<br />
BoardName "GeForce GTX 1050 Ti"<br />
EndSection<br />
}}<br />
<br />
==== Отключение лого при запуске ====<br />
<br />
Добавьте {{ic|"NoLogo"}} в секцию {{ic|Device}}:<br />
<br />
Option "NoLogo" "1"<br />
<br />
==== Переопределение обнаружения монитора ====<br />
<br />
Опция {{ic|"ConnectedMonitor"}} в секции {{ic|Device}} позволяет переопределить обнаружение монитора при запуске X-сервера, что может сэкономить значительное количество времени при запуске. Доступными опциями являются: {{ic|"CRT"}} для аналоговых подключений, {{ic|"DFP"}} для цифровых мониторов и {{ic|"TV"}} для телевизоров.<br />
<br />
Следующая опция заставит драйвер NVIDIA обойти проверки при запуске и распознать монитор как DFP:<br />
<br />
Option "ConnectedMonitor" "DFP"<br />
<br />
{{Note (Русский)|Используйте "CRT" для всех аналоговых 15-контактных VGA-подключений, даже если дисплей является плоской панелью. "DFP" предназначен только для цифровых соединений DVI, HDMI или DisplayPort.}}<br />
<br />
==== Включение SLI ====<br />
<br />
{{Warning (Русский)|Начиная с серии GTX 10xx (1080, 1070, 1060 и т.д.) поддерживается только 2-way SLI. 3-way и 4-way SLI могут работать для приложений CUDA/OpenCL, но скорее всего сломают все приложения OpenGL.}}<br />
<br />
Взято из NVIDIA driver's [ftp://download.nvidia.com/XFree86/Linux-x86/355.11/README/xconfigoptions.html README] Appendix B: ''This option controls the configuration of SLI rendering in supported configurations.'' "Supported configuration" — это компьютер с материнской платой, имеющей сертификацию SLI и 2 или 3 GPU GeForce с сертификацией SLI.<br />
<br />
Найдите идентификатор PCI-шины первого GPU с помощью {{ic|lspci}}:<br />
<br />
{{hc|# lspci {{!}} grep "VGA{{!}}3D controller"|<br />
00:02.0 VGA compatible controller: Intel Corporation Xeon E3-1200 v2/3rd Gen Core processor Graphics Controller (rev 09)<br />
03:00.0 VGA compatible controller: NVIDIA Corporation GK107 [GeForce GTX 650] (rev a1)<br />
04:00.0 VGA compatible controller: NVIDIA Corporation GK107 [GeForce GTX 650] (rev a1)<br />
08:00.0 3D controller: NVIDIA Corporation GM108GLM [Quadro K620M / Quadro M500M] (rev a2)<br />
}}<br />
<br />
Добавьте BusID (в данном примере 3) в секцию {{ic|Device}}:<br />
<br />
BusID "PCI:3:0:0"<br />
<br />
{{Note (Русский)|Формат значения BusID должен быть таким: {{ic|"PCI:<BusID>:0:0"}}}}<br />
<br />
Добавьте нужное значение режима рендеринга SLI в секции {{ic|Screen}}:<br />
<br />
Option "SLI" "AA"<br />
<br />
Таблица доступных режимов рендеринга:<br />
<br />
{| class="wikitable"<br />
! Значение !! Поведение<br />
|-<br />
| 0, no, off, false, Single || Использовать только один GPU при рендеринге.<br />
|-<br />
| 1, yes, on, true, Auto || Включить SLI и позволить драйверу автоматически выбрать подходящий режим рендеринга.<br />
|-<br />
| AFR || Включить SLI и использовать режим рендеринга чередующихся кадров (alternate frame rendering mode).<br />
|-<br />
| SFR || Включить SLI и использовать режим рендеринга с разделением кадров (split frame rendering mode).<br />
|-<br />
| AA || Включить SLI и использовать сглаживание SLI. Используйте это в сочетании с полным сглаживанием сцены для улучшения качества изображения.<br />
|}<br />
<br />
Также можно использовать ''nvidia-xconfig'' для внесения этих изменений в {{ic|xorg.conf}} одной командой:<br />
<br />
# nvidia-xconfig --busid=PCI:3:0:0 --sli=AA<br />
<br />
Проверка режима SLI:<br />
<br />
{{hc|$ nvidia-settings -q all {{!}} grep SLIMode|<br />
Attribute 'SLIMode' (arch:0.0): AA <br />
'SLIMode' is a string attribute.<br />
'SLIMode' is a read-only attribute.<br />
'SLIMode' can use the following target types: X Screen.<br />
}}<br />
<br />
{{Warning (Русский)|После включения SLI система может зависнуть/не реагировать при запуске xorg. Рекомендуется отключить экранный менеджер перед перезагрузкой.}}<br />
<br />
Если эта конфигурация не работает, может понадобиться использовать PCI Bus ID, который выдаст {{ic|nvidia-settings}},<br />
<br />
{{hc|$ nvidia-settings -q all {{!}} grep -i pcibus|<br />
Attribute 'PCIBus' (host:0[gpu:0]): 101.<br />
'PCIBus' is an integer attribute.<br />
'PCIBus' is a read-only attribute.<br />
'PCIBus' can use the following target types: GPU, SDI Input Device.<br />
Attribute 'PCIBus' (host:0[gpu:1]): 23.<br />
'PCIBus' is an integer attribute.<br />
'PCIBus' is a read-only attribute.<br />
'PCIBus' can use the following target types: GPU, SDI Input Device.<br />
}}<br />
<br />
и закомментировать опцию Primary GPU в настройках xorg,<br />
<br />
{{hc|/usr/share/X11/xorg.conf.d/10-nvidia-drm-outputclass.conf|<br />
...<br />
<br />
Section "OutputClass"<br />
...<br />
# Option "PrimaryGPU" "yes"<br />
...<br />
}}<br />
<br />
Использование этой конфигурации также может решить проблемы с графической загрузкой.<br />
<br />
=== Несколько мониторов ===<br />
<br />
Смотрите [[Multihead]] для получения основной информации.<br />
<br />
==== Использование nvidia-settings ====<br />
<br />
Можно использовать [[#nvidia-settings|nvidia-settings]] для настройки нескольких мониторов.<br />
<br />
Для настройки через командную строку сперва узнайте {{ic|CurrentMetaMode}}:<br />
<br />
{{hc|$ nvidia-settings -q CurrentMetaMode|2=<br />
Attribute 'CurrentMetaMode' (hostnmae:0.0): id=50, switchable=no, source=nv-control :: DPY-1: 2880x1620 @2880x1620 +0+0 {ViewPortIn=2880x1620, ViewPortOut=2880x1620+0+0}<br />
}}<br />
<br />
Сохраните всё после символов {{ic|::}} и до конца атрибута (в данном примере {{ic|1=DPY-1: 2880x1620 @2880x1620 +0+0 {ViewPortIn=2880x1620, ViewPortOut=2880x1620+0+0}<nowiki/>}}) и используйте для перенастройки мониторов с помощью {{ic|1=nvidia-settings --assign "CurrentMetaMode=''your_meta_mode''"}}.<br />
<br />
{{Tip (Русский)|Вы можете создать псевдонимы в командной облочке для различных конфигураций мониторов и разрешений, которые вы используете.}}<br />
<br />
==== ConnectedMonitor ====<br />
<br />
Если драйвер не определил второй монитор, вы можете принудительно указать его с помощью опции ConnectedMonitor <br />
<br />
{{hc|/etc/X11/xorg.conf|<br />
<br />
Section "Monitor"<br />
Identifier "Monitor1"<br />
VendorName "Panasonic"<br />
ModelName "Panasonic MICRON 2100Ex"<br />
HorizSync 30.0 - 121.0 # this monitor has incorrect EDID, hence Option "UseEDIDFreqs" "false"<br />
VertRefresh 50.0 - 160.0<br />
Option "DPMS"<br />
EndSection<br />
<br />
Section "Monitor"<br />
Identifier "Monitor2"<br />
VendorName "Gateway"<br />
ModelName "GatewayVX1120"<br />
HorizSync 30.0 - 121.0<br />
VertRefresh 50.0 - 160.0<br />
Option "DPMS"<br />
EndSection<br />
<br />
Section "Device"<br />
Identifier "Device1"<br />
Driver "nvidia"<br />
Option "NoLogo"<br />
Option "UseEDIDFreqs" "false"<br />
Option "ConnectedMonitor" "CRT,CRT"<br />
VendorName "NVIDIA Corporation"<br />
BoardName "GeForce 6200 LE"<br />
BusID "PCI:3:0:0"<br />
Screen 0<br />
EndSection<br />
<br />
Section "Device"<br />
Identifier "Device2"<br />
Driver "nvidia"<br />
Option "NoLogo"<br />
Option "UseEDIDFreqs" "false"<br />
Option "ConnectedMonitor" "CRT,CRT"<br />
VendorName "NVIDIA Corporation"<br />
BoardName "GeForce 6200 LE"<br />
BusID "PCI:3:0:0"<br />
Screen 1<br />
EndSection<br />
<br />
}}<br />
<br />
Дублирование устройств с опцией {{ic|Screen}} описывает использование сервером Xorg двух мониторов на одной карте без технологии {{ic|TwinView}}. Учтите, что {{ic|nvidia-settings}} будет вырезать любое упоминание опции {{ic|ConnectedMonitor}}.<br />
<br />
==== TwinView ====<br />
<br />
Вы хотите только один большой экран вместо двух. Установите значение опции {{ic|TwinView}} в {{ic|1}}. Эта опция должна использоваться если вы хотите композитинга. Технология TwinView работает только на базе одной карты, когда все мониторы подключены к одной карте. <br />
Option "TwinView" "1"<br />
<br />
Пример конфигурации:<br />
<br />
{{hc|/etc/X11/xorg.conf.d/10-monitor.conf|<br />
Section "ServerLayout"<br />
Identifier "TwinLayout"<br />
Screen 0 "metaScreen" 0 0<br />
EndSection<br />
<br />
Section "Monitor"<br />
Identifier "Monitor0"<br />
Option "Enable" "true"<br />
EndSection<br />
<br />
Section "Monitor"<br />
Identifier "Monitor1"<br />
Option "Enable" "true"<br />
EndSection<br />
<br />
Section "Device"<br />
Identifier "Card0"<br />
Driver "nvidia"<br />
VendorName "NVIDIA Corporation"<br />
<br />
#refer to the link below for more information on each of the following options.<br />
Option "HorizSync" "DFP-0: 28-33; DFP-1: 28-33"<br />
Option "VertRefresh" "DFP-0: 43-73; DFP-1: 43-73"<br />
Option "MetaModes" "1920x1080, 1920x1080"<br />
Option "ConnectedMonitor" "DFP-0, DFP-1"<br />
Option "MetaModeOrientation" "DFP-1 LeftOf DFP-0"<br />
EndSection<br />
<br />
Section "Screen"<br />
Identifier "metaScreen"<br />
Device "Card0"<br />
Monitor "Monitor0"<br />
DefaultDepth 24<br />
Option "TwinView" "True"<br />
SubSection "Display"<br />
Modes "1920x1080"<br />
EndSubSection<br />
EndSection<br />
}}<br />
<br />
[https://download.nvidia.com/XFree86/Linux-x86_64/440.31/README/configtwinview.html Дополнительная информация о технологии TwinView (англ.)].<br />
<br />
Если вы имеете несколько карт, которые совместимы с технологией SLI, вы можете использовать несколько мониторов, присоединённых к разным картам (пример: две карты в режиме SLI с подключением монитора на каждой карте). Опция "MetaModes" совместно с режимом SLI Mosaic позволяет это. Ниже указана конфигурация, которая работает для вышеупомянутого примера и безупречно запускает [[GNOME (Русский)|GNOME]].<br />
<br />
{{hc|/etc/X11/xorg.conf.d/10-monitor.conf|<br />
Section "Device"<br />
Identifier "Card A"<br />
Driver "nvidia"<br />
BusID "PCI:1:00:0"<br />
EndSection<br />
<br />
Section "Device"<br />
Identifier "Card B"<br />
Driver "nvidia"<br />
BusID "PCI:2:00:0"<br />
EndSection<br />
<br />
Section "Monitor"<br />
Identifier "Right Monitor"<br />
EndSection<br />
<br />
Section "Monitor"<br />
Identifier "Left Monitor"<br />
EndSection<br />
<br />
Section "Screen"<br />
Identifier "Right Screen"<br />
Device "Card A"<br />
Monitor "Right Monitor"<br />
DefaultDepth 24<br />
Option "SLI" "Mosaic"<br />
Option "Stereo" "0"<br />
Option "BaseMosaic" "True"<br />
Option "MetaModes" "GPU-0.DFP-0: 1920x1200+4480+0, GPU-1.DFP-0:1920x1200+0+0"<br />
SubSection "Display"<br />
Depth 24<br />
EndSubSection<br />
EndSection<br />
<br />
Section "Screen"<br />
Identifier "Left Screen"<br />
Device "Card B"<br />
Monitor "Left Monitor"<br />
DefaultDepth 24<br />
Option "SLI" "Mosaic"<br />
Option "Stereo" "0"<br />
Option "BaseMosaic" "True"<br />
Option "MetaModes" "GPU-0.DFP-0: 1920x1200+4480+0, GPU-1.DFP-0:1920x1200+0+0"<br />
SubSection "Display"<br />
Depth 24<br />
EndSubSection<br />
EndSection<br />
<br />
Section "ServerLayout"<br />
Identifier "Default"<br />
Screen 0 "Right Screen" 0 0<br />
Option "Xinerama" "0"<br />
EndSection}}<br />
<br />
===== Vsync при использовании TwinView =====<br />
<br />
Если вы используете TwinView и вертикальную синхронизацию (опция "Sync to VBlank" в '''nvidia-settings'''), вы заметите, что только один экран корректно использует синхронизацию, если у вас нет двух одинаковых мониторов. Несмотря на то, что '''nvidia-settings''' имеет необходимую опцию для выбора, какой именно экран синхронизировать (опция "Sync to this display device"), это не всегда работает. Решением будет добавить следующие переменные окружения при запуске, например в {{ic|/etc/profile}}:<br />
<br />
export __GL_SYNC_TO_VBLANK=1<br />
export __GL_SYNC_DISPLAY_DEVICE=DFP-0<br />
export VDPAU_NVIDIA_SYNC_DISPLAY_DEVICE=DFP-0<br />
<br />
Вы можете изменить {{ic|DFP-0}} на ваш используемый монитор ({{ic|DFP-0}} это DVI порт, а {{ic|CRT-0}} - VGA порт). Идентификатор для вашего монитора можно найти с помощью '''nvidia-settings''' в секции "X Server XVideoSettings".<br />
<br />
===== Gaming using TwinView =====<br />
<br />
Если вы захотите сыграть в полноэкранные игры при использовании TwinView, вероятно вы заметите, что игры распознают два экрана как один большой экран. Хотя это технически правильно (виртуальный экран X в действительности соответствует размеру ваших экранов вместе), вы, вероятно, не захотите так играть.<br />
<br />
Чтобы исправить это для SDL, попробуйте:<br />
export SDL_VIDEO_FULLSCREEN_HEAD=1<br />
<br />
Для OpenGL, добавьте Metamodes в свой xorg.conf в секции {{ic|Device}} и перезапустите X:<br />
Option "Metamodes" "1680x1050,1680x1050; 1280x1024,1280x1024; 1680x1050,NULL; 1280x1024,NULL;"<br />
<br />
Еще один метод, который может работать самостоятельно, или в сочетании с упомянутыми выше: [[Gaming#Starting_games_in_a_separate_X_server|starting games in a separate X server]].<br />
<br />
==== Режим Mosaic ====<br />
<br />
Режим Mosaic единственный способ использовать более чем два монитора через несколько видеокарт с использованием композитинга. Ваш оконный менджер может распознать, а может и не распознать различия между мониторами.<br />
Режим Mosaic требует правильной конфигурации SLI. Даже если используется режим Base без SLI, видеокарты должны быть совместимы с SLI.<br />
<br />
===== Base Mosaic =====<br />
<br />
Режим Base Mosaic работает с картами Geforce 8000 series или выше. Его нельзя включить через графический интерфейс nvidia-setting. Вы должны использовать команду {{ic|nvidia-xconfig}}, либо отредактировать {{ic|xorg.conf}} самостоятельно. Опция Metamodes должна быть указана. Следующий пример для четырёх DFP мониторов в конфигурации 2х2, каждый запущен в разрешении 1920x1024, по два подключенных DFP монитора на две карты:<br />
$ nvidia-xconfig --base-mosaic --metamodes="GPU-0.DFP-0: 1920x1024+0+0, GPU-0.DFP-1: 1920x1024+1920+0, GPU-1.DFP-0: 1920x1024+0+1024, GPU-1.DFP-1: 1920x1024+1920+1024"<br />
<br />
{{Note (Русский)|Хотя в документации и указана конфигурация мониторов 2х2, [https://devtalk.nvidia.com/default/topic/579449/linux/basemosaic-v295-vs-v310-vs-v325-only-up-to-three-screens-/post/3954733/#3954733 карты GeForce имеют искусственное ограничение в 3 монитора]. Большее количество мониторов доступно в картах серии Quadro. С сентября 2014, Windows не имеет ограничение на количество мониторов с той же самой версией драйвера. Это не ошибка, так задумано по дизайну архитектуры.}}<br />
<br />
===== SLI Mosaic =====<br />
<br />
Если вы имеете конфигурацию SLI и все графические ускорители серии Quadro FX 5800, Quadro Fermi или новее, тогда вы можете использовать режим SLI Mosaic. он можеть быть включен из графического интерфейса nvidia-settings или из командной строки:<br />
$ nvidia-xconfig --sli=Mosaic --metamodes="GPU-0.DFP-0: 1920x1024+0+0, GPU-0.DFP-1: 1920x1024+1920+0, GPU-1.DFP-0: 1920x1024+0+1024, GPU-1.DFP-1: 1920x1024+1920+1024"<br />
<br />
== Wayland ==<br />
<br />
Смотрите [[Wayland (Русский)#Требования]].<br />
<br />
Дополнительные параметры конфигурации можно найти на страницах вики или в документации соответствующего композитора.<br />
<br />
Информацию об XWayland смотрите в разделе [[Wayland (Русский)#XWayland]].<br />
<br />
== Советы и рекомендации ==<br />
<br />
Смотрите [[NVIDIA/Советы и рекомендации]].<br />
<br />
== Смотрите также ==<br />
<br />
* [https://forums.developer.nvidia.com/t/current-graphics-driver-releases/28500 Информация о текущих версиях драйверов на официальном форуме Nvidia]<br />
* [https://forums.developer.nvidia.com/c/gpu-unix-graphics/linux/148 NVIDIA Developers Forum - Linux Subforum]</div>Garison