use-package manual

Table of Contents

1 概览

use-package 可以用来将 package 配置从 .emacs 文件按中分离出来,这样做既不影响性能,而且更整洁。

2 The basics(基本使用)

Here is the simplest use-package declaration:

下面是最简单的 use-package 声明:

(use-package foo)

This loads in the package foo, but only if foo is available on your system. If not, a warning is logged to the Messages buffer. If it succeeds, a message about "Loading foo" is logged, along with the time it took to load, if it took over 0.1s.

这会加载 package foo,但只有系统存在该包的时候才会加载成功。如果不存在,一个警告会记录在 Message buffer 中。如果成功,会记录一个关于“loading foo”的信息,如果加载超过 0.1s,与之伴随的还有加载所耗时长。

Use the :init keyword to execute code before a package is loaded. It accepts one or more forms, up until the next keyword:

使用 :init 在加载包之前执行代码。它接受一个或多个表,直到遇到下个关键字:

(use-package foo
  :init
  (setq foo-variable t))

Similarly, :config can be used to execute code after a package is loaded. In cases where loading is done lazily (see more about autoloading below), this execution is deferred until after the autoload occurs:

同样, :config 可以在加载包后执行代码。在延迟加载的情况下(参阅自动加载了解更多信息),该执行也会延迟直到发生自动加载之后:

(use-package foo
  :init
  (setq foo-variable t)
  :config
  (foo-mode 1))

As you might expect, you can use :init and :config together:

如你所料, :init:config 可以一起使用:

(use-package color-moccur
  :commands (isearch-moccur isearch-all)
  :bind (("M-s O" . moccur)
         :map isearch-mode-map
         ("M-o" . isearch-moccur)
         ("M-O" . isearch-moccur-all))
  :init
  (setq isearch-lazy-highlight t)
  :config
  (use-package moccur-edit))

In this case, I want to autoload the commands isearch-moccur and isearch-all from color-moccur.el, and bind keys both at the global level and within the isearch-mode-map (see next section). When the package is actually loaded (by using one of these commands), moccur-edit is also loaded, to allow editing of the moccur buffer.

上面这种情况是想从 color-moccur.el 中自动加载 isearch-moccur 和 isearch-all,并在全局和 isearch-mode-map 中进行键绑定。当该包实际加载时(使用这些命令中的一个),moccur-edit 也会加载,用来编辑 moccur buffer。

3 Key-binding(键绑定)

Another common thing to do when loading a module is to bind a key to primary commands within that module:

另一个常见的事情是将一个模块的加载绑定到该模块的主要命令上:

(use-package ace-jump-mode
  :bind ("C-." . ace-jump-mode))

This does two things: first, it creates an autoload for the ace-jump-mode command and defers loading of ace-jump-mode until you actually use it. Second, it binds the key C-. to that command. After loading, you can use M-x describe-personal-keybindings to see all such keybindings you've set throughout your .emacs file.

这会做两件事情:首先为 ace-jump-mode 命令创建自动加载,延迟加载 ace-jump-mode 直到实际使用它的时候。其次,将 C-. 绑定到该命令。加载之后,可以使用 M-x describe-personal-keybindings 查看到.emacs 文件中这样设置的所有键绑定。

A more literal way to do the exact same thing is:

一种更文字的方式可以做同样的事情:

