Emacs custom indentation

ぐ巨炮叔叔 提交于 2019-12-22 04:01:21

问题


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.


回答1:


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




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!