📜 ⬆️ ⬇️

Emacs and Python (Article 2 of the series)

According to the results of research work programmers about 20% of the time spent on direct writing code, and about 80% of the time - to view the old, its analysis. Based on this premise, the text editor must first provide convenient means of navigating through the code. Most of the described features deal with navigation and analysis.

In this article, I will try to demonstrate the maximum of the convenient in daily use of the features of the Emacs editor for the Python language, and more specifically for editing Django projects.

As the saying goes: “they have been waiting for the promised three years.” Although three years have not passed, there is already a good deal from my previous article , Emacs for Beginners: An Introduction . I will not “spread out across the tree to the tree,” but I will try to show as briefly as possible how the various Emacs features work as applied to Python.
')


Article format:


For those who are interested in applying the recipes entirely - my config is available (Mercurial) here , and here: a recipe for its use .

Content




1. Integrated documentation




Pretty handy feature. In any place, if you have forgotten any details on the documentation, you can call one of the options for displaying documentation:



I show these features separately as they are independent of each other.

1.1. Rope pydoc




Recipe of inclusion: according to the recipe of inclusion rope separate and talk and is described in:


After turning on the rope, its keybindings and menu start working:




1.2. Pylookup - an index of documentation on standard library Python




The package is installed from here: https://github.com/tsgates/pylookup . It has two active components: pylookup.el is placed in a directory readable by emacs for downloading Lisp, and pylookup.py is placed somewhere where it will be accessible along the way for the user.

Indexed as follows:
./pylookup.py -d /var/db/pylookup/pylookup.db -u /usr/share/doc/python-docs-2.*/html


In emacs, we set up a module load and a convenient key to call. I'm set up
on the keys Control + Shift + Menu .

Included as follows (see also: cfg_pylookup.el ):

