Skip to content

Instantly share code, notes, and snippets.

@brianloveswords
Last active May 18, 2019 03:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianloveswords/e23cedf3a80bab675fe5 to your computer and use it in GitHub Desktop.
Save brianloveswords/e23cedf3a80bab675fe5 to your computer and use it in GitHub Desktop.
An enhanced newline function for use with smartparens-mode.

I use smartparens-mode so when I type { I get {} with the cursor inbetween the two braces. I realized that more or less 100% of the time I called newline-and-indent when the cursor was between curly braces what I really wanted was to create a block and have my cursor be in the middle of that block, e.g.

let object = {}

after:

let object = {}

I was manually doing the whole newline-and-indent, split-line and indent-for-tab-command dance but then I realized I use emacs and I should probably just write some elisp to fix it so I did.

(defun my-fancy-newline ()
"Add two newlines and put the cursor at the right indentation
between them if a newline is attempted when the cursor is between
two curly braces, otherwise do a regular newline and indent"
(interactive)
(if (and (equal (char-before) 123) ; {
(equal (char-after) 125)) ; }
(progn (newline-and-indent)
(split-line)
(indent-for-tab-command))
(newline-and-indent)))
;; I set mine to C-j, you do you, don't let me tell you how to live your life.
(global-set-key (kbd "C-j") 'my-fancy-newline)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment