简体   繁体   中英

Emacs command to insert and indent line above cursor

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 Cu 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.

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.

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.

Probably bad form to answer my own question, but Cheeso's answer motivated me to do some lisp programming for the second time in ten years (my original version was a named keyboard macro, but it stepped all over the kill/mark-rings). Here's what I came up with

(defun insert-and-indent-line-above ()
  (interactive)
  (push-mark)
  (let* 
    ((ipt (progn (back-to-indentation) (point)))
     (bol (progn (move-beginning-of-line 1) (point)))
     (indent (buffer-substring bol ipt)))
    (newline)
    (previous-line)
    (insert indent)))

(global-set-key [ (control return) ] 'insert-and-indent-line-above)

there are probably many better ways of doing this, but two hours of lisp-hacking can hardly be called wasted time:-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM