Emacs: Why major mode is not set correctly when file is opened?

时间:2016-11-09 06:56:38

标签: emacs major-mode python.el

Why major mode is not automatically set to python-mode when I open a .py file (emacs test.py)? Some parts of my .emacs that deal with python are:

(setq
 python-shell-interpreter "ipython"
 python-shell-interpreter-args "--gui=wx --matplotlib=wx --colors=Linux"
)

(defun my-eval-after-load-python()
    (setq initial-frame-alist '((top . 48) (left . 45) (width . 142) (height . 57)))
    (split-window-horizontally (floor (* 0.49 (window-width))))
    (other-window 1)
    (run-python (python-shell-parse-command))
    (python-shell-switch-to-shell)
    (other-window 1)
)
(eval-after-load "python" '(my-eval-after-load-python))

Left window should display the ipython shell and right window the opened file test.py. Everything works but test.py is in fundamental-mode and actually the scratch buffer is set to python-mode.

EDIT

Well, the problem is just the way my eval function deals with windows and buffers, so that this code treats the major-modes correctly:

(defun my-eval-after-load-python()
  (setq initial-frame-alist '((top . 48) (left . 45) (width . 142) (height . 57)))
  (split-window-horizontally (floor (* 0.49 (window-width))))
  (run-python (python-shell-parse-command))
)
(eval-after-load "python" '(my-eval-after-load-python))

The left window shows foo.py (in python-mode) and right window displays the scratch buffer (in text-mode). There are also the message buffer and a python shell buffer (inferior-python-mode). Now it's just a matter of opening the inferior-python-mode on the left window and the foo.py on the right window.

3 个答案:

答案 0 :(得分:2)

好的,所以你告诉Emacs查找文件一些foo.py文件,Emacs将其读入一个新的fundamental-mode缓冲区,然后调用python-mode

这是一个自动加载,所以首先它必须加载python.el,然后你的eval-after-load启动并开始搞乱选定的缓冲区。

之后,python-mode实际上被调用了 - 但是您已经选择了其他缓冲区,因此该缓冲区启用了模式,并且foo.py保持基本模式。

将代码包装在save-current-buffer中是一个明智的开始,但您可能还希望在操作中更明确,而不是依靠other-window来做您想做的事。

答案 1 :(得分:2)

首先从基础开始。摆脱你的python相关配置。重新启动emacs并查看是否打开.py文件在python-mode中打开它。

如果这不起作用,请检查auto-mode-alist的值。这是一个关联列表,其中列表的每个元素是一个cons单元,其中car是键,cdr是与该键相关联的值。这些cons细胞通常被写成“点对”,即(键值)。因此,auto-mode-alist只是一个关联列表,其中每个关联用于将文件名模式与emacs模式相关联。文件名模式通常表示为正则表达式。

当您在emacs中打开文件时,它将检查auto-mode-alist以查看是否有任何键(正则表达式)与文件名匹配。如果匹配,则emacs将在加载文件后启动该模式。如果没有匹配项,emacs将默认使用基本模式。

所以,如果你发现当你打开一个名字以扩展名.py结尾的文件时,emacs没有把缓冲区放在python模式下,最可能的原因是没有auto-mode-alist条目与您正在使用的文件名匹配的键。

我没有用python编程,但是我在系统上注意到,我的自动模式列表中有以下条目

("\\.pyw?\\'" . python-mode)

当我打开test.py时,我的emacs以python-mode打开文件。

让这一点工作或验证它在一个vanilla emacs中工作。如果不是,则添加相应的条目,测试它是否有效,然后添加回配置。

如果你发现它正常工作,直到你添加你的设置功能,然后回来,我们可以看看该功能。你定义你的函数的方式有点混乱,当然可以改进,但没有明显的跳出来作为一个问题,这就是为什么我想看看是否只是打开pythong文件没有任何其他python设置的东西工作。

答案 2 :(得分:0)

根据When window is split on startup, how to open the file on the right side?中给出的接受答案,我能够实现所需的行为:

{{1}}