Skip to content

Getting Started with Sourcery for Emacs

Installation

  1. Install the lsp-mode LSP client for Emacs.
  2. Install the sourcery pypi package with pip install sourcery. Note down the application path e.g. /path/to/sourcery or C:\path\to\sourcery.exe
  3. Login with sourcery login. When using Sourcery on an open source project you do not need to log in, but you'll need to for non-open source projects.
  4. Add the following code to your emacs config:
(lsp-register-client
 (make-lsp-client :new-connection (lsp-stdio-connection '("<Command to run Sourcery>" "lsp"))
                  :initialization-options '((extension_version . "emacs-lsp")
                                            (editor_version . "emacs"))
                  :activation-fn (lsp-activate-on "python")
                  :server-id 'sourcery
                  :add-on? t
                  :priority 2))

Seeing Your First Suggestions

Sourcery scans the currently open Python file. If lsp-modeline-diagnostics-mode is enabled it highlights the relevant lines of code with improvements.

When on a suggestion line, you can hover to see the suggestion, and run the code action to refactor that code.

You can also try out Sourcery by copying this code into a Python file in Emacs:

def merge_nested_if(a, b):
    if a:
        if b:
            return c

Sourcery will suggest merging together the nested if statements so you get:

def merge_nested_if(a, b):
    if a and b:
        return c

Accept a Suggestion

When on a suggestion line, you can hover to see the suggestion, and run the code action to refactor that code.

Skip a Suggestion

When on a suggestion line, you can hover to see it, and run the code action to skip it if you don't like it.

You can also tell Sourcery not to suggest anything or a specific type of rule for a function.

  • Add a comment # sourcery skip to a function to skip all rules for that function

  • Add a comment # sourcery skip: <rule-id> to a function to skip the specific rule in that function. A full list of rules and their IDs are available at:

  • Python Rules.

  • JavaScript Rules.

Extract Duplicate Code Into Methods

Sourcery will automatically detect opportunities for repeated or nearly repeated sections of code within a function to be extracted out into their own methods. When these refactorings are suggested, the new methods will be given a generic name based on the function it was extracted from and you can easily rename it.

Configuring Sourcery

See our section on Configuring Sourcery for details on customizing your Sourcery configuration.