3

C-e C-j will insert a newline below and jump to it indented. C-a C-o TAB will insert a newline above and jump to it indented.

Is there a single bind to these or where/how should I bind these commands?

1 Answer 1

6

You can always check what function some keys are bound to using C-h k. For example, if we type C-h k C-e, we see that it is bound to (move-end-of-line ARG); similarly, C-j is bound to (newline-and-indent).

In this case, it turns out that C-e C-j is a sequence of two commands rather than a single thing. (The same with C-a C-o TAB.) To bind this to a single key, we first have to wrap it in a function. You can define this function in your .emacs file:

(defun my-newline-below ()
  "Insert a newline below and jump to it indented."
  (interactive)
  (move-end-of-line nil)
  (newline-and-indent))

All this function does is run the two commands we found. The string on top is just some documentation, and (interactive) is needed so that you can bind it to a key (or call it directly from M-x). move-end-of-line takes an argument, so we just pass in nil to get the default behavior. Happily, the output of C-h k tells us we can do this, so we don't have to guess what ARG is for.

Now we can just globally set this to some key:

(global-set-key (kbd "C-M-j") 'my-newline-below)

And voilà: the first command you wanted, bound to C-M-j. Now you can do the second one the same way, which is a great exercise to learn how to define your own custom commands like this.

2
  • Great!, can you also suggest me sample mappings for these commands, eg. what do you use @TikhonJelvis? Nov 11, 2014 at 18:40
  • @user3995789: Euh, that's actually pretty tricky. I don't use those particular commands myself, and have a bunch of custom mappings already. In fact, looking at it, C-M-j is already bound to something, it's just something I don't use. You'll have to look around for some free keybindings on your own setup; traditionally, ones in the form C-c a where a can be any letter are reserved for your customizations, but I've found they're a bit awkward to type. Nov 11, 2014 at 18:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.