(use-package ace-jump-mode
  :commands ace-jump-mode
  :init
  (bind-key "C-." 'ace-jump-mode))

When you use the :commands keyword, it creates autoloads for those commands and defers loading of the module until they are used. Since the :init form is always run – even if ace-jump-mode might not be on your system – remember to restrict :init code to only what would succeed either way.

当使用 :commands 关键字,它为这些命令创建自动加载,并在实际使用这些模块的时候才加载它们。因为 :init 表总是运行 — 即使系统中并不存在 ace-jump-mode — 记住限制 :init 代码去做无论如何都会成功的事情。

The :bind keyword takes either a cons or a list of conses:

:bind 关键字需要一个 cons 或者一个 conses 的列表:

(use-package hi-lock
  :bind (("M-o l" . highlight-lines-matching-regexp)
         ("M-o r" . highlight-regexp)
         ("M-o w" . highlight-phrase)))

The :commands keyword likewise takes either a symbol or a list of symbols.

:commands 关键字同样需要一个符号,或一个符号列表。

NOTE: special keys like tab or F1-Fn are written in square brackets, i.e. [tab] instead of "tab".

注意:像制表符或 F1-Fn 这样的特殊键要卸载中括号中,比如 [tab] 而不是"tab".

4 Binding to keymaps(绑定到键映射)

Normally :bind expects that commands are functions that will be autoloaded from the given package. However, this does not work if one of those commands is actually a keymap, since keymaps are not functions, and cannot be autoloaded using Emacs' autoload mechanism.

通常 :bind 期待的命令是从给定 package 中自动加载的函数。然而,如果这些命令中的一个如果实际上是键映射的话,这就不工作,因为键映射不是函数,不能使用 Emacs 的自动加载机制进行自动加载。

To handle this case, use-package offers a special, limited variant of :bind called :bind-keymap. The only difference is that the "commands" bound to by :bind-keymap must be keymaps defined in the package, rather than command functions. This is handled behind the scenes by generating custom code that loads the package containing the keymap, and then re-executes your keypress after the first load, to reinterpret that keypress as a prefix key.

为了处理这种情况,use-package 提供了 :bind 一个特殊的、受限的变种叫做 :bind-keymap. 二者之间的区别是 :bind-keymap 绑定的命令必须是包中定义的键映射,而不是命令函数。背后通过生成订制代码来加载包含键映射的包,然后第一次加载之后再次执行键盘按键,将该按键解释为一个前缀键。

5 Binding within local keymaps(绑定到局部键映射)

Slightly different from binding a key to a keymap, is binding a key within a local keymap that only exists after the package is loaded. use-package supports this with a :map modifier, taking the local keymap to bind to:

绑定按键到局部键映射和绑定一个按键到键映射稍微不同的是该绑定只有在加载包之后才会存在。use-package 通过 :map 修饰符支持局部键绑定:

(use-package helm
  :bind (:map helm-mode-map
         ("C-c h" . helm-execute-persistent-action)))

The effect of this statement is to wait until helm has loaded, and then to bind the key C-c h to helm-execute-persistent-action within Helm's local keymap, helm-mode-map.

上面声明的效果是等到加载 helm 后,在 helm 的局部键映射 helm-mode-map 中将 C-c h 绑定到 helm-execute-persistent-action。

Multiple uses of :map may be specified. Any binding occurring before the first use of :map are applied to the global keymap:

可能会使用多个 :map 。第一个 :map 之前的任何绑定都应用于全局键映射。

(use-package term
  :bind (("C-c t" . term)
         :map term-mode-map
         ("M-p" . term-send-up)
         ("M-n" . term-send-down)
         :map term-raw-map
         ("M-o" . other-window)
         ("M-p" . term-send-up)
         ("M-n" . term-send-down)))

6 Modes and interpreters(模式和解释器)

Similar to :bind, you can use :mode and :interpreter to establish a deferred binding within the auto-mode-alist and interpreter-mode-alist variables. The specifier to either keyword can be a cons cell, a list, or just a string:

类似 :bind ,可以使用 :mode:interpreter 在变量 auto-mode-alist 和 interpreter-mode-alist 中建立延迟键绑定。关键字的说明符可以是一个 cons cell,一个列表或一个字符串。

(use-package ruby-mode
  :mode "\\.rb\\'"
  :interpreter "ruby")

;; The package is "python" but the mode is "python-mode":
(use-package python
  :mode ("\\.py\\'" . python-mode)
  :interpreter ("python" . python-mode))

If you aren't using :commands, :bind, :bind*, :bind-keymap, :bind-keymap*, :mode, or :interpreter (all of which imply :defer; see the docstring for use-package for a brief description of each), you can still defer loading with the :defer keyword:

如果不使用 :commands, :bind, :bind*, :bind-keymap, :bind-keymap*, :mode, or :interpreter (这些都意味着 :defer ; 参阅 use-package 中的文档字符串了解每个的简要描述),也可以使用 :defer 关键字实现延迟加载:

(use-package ace-jump-mode
  :defer t
  :init
  (autoload 'ace-jump-mode "ace-jump-mode" nil t)
  (bind-key "C-." 'ace-jump-mode))

This does exactly the same thing as the following:

同样的事情可以这样做:

(use-package ace-jump-mode
  :bind ("C-." . ace-jump-mode))

7 Notes about lazy loading(延迟加载的注意事项)

In almost all cases you don't need to manually specify :defer t. This is implied whenever :bind or :mode or :interpreter is used. Typically, you only need to specify :defer if you know for a fact that some other package will do something to cause your package to load at the appropriate time, and thus you would like to defer loading even though use-package isn't creating any autoloads for you.

大多数情况下不需要手动指定 :defer 为 t。使用 :bind or :mode or :interpreter 就包含了这层意思。通常,如果知道其他 packge 会做一些事情导致你的包在适当的时间加载才需要指定 :defer, 因此想要延迟加载,即使 use-package 不会为你创建任何自动加载。

You can override package deferral with the :demand keyword. Thus, even if you use :bind, using :demand will force loading to occur immediately and not establish an autoload for the bound key.

可以使用 :demand 关键字覆盖包的延迟加载。因此,即使使用 :bind, using :demand 也会强制立即发生加载,不会为绑定键建立任何自动加载。

8 Information about package loads

When a package is loaded, and if you have use-package-verbose set to t, or if the package takes longer than 0.1s to load, you will see a message to indicate this loading activity in the Messages buffer. The same will happen for configuration, or :config blocks that take longer than 0.1s to execute. In general, you should keep :init forms as simple and quick as possible, and put as much as you can get away with into the :config block. This way, deferred loading can help your Emacs to start as quickly as possible.

包加载之后,如果将 use-package-verbose 设置为 t,或者包加载耗时超过 0.1s,就会在 *Messages* buffer 中看到指示加载活动的信息。配置也是同样的,或者 :config 块执行超过 0.1s。通常, :init 应该尽可能简单和迅速,在 :config 块中放尽可能多的东西。通过这种方式,延迟加载可以帮助 Emacs 尽可能快的启动。

Additionally, if an error occurs while initializing or configuring a package, this will not stop your Emacs from loading. Rather, the error will be captured by use-package, and reported to a special Warnings popup buffer, so that you can debug the situation in an otherwise functional Emacs.

此外,如果初始化或配置包的时候发生了错误,不会阻止 Emacs 继续加载。相反,use-package 会捕获到该错误,并在 *Warnings* popup buffer 中报告,这样就可以在原本功能的 Emacs 调试这种情况。

9 Conditional loading

You can use the :if keyword to predicate the loading and initialization of modules. For example, I only want edit-server running for my main, graphical Emacs, not for other Emacsen I may start at the command line:

可以使用 :if 关键字处理模块的加载和初始化。例如,只想 edit-server 运行于图形 Emacs 中,而不是其他从命令行启动的 Emacsen:

(use-package edit-server
  :if window-system
  :init
  (add-hook 'after-init-hook 'server-start t)
  (add-hook 'after-init-hook 'edit-server-start t))

The :disabled keyword can turn off a module you're having difficulties with, or stop loading something you're not using at the present time:

:disabled 关键字可以关闭一个对你而言有困难的模块,或者停用当前不会用到的东西:

(use-package ess-site
  :disabled t
  :commands R)

When byte-compiling your .emacs file, disabled declarations are ommitted from the output entirely, to accelerate startup times.

字节编译.emacs 文件时,为了加速启动,输出中会删除素有禁用的声明。

10 Byte-compiling your .emacs(编译 .emacs 文件)

Another feature of use-package is that it always loads every file that it can when .emacs is being byte-compiled. This helps to silence spurious warnings about unknown variables and functions.

use-package 另一个特点是如果字节编译了.emacs 文件,它将尽可能加载每个文件。这有助于静默位置变量和函数引起的假警告

However, there are times when this is just not enough. For those times, use the :defines and :functions keywords to introduce dummy variable and function declarations solely for the sake of the byte-compiler:

然而,有时这是不够的。这时,使用 :defines:functions 关键字仅仅为字节编译器引入哑变量和函数声明。

(use-package texinfo
  :defines texinfo-section-list
  :commands texinfo-mode
  :init
  (add-to-list 'auto-mode-alist '("\\.texi$" . texinfo-mode)))

If you need to silence a missing function warning, you can use :functions:

如果需要静默一个丢失函数的警告,可以使用 :function :

(use-package ruby-mode
  :mode "\\.rb\\'"
  :interpreter "ruby"
  :functions inf-ruby-keys
  :config
  (defun my-ruby-mode-hook ()
    (require 'inf-ruby)
    (inf-ruby-keys))

  (add-hook 'ruby-mode-hook 'my-ruby-mode-hook))

11 Prevent a package from loading at compile-time(编译时阻止加载包)

Normally, use-package will load each package at compile time before compiling the configuration, to ensure that any necessary symbols are in scope to satisfy the byte-compiler. At times this can cause problems, since a package may have special loading requirements, and all that you want to use use-package for is to add a configuration to the eval-after-load hook. In such cases, use the :no-require keyword, which implies :defer:

通常,编译时,use-package 在编译配置之前加载每个包,以确保满足字节编译器的任何必要的符号都在作用域中。有时这会导致问题,因为一个包可能有特殊加载要求,为此 use-package 可以做的是为 eval-after-load hook 添加一个配置。这种情况下,使用 :no-require 关键字,这意味着 :defer

(use-package foo
  :no-require t
  :config
  (message "This is evaluated when `foo' is loaded"))

12 Extending the load-path(扩展 load-path)

If your package needs a directory added to the load-path in order to load, use :load-path. This takes a symbol, a function, a string or a list of strings. If the path is relative, it is expanded within user-emacs-directory:

为了包为了加载需要将一个目录添加到 load-path 中,使用 :load-path 。这需要一个符号,函数,字符串或字符串的列表。如果是相对路径,使用 user-emacs-directory 进行扩展。

(use-package ess-site
  :load-path "site-lisp/ess/lisp/"
  :commands R)

Note that when using a symbol or a function to provide a dynamically generated list of paths, you must inform the byte-compiler of this definition so the value is available at byte-compilation time. This is done by using the special form eval-and-compile (as opposed to eval-when-compile). Further, this value is fixed at whatever was determined during compilation, to avoid looking up the same information again on each startup:

注意使用一个符号或函数提供动态生成的路径列表,必须告知字节编译器该定义,这样该值在编译时可用。这是通过使用特殊形式 eval-and-compile (而不是 eval-when-compile)实现的。进一步说,无论是否在编译,该值都是固定的,为了避免在每次启动的时候查找相同的信息:

(eval-and-compile
  (defun ess-site-load-path ()
    (shell-command "find ~ -path ess/lisp")))

(use-package ess-site
  :load-path (lambda () (list (ess-site-load-path)))
  :commands R)

13 Diminishing minor modes(diminish 辅助模式)

use-package also provides built-in support for the diminish utility – if you have that installed. Its purpose is to remove strings from your mode-line that provide no useful information. It is invoked with the :diminish keyword, which is passed either a minor mode symbol, a cons of the symbol and its replacement string, or just a replacement string, in which case the minor mode symbol is guessed to be the package name with "-mode" appended at the end:

use-package 还为 diminsh utility 提供了内置支持 — 如果安装的话。它的目的是从模式行删除提供无用信息的字符串。 使用 :diminish 关键字,它需要一个辅助模式符号,一个符号 cons 和替代字符串,或者指示替代符串,这种情况下,辅助模式符号被猜测为包名末尾加上“-mode""。

(use-package abbrev
  :diminish abbrev-mode
  :config
  (if (file-exists-p abbrev-file-name)
      (quietly-read-abbrev-file)))

14 For package.el users(对于 package.el 用户)

You can use use-package to load packages from ELPA with package.el. This is particularly useful if you share your .emacs among several machines; the relevant packages are downloaded automatically once declared in your .emacs. The :ensure keyword causes the package(s) to be installed automatically if not already present on your system。set (setq use-package-always-ensure t) if you wish this behavior to be global for all packages):

可以使用 use-package 配合 package.el 从 ELPA 加载包。这对于在多个机器之间共享.emacs 很有用;一旦在.emacs 中声明,相关的包都会下载。 如果系统上没有, :ensure 关键字会自动安装。如果对所有包都这样处理,这样设置:(setq use-package-always-ensure t)

(use-package magit
  :ensure t)

If you need to install a different package from the one named by use-package, you can specify it like this:

如果想要安装一个与 use-package 命名不同的包,可以这样指定:

(use-package tex-site
  :ensure auctex)

Lastly, when running on Emacs 24.4 or later, use-package can pin a package to a specific archive, allowing you to mix and match packages from different archives. The primary use-case for this is preferring packages from the melpa-stable and gnu archives, but using specific packages from melpa when you need to track newer versions than what is available in the stable archives is also a valid use-case.

最后,如果运行于 Emacs 24.4 或更高版本,use-package 可以将一个包 pin 到特定的档案,允许从不同的档案混合和匹配包。主要使用场景是相比 gnu 更喜欢来自 melpa-stable 档案的包,但是当需要跟踪稳定档案的更新版本时,使用来自 melpa 指定的包也是一个有效的用例。

By default package.el prefers melpa over melpa-stable due to the versioning (> evil-20141208.623 evil-1.0.9), so even if you are tracking only a single package from melpa, you will need to tag all the non-melpa packages with the appropriate archive. If this really annoys you, then you can set use-package-always-pin to set a default.

默认情况下 package.el 由于版本更喜欢 melpa 而不是 melpa-stable,所以即使只从 melpa 跟踪一个包,也需要使用合适的档案标记所有其他非 melpa 的包。如果觉得这很烦,可以为 use-package-always-pin 设置一个默认的。

If you want to manually keep a package updated and ignore upstream updates, you can pin it to manual, which as long as there is no repository by that name, will Just Work(tm).

如果想手动保持更新一个包,忽略上游更新,可以将其 pin 到 manual,只要没有改名字的容器,这就会有效。

use-package throws an error if you try to pin a package to an archive that has not been configured using package-archives (apart from the magic manual archive mentioned above):

如果尝试 pin 一个包到没有使用 package-archives 配置的档案(除了上面提到的魔法档案),use-package 将会抛出错误。

Archive 'foo' requested for package 'bar' is not available.

Example:

(use-package company
  :ensure t
  :pin melpa-stable)

(use-package evil
  :ensure t)
  ;; no :pin needed, as package.el will choose the version in melpa

(use-package adaptive-wrap
  :ensure t
  ;; as this package is available only in the gnu archive, this is
  ;; technically not needed, but it helps to highlight where it
  ;; comes from
  :pin gnu)

(use-package org
  :ensure t
  ;; ignore org-mode from upstream and use a manually installed version
  :pin manual)

NOTE: the :pin argument has no effect on emacs versions < 24.4.

注意:pin 参数对于版本小于 24.4 的 emacs 无效。

15 Extending use-package with new or modified keywords

Starting with version 2.0, use-package is based on an extensible framework that makes it easy for package authors to add new keywords, or modify the behavior of existing keywords.

15.1 First step: Add the keyword

The first step is to add your keyword at the right place in use-package-keywords. This list determines the order in which things will happen in the expanded code. You should never change this order, but it gives you a framework within which to decide when your keyword should fire.

15.2 Second step: Create a normalizer

Define a normalizer for your keyword by defining a function named after the keyword, for example:

(defun use-package-normalize/:pin (name-symbol keyword args)
  (use-package-only-one (symbol-name keyword) args
    (lambda (label arg)
      (cond
       ((stringp arg) arg)
       ((symbolp arg) (symbol-name arg))
       (t
        (use-package-error
         ":pin wants an archive name (a string)"))))))

The job of the normalizer is take a list of arguments (possibly nil), and turn it into the single argument (which could still be a list) that should appear in the final property list used by use-package.

15.3 Third step: Create a handler

Once you have a normalizer, you must create a handler for the keyword:

(defun use-package-handler/:pin (name-symbol keyword archive-name rest state)
  (let ((body (use-package-process-keywords name-symbol rest state)))
    ;; This happens at macro expansion time, not when the expanded code is
    ;; compiled or evaluated.
    (if (null archive-name)
        body
      (use-package-pin-package name-symbol archive-name)
      (use-package-concat
       body
       `((push '(,name-symbol . ,archive-name)
               package-pinned-packages))))))

Handlers can affect the handling of keywords in two ways. First, it can modify the state plist before recursively processing the remaining keywords, to influence keywords that pay attention to the state (one example is the state keyword :deferred, not to be confused with the use-package keyword :defer). Then, once the remaining keywords have been handled and their resulting forms returned, the handler may manipulate, extend, or just ignore those forms.

The task of each handler is to return a list of forms representing code to be inserted. It does not need to be a progn list, as this is handled automatically in other places. Thus it is very common to see the idiom of using use-package-concat to add new functionality before or after a code body, so that only the minimum code necessary is emitted as the result of a use-package expansion.

15.4 Fourth step: Test it out

After the keyword has been inserted into use-package-keywords, and a normalizer and a handler defined, you can now test it by seeing how usages of the keyword will expand. For this, temporarily set use-package-debug to t, and just evaluate the use-package declaration. The expansion will be shown in a special buffer called use-package.

16 Some timing results

On my Retina iMac, the "Mac port" variant of Emacs 24.4 loads in 0.57s, with around 218 packages configured (nearly all of them lazy-loaded). However, I experience no loss of functionality, just a bit of latency when I'm first starting to use Emacs (due to the autoloading). Since I also use idle-loading for many packages, perceived latency is typically reduced overall.

On Linux, the same configuration loads in 0.32s.

If I don't use Emacs graphically, I can test the absolute minimum times. This is done by running:

time emacs -l init.elc -batch --eval '(message "Hello, world!")'

On the Mac I see an average of 0.36s for the same configuration, and on Linux 0.26s.

17 Upgrading to 2.x

17.1 Semantics of :init is now consistent

The meaning of :init has been changed: It now always happens before package load, whether :config has been deferred or not. This means that some uses of :init in your configuration may need to be changed to :config (in the non-deferred case). For the deferred case, the behavior is unchanged from before.

Also, because :init and :config now mean "before" and "after", the :pre- and :post- keywords are gone, as they should no longer be necessary.

Lastly, an effort has been made to make your Emacs start even in the presence of use-package configuration failures. So after this change, be sure to check your Messages buffer. Most likely, you will have several instances where you are using :init, but should be using :config (this was the case for me in a number of places).

17.2 :idle has been removed

I am removing this feature for now because it can result in a nasty inconsistency. Consider the following definition:

(use-package vkill
  :commands vkill
  :idle (some-important-configuration-here)
  :bind ("C-x L" . vkill-and-helm-occur)
  :init
  (defun vkill-and-helm-occur ()
    (interactive)
    (vkill)
    (call-interactively #'helm-occur))

  :config
  (setq vkill-show-all-processes t))

If I load my Emacs and wait until the idle timer fires, then this is the sequence of events:

:init :idle <load> :config

But if I load Emacs and immediately type C-x L without waiting for the idle timer to fire, this is the sequence of events:

:init <load> :config :idle

It's possible that the user could use featurep in their idle to test for this case, but that's a subtlety I'd rather avoid.

17.3 :defer now accepts an optional integer argument

:defer [N] causes the package to be loaded -- if it has not already been -- after N seconds of idle time.
(use-package back-button
  :commands (back-button-mode)
  :defer 2
  :init
  (setq back-button-show-toolbar-buttons nil)
  :config
  (back-button-mode 1))

17.4 Add :preface, occurring before everything except :disabled

:preface can be used to establish function and variable definitions that will 1) make the byte-compiler happy (it won't complain about functions whose definitions are unknown because you have them within a guard block), and 2) allow you to define code that can be used in an :if test.

Note that whatever is specified within :preface is evaluated both at load time and at byte-compilation time, in order to ensure that definitions are seen by both the Lisp evaluator and the byte-compiler, so you should avoid having any side-effects in your preface, and restrict it merely to symbol declarations and definitions.

17.5 Add :functions, for declaring functions to the byte-compiler

What :defines does for variables, :functions does for functions.

17.6 use-package.el is no longer needed at runtime

This means you should put the following at the top of your Emacs, to further reduce load time:

(eval-when-compile
  (require 'use-package))
(require 'diminish)                ;; if you use :diminish
(require 'bind-key)

Author: lsl

Created: 2017-08-30 三 16:06

Emacs 25.2.2 (Org mode 8.2.10)

Validate