My team uses a special type of file for configuration, and I would like to auto-indent (block indent) the file using emacs.
I would like to increase the indentation by a tab size for an opening parenthesis - { or [, and decrease by a tab size for a closing parenthesis - } or ] .
For example,
files = {
file1 = first_file.txt
file2 = second_file.txt
rules = {
skip_header = 1
fast_process = 1
}
}
C-style indentation doesn't work since a line doesn't end with semi-colon.
I have studied about emacs indentation for half a day today, but still doesn't know how to do this.
Derive a new mode from text-mode or something and create your own indentation function. I know it's easier said than done, so this might be close enough:
(define-derived-mode foo-mode text-mode "Foo"
"Mode for editing some kind of config files."
(make-local-variable 'foo-indent-offset)
(set (make-local-variable 'indent-line-function) 'foo-indent-line))
(defvar foo-indent-offset 4
"*Indentation offset for `foo-mode'.")
(defun foo-indent-line ()
"Indent current line for `foo-mode'."
(interactive)
(let ((indent-col 0))
(save-excursion
(beginning-of-line)
(condition-case nil
(while t
(backward-up-list 1)
(when (looking-at "[[{]")
(setq indent-col (+ indent-col foo-indent-offset))))
(error nil)))
(save-excursion
(back-to-indentation)
(when (and (looking-at "[]}]") (>= indent-col foo-indent-offset))
(setq indent-col (- indent-col foo-indent-offset))))
(indent-line-to indent-col)))
Open your file and do M-x foo-mode
It looks to me as though javascript-mode
would do the right thing with your sample. It might not be perfect, but a lot easier than writing your own indentation mode.
来源:https://stackoverflow.com/questions/4158216/emacs-custom-indentation