4

When I'm editing a markdown-mode document with a list like this:

* foo
* bar
  * baz

and my cursor is at the very end of the baz line, and I press RET (which is bound to markdown-enter-key) then the baz line gets dedented so the file looks like this:

* foo
* bar
* baz

But what I would like is for the indentation to behave like most programming modes, i.e. keep baz where it was, and on the newline align my cursor with the baz bullet point so I can start typing another bullet point at that level, e.g.

* foo
* bar
  * baz
  * 

How can I configure my emacs to do this?

jml
  • 161
  • 3
  • 3
    Try `M-RET` ('markdown-insert-list-item'). – xuchunyang Aug 09 '15 at 14:30
  • @xuchunyang That's the answer, why not make it one :) – Kaushal Modi Aug 09 '15 at 23:16
  • 1
    That works, thanks, but I'd like to make `RET` do that (or that without the `*`). – jml Aug 10 '15 at 08:58
  • Personally I am satisfied with using one extra specific key `M-RET` to indent list items, instead of trying to make `RET` to do different things base on context (but that context is probably not enough and will produces ambiguity and instability, for example, when to start and end a list is unexpected, which means you always have to do it manually). But I do know some markdown editors (e.g., https://github.com/uranusjr/macdown) do what you requested, so I guess you can try to implement it yourself and/or talk to the markdown-mode author. – xuchunyang Aug 10 '15 at 12:25

1 Answers1

1

I made a new command for your request, the idea is:

  • when the point is outside a list, just insert a newline as usual
  • when the point is inside a list
    • if the current list is empty, delete it and insert a newline
    • otherwise, insert a new list item
(defun markdown-enter-key-dwim ()
  (interactive)
  (require 'subr-x)                     ; Needs Emacs 24.4
  (if-let ((bounds (markdown-cur-list-item-bounds))
           (beg (car bounds)) (end (cadr bounds))
           (text (buffer-substring beg end)))
      (if (and (>= (length text) 2)
               (string-blank-p
                (substring text 2)))
          (progn
            ;; Delete current blank list
            (kill-region beg end)
            ;; Insert RET
            (markdown-enter-key))
        ;; Create a new list
        (call-interactively #'markdown-insert-list-item))
    ;; Not within a list environment
    (markdown-enter-key)))

(require 'markdown-mode)
(define-key markdown-mode-map2 (kbd "RET") #'markdown-enter-key-dwim)

Notes, markdown-enter-key-dwim is not well-tested (probably too aggressive) and needs future work. The built-in M-RET (markdown-insert-list-item) is still handy enough for me, maybe you can just use it as well.

xuchunyang
  • 14,302
  • 1
  • 18
  • 39