Search code examples
emacsorg-modeaquamacs

in org-mode, how to protect stars from deletion?


I use org-mode in org-indent-mode, meaning all the stars but one are hidden, but the levels retain their indentation, creating an outline-type effect.

When I'm editing, I always seem to accidentally delete the space between the star and the text. Which means that this:

gets all messed up and turns into this:

Or sometimes, even worse, I even delete the space AND one or more of the stars. Then I have to figure out where I am and try to reenter the right number of stars to get me back to the right level, which is a pain.

This question might be against the spirit of org-mode, but is there a way to "protect" the stars and the space after them, such that when I hit delete multiple times, it sends me back up to the previous line of text rather than deleting the stars?


Solution

  • Here's the code:

    (defun new-org-delete-backward-char (N)
      (interactive "p")
      (if (not (looking-back "[*]+ "))
          (org-delete-backward-char N)
        (previous-line)
        (end-of-line)))
    
    (add-hook 
     'org-mode-hook
     (lambda ()
       (define-key org-mode-map (kbd "DEL") 
         'new-org-delete-backward-char)))
    

    I was messing up my outlines too, before I've defined org-speed-commands-user to do stuff like insert heading up, down etc. Maybe you'd like to try that instead. Also, this is quite useful:

    (define-key org-mode-map (kbd "C-a")
                  (lambda()(interactive)
                    (if (looking-at "^[^*]")
                        (re-search-backward "^*")
                      (org-beginning-of-line))))
    

    It brings you to the beginning of heading once you're already at the beginning of line, when you press C-a.

    UPD

    This version has provisioning for deleting region and goes to the end of the line:

    (defun new-org-delete-backward-char (N)
      (interactive "p")
      (cond ((region-active-p)
             (delete-region
              (region-beginning)
              (region-end)))
            ((looking-back "[*]+ ")
             (previous-line)
             (end-of-line))
            (t
             (org-delete-backward-char N))))