Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs custom indentation

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.

like image 446
canonv Avatar asked Nov 11 '10 19:11

canonv


People also ask

How do I set an indentation in Emacs?

This command, given anywhere on a line, positions point at the first nonblank character on the line. To insert an indented line before the current line, do C-a C-o TAB . To make an indented line after the current line, use C-e C-j . If you just want to insert a tab character in the buffer, you can type C-q TAB .

How do I set tabs in Emacs?

In text mode, it does relative indentation (relative to the previous line, that is). You can type C-q TAB to insert a tab character.

How many spaces is a tab in Emacs?

This is because standard tabs are set to eight spaces. Tabs are special characters.

How do I disable tabs in Emacs?

If you want to remove tabs in an existing file, mark the whole buffer using C-x h and use M-x untabify . ( M-x tabify does the opposite …)


1 Answers

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

like image 96
scottfrazer Avatar answered Nov 16 '22 01:11

scottfrazer