emacs lisp, how to get buffer major mode?

2019-01-16 12:24发布

I have tried to search Google and look in the manual, but still cannot find how to get major mode of a buffer object. Can you help me with an example or a reference. Thanks

only solution I could find was to query major-mode after changing the buffer and then changing back to original buffer. Is there a better way to do it?

6条回答
▲ chillily
2楼-- · 2019-01-16 12:38

A simple way to do this is to use the buffer-local-value function since major-mode is a buffer-local variable:

(buffer-local-value 'major-mode (get-buffer "*scratch*"))
查看更多
\"骚年 ilove
3楼-- · 2019-01-16 12:53

Just extending from previous answers - call with no arguments to get the current buffer's mode:

(defun buffer-mode (&optional buffer-or-name)
  "Returns the major mode associated with a buffer.
If buffer-or-name is nil return current buffer's mode."
  (buffer-local-value 'major-mode
   (if buffer-or-name (get-buffer buffer-or-name) (current-buffer))))

E.g. in *scratch* buffer:

(buffer-mode) => 'lisp-interaction-mode

(buffer-mode "tasks.org") => 'org-mode
查看更多
The star\"
4楼-- · 2019-01-16 12:53

Simply evaluate this:

(print major-mode)
查看更多
Explosion°爆炸
5楼-- · 2019-01-16 12:54

Is there a problem with that?

(defun buffer-mode (buffer-or-string)
  "Returns the major mode associated with a buffer."
  (with-current-buffer buffer-or-string
     major-mode))

with-current-buffer will restore your buffer when it returns.

查看更多
对你真心纯属浪费
6楼-- · 2019-01-16 12:54

For current buffer:

(message "%s" major-mode)
查看更多
冷血范
7楼-- · 2019-01-16 12:57

Well, describe-mode takes an optional buffer argument, but that displays the help... and I'm not exactly sure what it returns...

But that's the best I could find in a brief search... sorry...

查看更多
登录 后发表回答