简体   繁体   中英

Python Predefined Auto-Import in Emacs

Here is an import example from Selenium Python Bindings Library Documentation :

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

These two imports are used a lot. Is there a way to do the following:

  • Define "from selenium.webdriver.common.by import By" as auto-import suggestion somewhere
  • Have auto-complete suggestions after typing "By." even without importing
  • Selecting a suggestion given after typing "By." creates an import as in the first code block?

I use yasnippet for a similar thing:

# -*- mode: snippet -*-
# contributor: jpkotta
# name: from __future__ import ...
# key: future
# --
from __future__ import print_function, division, unicode_literals, absolute_import

You can make a pretty simple command to do this if you don't want to bother with yasnippet:

(defun insert-foo ()
  (interactive)
  (let ((str "foo"))
    (save-excursion
      (save-restriction
        (widen)
        (goto-char (point-min))
        (unless (search-forward-regexp (concat "^" (regexp-quote str)) nil t)
          (goto-char (point-min))
          (while (and (looking-at (concat "^" comment-start))
                    (not (eobp)))
            (forward-line 1))
          (insert str))))))

This is smart enough to skip comments at the beginning of the buffer and is idempotent, but will not run automatically. You could write a command to search for another string "By." and run the insert command if it's found, and then add it to eg python-mode-hook or before-save-hook .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM