I use emacs for development and very often need to move to the start of a line (C-a). However if the line is indented, I\'d like to move to the point at which code st
Common idiom among modern IDE is to move at the first/last non-whitespace on second press:
(defun my--smart-beginning-of-line ()
"Move point to `beginning-of-line'. If repeat command it cycle
position between `back-to-indentation' and `beginning-of-line'."
(interactive "^")
(if (and (eq last-command 'my--smart-beginning-of-line)
(= (line-beginning-position) (point)))
(back-to-indentation)
(beginning-of-line)))
(defun my--smart-end-of-line ()
"Move point to `end-of-line'. If repeat command it cycle
position between last non-whitespace and `end-of-line'."
(interactive "^")
(if (and (eq last-command 'my--smart-end-of-line)
(= (line-end-position) (point)))
(skip-syntax-backward " " (line-beginning-position))
(end-of-line)))
(global-set-key [home] 'my--smart-beginning-of-line)
(global-set-key [end] 'my--smart-end-of-line)
This code firstly move to actual begin/end, new behavior show up on subsequent presses. So any old keyboard macros will work as expected!
I do the same toggling trick as Trey, but defaulting to indentation instead of to beginning of line. It takes slightly more code because there's no "at-beginning-of-indentation" function that I know of.
(defun smart-line-beginning ()
"Move point to the beginning of text on the current line; if that is already
the current position of point, then move it to the beginning of the line."
(interactive)
(let ((pt (point)))
(beginning-of-line-text)
(when (eq pt (point))
(beginning-of-line))))
This will probably let you continue to use Ctrl-a and have it do what you want most often, while still being able to get the built-in behavior easily.
By default, Meta-m runs back-to-indentation which according to the documentation will "Move point to the first non-whitespace character on this line."
Meta-m
A favorite way for me to handle this is to have C-a toggle between the beginning of the line and the beginning of the code. You can do so with this function:
(defun beginning-of-line-or-indentation ()
"move to beginning of line, or indentation"
(interactive)
(if (bolp)
(back-to-indentation)
(beginning-of-line)))
And add the appropriate binding to your favorite mode map:
(eval-after-load "cc-mode"
'(define-key c-mode-base-map (kbd "C-a") 'beginning-of-line-or-indentation))