Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get auto indent (not smart indent) in emacs in all modes

I'm new to emacs, and its indenting is driving me up the walls. It's too smart for its own good; it (incorrectly) thinks it knows how I want to format my source, but I don't have time to chase down every setting for every mode for every different language that I write code for; and many of those languages don't have any mode enabled at all.

Here's the behaviour I'd like:

  • TAB inserts indent
  • RET inserts a new line then copies the blank characters from the start of the previous line to the first non-blank character, or end of line, whichever comes sooner
  • DEL (backspace key) in the blank text between line start and first non-blank character / end of line deletes one indent if possible, otherwise single character like normal
  • No auto-indent on {
  • No auto-unindent on }
  • In fact, no smart-ass indenting behaviour anywhere anytime, just copy previous line's indent on RET.
  • Two variables to be configured per source file format: display tab width, and contents of indent. Preferably these can be configured for random source code formats without having to write a major mode for them, unless writing a major mode is a one-liner in .emacs, consisting of two setqs.

This would get me logical and consistent behaviour across all languages. It would leave the work of formatting the code to me, but that's OK, I've been doing that for 20 years, and I know how to make other macros that make it efficient. More importantly, it saves me from endless fiddling with configuration settings trying to get the automatic behaviour to suit my preferences. And my macros can rely on consistent behaviour so they work correctly in all modes.

Is the above possible? Surely someone else has done this before? Is there some minor mode out there that makes it so?

like image 338
Barry Kelly Avatar asked Sep 22 '13 15:09

Barry Kelly


1 Answers

Here's the code:

(setq tab-width 4)
(defun plain-tab ()
  (interactive)
  (insert (make-string tab-width ?\ )))
(defun plain-ret ()
  (interactive)
  (looking-back "^\\( +\\).*")
  (newline)
  (insert (match-string 1)))
(defun plain-del ()
  (interactive)
  (backward-delete-char
   (if (looking-back (format " \\{%d\\}" tab-width)) tab-width 1)))
(defvar all-the-mode-maps
  '(c-mode-map c++-mode-map java-mode-map
    js-mode-map emacs-lisp-mode-map
    clojure-mode-map))
(require 'cc-mode)
(require 'js)
(require 'clojure-mode)
(eval `(mapc 
        (lambda(map)
          (define-key map [tab] 'plain-tab)
          (define-key map [return] 'plain-ret)
          (define-key map [backspace] 'plain-del)
          (define-key map "{" (lambda()(interactive)(insert "{")))
          (define-key map "}" (lambda()(interactive)(insert "}"))))
        (list ,@all-the-mode-maps)))
like image 92
abo-abo Avatar answered Sep 22 '22 00:09

abo-abo