Search code examples
emacsmajor-modepython.el

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


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.


Solution

  • Based on the accepted answer given in When window is split on startup, how to open the file on the right side? I was able to implement the desired behavior:

    (defun my-eval-after-load-python (buffer alist direction &optional size pixelwise)
      (setq initial-frame-alist '((top . 44) (left . 18) (width . 135) (height . 49)))
      (let ((window
            (cond
            ((get-buffer-window buffer (selected-frame)))
            ((window-in-direction direction))
            (t (split-window (selected-window) size direction pixelwise))
            )
           ))
       (window--display-buffer buffer window 'window alist display-buffer-mark-dedicated) 
       (run-python (python-shell-parse-command))
       (other-window 1) 
       (python-shell-switch-to-shell) 
       (select-window window)
      )
    )
    
    (eval-after-load "python" '(my-eval-after-load-python (current-buffer) nil 'right (floor (* 0.49 (window-width)))))