Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs command to insert and indent line above cursor

Tags:

emacs

elisp

I frequently find myself typing on a line, when I realize I need(ed) a variable definition (or something similar) on the line above. What I would like is to

  1. press C-return from anywhere on a line and have the cursor move to a newly inserted blank line above, with correct indentation (or at least the same as the original line).
  2. be able to yank any text...
  3. and C-u C-space to get back to the original position

I've managed to do #1, but my emacs-fu isn't strong enough to do the rest.

like image 567
thebjorn Avatar asked Mar 07 '09 20:03

thebjorn


People also ask

How do I add a new line in emacs?

Insert the line to ". emacs" file. <C + S + Return> that means <Ctrl + Shift + Enter> for new line above. Both will indent also.

What is the command to insert text before the cursor in emacs?

To insert printing characters into the text you are editing, just type them. This inserts the characters you type into the buffer at the cursor (that is, at point; see section Point). The cursor moves forward, and any text after the cursor moves forward too.


2 Answers

Here's my humble solution:

(defun my-insert-before-line ()
  (interactive)
  (save-excursion
    (beginning-of-line)
    ; I've changed the order of (yank) and (indent-according-to-mode)
    ; in order to handle the case when yanked line comes with its own indent
    (yank)(indent-according-to-mode)
    ; could be as well changed to simple (newline) it's metter of taste
    ; and of usage
    (newline-and-indent)))

Hope it helps.

like image 134
Serge Avatar answered Oct 19 '22 13:10

Serge


Here's what you can do if you are not a Zen master emacs dude.

Emacs has a record-macro thing, kmacro-start-macro and kmacro-end-macro.

After recording your macro, do name-last-kbd-macro. then visit .emacs, and do insert-kbd-macro.

You then have an fset statement that defines your macro. It may look funny, and it is not as maintainable as elisp, but if you stuff it into your .emacs, that macro (by that name) will be available to any of your editing sessions. And you can bind it to a key sequence as well.

like image 41
Cheeso Avatar answered Oct 19 '22 12:10

Cheeso