(eval-when-compile (require 'pylookup)) (setq pylookup-program "/usr/local/bin/pylookup.py") (setq pylookup-db-file "/var/db/pylookup/pylookup.db") (global-set-key [(control shift menu)] 'pylookup-lookup) 




1.2.1. To index also Django documentation:




Install django-docs:

 cd ~/ svn co http://code.djangoproject.com/svn/django/trunk/docs/ django-docs cd django-docs make html cd _build/html ln -s genindex.html genindex-all.html 


And we supplement the command from above:

 ./pylookup.py -d /var/db/pylookup/pylookup.db -u /usr/share/doc/python-docs-2.*/html -u ~/django-docs/_build/html/ 




2. Python debugger: pdb




There is a wonderful pdbtrack module that “watches” movements on the program code during debugging on the n, s keys and others. And by the way, skilfully working with pdb can be achieved more than in similar visual debugging tools.

pdbtrack is automatically enabled with the inclusion of the main python-mode mode.

In order for it to be invoked in emacs, you need to put a line like:
import pdb; pdb.set_trace () in your code. The executable program must be executed in emacs / shell.



3. Rgrep




rgrep - fast search for a string in all files with a specific extension. Here it is worth noting that starting with the emacs 23.x version, the developers changed something in the call interface and now it’s impossible to separate the extensions with a space, such as [* .html * .py], if you don’t know the workaround:
to enter a space in rgrep - screen it with the Cq key

rgrep works surprisingly fast, and even in our largest project with tens of thousands of files it finds what it takes in a split second, which is important for frequent searches.

My rgrep is tied to a key: C-f7



4. Occur




occur shows the entry of this line in the current file. In order to make it convenient to call, I made a macro that automatically highlights the current word and then calls the occor on it. I have this function tied to the key: Cz o



5. Blocks in Emacs




Blocks are:


Also, blocks can be stored in different registers, respectively, you can work with different blocks at the same time.



5.1. Multiple blocks



Yes. It is not used very often, but when applied, it saves you a lot of time that would have been spent up-and-down on klipper / parcellite or even worse (if you have one clipboard).

Keys:



5.1. Square blocks



5.1.1. Visual square blocks

The visual mode is activated by the C-enter button. A rectangular area appears in which you can fill in the text, delete,
or copy the whole rectangle. In this mode, all stantadnye buttons work with the block - Alt + Y to remember
block and ctrl + y to paste.

5.1.2. Non-visual square blocks


There is a second variant of square blocks, somewhat trimmed, but working for the terminal mode. It works like this:
select the block as usual (C-space) but at the same time work with the block by keys:



5.2. View kill ring


Some convenient replacement of a named block is the klipper analog built into emacs, called killring:

 (require 'browse-kill-ring) (global-set-key (kbd "Cc k") 'browse-kill-ring) 


5.3. Tangled situation with blocks and copy keys



It is worth noting that the situation with blocks and key bindings to operations is confused by several objective, historical
reasons:



As a result, often even such a trivial thing as copying in blocks becomes difficult to master.
emacs.

It also adds to the fire that in the xorg true way to copy blocks: Control Insert to copy and Shift Insert
to embed the block. In this case, the mouse copies to one clipboard and keyboard selections fall into another.

For starters, I often advise you to master the “True Way” right away and not try to turn on the so-called cua-mode, designed to free the Cc Cv
standard emacs key bindinds, depriving the end user of the mass of convenient functionality. If you really study emacs, then learn
two additional keys:


not a super problem. For those for whom it is - turn on Cua-mode boldly and work further, but most likely you don’t care
Return to the topic and return the standard keys when you feel that there are not enough convenient keyboard shortcuts.

6. Yasnippet - input automation with snippets




Yasnippet is a convenient way to automate the input of frequent, but difficult to memorize, blocks of text.



It is installed as an independent emacs package, usually available in the repository of your system.

Configured as:

 (add-to-list 'load-path "/usr/share/emacs/site-lisp/yasnippet") (autoload 'yas/initialize "yasnippet" "Do necessary initialization.") (autoload 'yas/load-directory "yasnippet" "Load snippet definition from a directory hierarchy." t) (require 'yasnippet) ;; not yasnippet-bundle (yas/initialize) (yas/load-directory "/usr/share/emacs/etc/yasnippet/snippets") (yas/load-directory "~/.emacs.d/yasnippets/") (setq hippie-expand-try-functions-list (cons 'yas/hippie-try-expand hippie-expand-try-functions-list)) (global-set-key [(\t)] 'indent-for-tab-command) (setq yas/trigger-key (kbd "Mn")) 


7. Navigating the python code




7.1. Up-down functions


Keys:




Configuration:
 (defun py-to-start-of-class() (interactive) (py-beginning-of-def-or-class 'class) ) (defun py-to-end-of-class() (interactive) (py-end-of-def-or-class 'class) ) (add-hook 'python-mode-hook '(lambda () (local-set-key [(s menu)] 'rope-code-assist) (local-set-key [(s up)] 'python-move-to-start-of-class) (local-set-key [(s down)] 'python-move-to-end-of-class) (local-set-key [(meta down)] 'py-end-of-def-or-class) (local-set-key [(meta up)] 'py-beginning-of-def-or-class) (local-set-key (kbd "Cc Ca") 'py-to-start-of-class) (local-set-key (kbd "Cc Ce") 'py-to-end-of-class) (local-set-key (kbd "sq") 'py-shift-region-left) (local-set-key (kbd "sw") 'py-shift-region-right) ) ) 


7.2. By function and class of the current file via IM-python




Keys (works not only in pyhon, but in general there are many):


Definition look here: idomenu.el



7.3. By functions and classes of the current file via Speedbar




I set up the Scroll_Lock key:
 (global-set-key [Scroll_Lock] 'speedbar) 




7.4. Transition to the place of definition of a variable [class, method]




Configured via Rope and bookmark on the keys:




The disadvantage of setup is that the record of the conversion history is global and each transition leaves trash in bookmarks,
You will need to rewrite this point in Lisp with an array. But while working and so.

 (defun rope-goto-definition-save-place () """ save current place as 'save-place' bookmark and rope-goto-definition """ (interactive) (bookmark-set "save-place" 1) (rope-goto-definition) ) (defun rope-return () """ save current place as 'save-place' bookmark and rope-goto-definition """ (interactive) (bookmark-jump "save-place") ) (global-set-key [(M return)] 'rope-goto-definition-save-place) (global-set-key [(M shift return)] 'rope-return) 


7.5. Bookmarks







 (require 'bm) (global-set-key (kbd "Cz b") 'bm-toggle) (global-set-key (kbd "Cz <up>") 'bm-previous) (global-set-key (kbd "Cz Cp") 'bm-previous) ;(global-set-key [(control shift down)] 'bm-next) ;(global-set-key [(control shift n)] 'bm-next) (global-set-key (kbd "Cz <down>") 'bm-next) (global-set-key (kbd "Cz Cn") 'bm-next) (global-set-key (kbd "Cz <SPC>") 'bm-show-all) 


7.6. Search file by name pattern



Works in any mode, not directly related to Python, just a handy feature. Called by:


 (global-set-key [(control shift f)] 'find-name-dired) 




7.7. Open project file: rope-file-find




Very convenient, especially to open a linked file, for example a template file for view in Django.




8. Working with python text


8.1. Python Ident left / right








8.2. Fighting blank text







 (define-key global-map "C-zws" 'show-trailing-whitespace) (define-key global-map "C-zwh" 'hide-trailing-whitespace) (define-key global-map "C-zwd" 'delete-trailing-whitespace) 


8.3. Visualization of line length excess




Installed by:
 (make-face 'mode-line-80col-face) 




8.4. Autocompletions




8.4.1. Autocomplete Rope




Starts working with the installation of Rope.



8.4.2. Hippie-expand autocompletions




  <span style = "color: # 66cc66;"> (</ span> global-set-key <span style = "color: # ff0000;"> "M-" </ span> 'hippie-expand <span style = "color: # 66cc66;">) </ span>




8.5. Comments in the text








 (global-set-key [(control \#)] 'comment-or-uncomment-region) (global-set-key [(control shift z)] 'comment-or-uncomment-region) 


 ; hippie expand (global-set-key "\M- " 'hippie-expand) 


9. Code quality testing




9.1. Flymake integration: pyflymake




To support flymake integration, you will need to install pyflakes, pylint packages and configure their location in your
copy file:

pyflymake.py
And also install this Lisp code:
cfg_flymake.el



Unfortunately, even after a lot of processing, this solution is not ideal. Sometimes flymake writes _flymake files out of place on
network services, sometimes just incorrectly fulfills. But in fact in 98% of cases it is very useful as it allows
find out earlier made mistake.

9.2. call pep8




The module is installed in the system: pep8.



 ; pep8 (require 'python-pep8) (global-set-key (kbd "Cc p 8") 'pep8) 


9.3. pylint call




Similarly. First, install the pylint system package and then:

 ; pylint (require 'python-pylint) (global-set-key (kbd "Cc p l") 'pylint) 




10. Django specificity




1) It is necessary to start the project from django-shell - in order to have pdb available.
2) There are several different modules for the syntax display django templates.



11. Compilation mode for python and quick start.



Anywhere in the python program, if this is a stand-alone script, you can run it through the Cc Cc key.
When an error is generated in this case, the cursor will be replaced with the error.

Option number two: run the program from the compile option. In my config, it is configured as:

 (global-set-key [C-f9] 'compile) 


In the case of using the compile function, you can use the F8 / Shift-F8 error traversal.

In both cases, the pdb call will not work and the programs will start without a link to the terminal.



12. In conclusion




What is not included in this article



I tried to describe the features most related to editing Python files. Many are not included in this review, although they are directly related to working with the Python project, for example, such a feature as working with a version control system - it deserves a separate article, which I intend to do in the [near future].

The article is not finished, as comments arrive, I will definitely make changes and additions.

What do I expect from reader comments :


PS The sound quality was disappointing, I wrote using ffmpeg -vf crop = 970: 505: 7: 15 -f alsa -i hw: 0 -f x11grab -r 25 -s 1680x1050 -i: 0.0 -s 1280x720 -vcodec libx264 -vpre lossless_ultrafast filename.avi and
on the microphone on the laptop. First, the keystrokes are loud, secondly the sound is quiet and sometimes there is extraneous noise. Alas ... Maybe I will retake the video using
headset, but so far there is - that is. Better so than without them at all, right?

Source: https://habr.com/ru/post/151167/


All Articles