简体   繁体   中英

Indent code in org-babel src blocks

In an org-mode file, with code like the following:

#+begin_src emacs-lisp
(add-to-list 'org-tab-before-tab-emulation-hook
             (lambda ()
               (when (within-the-body-of-a-begin-src-block)
                 (indent-for-tab-command--as-if-in-lisp-mode))))
#+end_src

I would like the TAB key to indent the code as it would if it were in a buffer in lisp mode.

What I need is:

  • A way to figure out whether the cursor is within a src block. It needs to not trigger when on the header line itself, as in that case the default org folding should take place.
  • A way to indent the code according to the mode (emacs-lisp in this case) specified in the header.

Org can already syntax highlight src blocks according to mode, and the TAB hooks are there. This looks do-able.

Since Emacs 24.1 you can now set the following option:

(setq org-src-tab-acts-natively t)

...and that should handle all src blocks.

Just move point into the code block and press Cc '

This will pop up a buffer in elisp-mode, syntax higlighting ad all...

Here's a rough solution:

(defun indent-org-src-block-line ()
  "Indent the current line of emacs lisp code."
  (interactive)
  (let ((info (org-babel-get-src-block-info 'light)))
    (when info
      (let ((lang (nth 0 info)))
        (when (string= lang "emacs-lisp")
          (let ((indent-line-function 'lisp-indent-line))
            (indent-for-tab-command)))))))

(add-to-list 'org-tab-before-tab-emulation-hook
             'indent-org-src-block-line)

It only handles emacs-lisp blocks. I've only tested with the src block un-indented (not the org default).

It is tough in general to make one mode work inside another - many keyboard commands will conflict. But some of the more basic strokes, like tab for indent, newline, commenting (org will comment the lisp code with #, which is wrong) seem like they could be made to work and would have the largest impact.

(defun my/org-cleanup ()
  (interactive)
  (org-edit-special)
  (indent-buffer)
  (org-edit-src-exit))

should do it, where `indent-buffer' is defined as:

(defun indent-buffer ()
  (interactive)
  (indent-region (point-min) (point-max)))

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