Getting Started with Sourcery for Emacs¶
Installation¶
- Install the lsp-mode LSP client for Emacs.
- Install the sourcery pypi package with
pip install sourcery
. Note down the application path e.g./path/to/sourcery
orC:\path\to\sourcery.exe
- Login with
sourcery login
- 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 all refactorings or a specific type of refactoring for a function.
- Add a comment
# sourcery skip
to a function to skip all reactorings for that function - Add a comment
# sourcery skip: <refactoring-id>
to a function to skip the specific refactoring in that function. A full list of refactorings and their IDs are available at Current Refactorings.
Advanced Features¶
There are more advanced ways you can improve your code with a Sourcery Pro or Sourcery Team subscription:
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.