Emacs函数在Python模式下为__all__添加符号?

时间:2009-05-13 20:50:43

标签: python emacs

是否有现有的Emacs函数在编辑Python代码时将当前符号下的符号添加到__all__

例如,假设光标位于o中的第一个foo

#    v---- cursor is on that 'o'
def foo():
    return 42

如果您执行了 M-x python-add-to-all (或其他),则会将'foo'添加到__all__

当我用Google搜索时,我没有看到一个,但是,一如既往,也许我错过了一些明显的东西。

更新

我尝试了Trey Jackson's answer(谢谢,Trey!)并进行了一些修复/改进,以防任何人感兴趣(不再双重插入,并将__all__置于更典型的位置如果它还不存在):

(defun python-add-to-all ()
  "Take the symbol under the point and add it to the __all__
list, if it's not already there."
  (interactive)
  (save-excursion
    (let ((thing (thing-at-point 'symbol)))
      (if (progn (goto-char (point-min))
                 (let (found)
                   (while (and (not found)
                               (re-search-forward (rx symbol-start "__all__" symbol-end
                                                      (0+ space) "=" (0+ space)
                                                      (syntax open-parenthesis))
                                                  nil t))
                     (setq found (not (python-in-string/comment))))
                   found))
          (when (not (looking-at (rx-to-string
                                  `(and (0+ (not (syntax close-parenthesis)))
                                        (syntax string-quote) ,thing (syntax string-quote)))))
            (insert (format "\'%s\', " thing)))
        (beginning-of-buffer)
        ;; Put before any import lines, or if none, the first class or
        ;; function.
        (when (not (re-search-forward (rx bol (or "import" "from") symbol-end) nil t))
          (re-search-forward (rx symbol-start (or "def" "class") symbol-end) nil t))
        (forward-line -1)
        (insert (format "\n__all__ = [\'%s\']\n" thing))))))

1 个答案:

答案 0 :(得分:10)

不是python程序员,我不确定这涵盖所有情况,但在一个简单的情况下适合我。如果数组存在,它将向数组添加符号,如果不存在,则创建__all__注意:它不会解析数组以避免双重插入。

(defun python-add-to-all ()
  "take the symbol under the point and add to the __all__ routine"
  (interactive)
  (save-excursion
    (let ((thing (thing-at-point 'word))
          p)
      (if (progn (goto-char (point-min))
                 (re-search-forward "^__all__ = \\[" nil t))
          (insert (format "\"%s\", " thing))
        (goto-char (point-min))
        (insert (format "__all__ = [\"%s\"]\n" thing))))))