Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
(defun line-starts-with-words (words)
(save-excursion
(back-to-indentation)
(and (not (nth 3 (syntax-ppss)))
(not (nth 4 (syntax-ppss)))
(member (current-word) words))))
(defun is-line-empty ()
(save-excursion
(end-of-line)
(eq (point) (line-beginning-position))))
(defun my-py-calculate-indentation (orig-fun &rest args)
(if (and (save-excursion (previous-line) (is-line-empty))
(not (save-excursion (forward-line) (is-line-empty))))
(save-excursion (forward-line) (current-indentation))
(apply orig-fun args)))
(advice-add 'my-py-calculate-indentation
:around
'python-indent-calculate-indentation)
(defun my-py-auto-indent-to (indent)
(indent-line-to (min indent (python-indent-calculate-indentation))))
(defun my-py-auto-indent-after-newline (prev-indent from-up)
(let ((prev-empty (save-excursion (previous-line) (is-line-empty)))
(next-empty (save-excursion (forward-line) (is-line-empty))))
(if from-up
(if prev-empty
(if next-empty
(my-py-auto-indent-to prev-indent)
(my-py-auto-indent-to (save-excursion
(forward-line)
(current-indentation))))
(indent-for-tab-command))
(if (and (not prev-empty)
next-empty)
(indent-for-tab-command)
(my-py-auto-indent-to prev-indent)))))
(defun my-py-newline-and-autoindent ()
(interactive)
(let ((curr-indent (current-indentation)))
(if (< (point) (+ (line-beginning-position) (current-indentation)))
(progn
(delete-horizontal-space)
(newline)
(indent-line-to curr-indent))
(newline)
(my-py-auto-indent-after-newline curr-indent t)
(save-excursion
(previous-line)
(end-of-line)
(delete-horizontal-space)))))
(defun my-py-newline-at-above ()
(interactive)
(let ((curr-indent (current-indentation)))
(end-of-line)
(delete-horizontal-space)
(beginning-of-line)
(newline)
(previous-line)
(my-py-auto-indent-after-newline curr-indent nil)))
(defun my-py-newline-at-below ()
(interactive)
(let ((curr-indent (current-indentation)))
(end-of-line)
(delete-horizontal-space)
(newline)
(my-py-auto-indent-after-newline curr-indent t)))
(defun insert-and-indent ()
(interactive)
(self-insert-command 1)
(indent-for-tab-command))
(setq py-indent-offset 2)
(setq python-indent 2)
(setq py-closing-list-dedents-bos t)
(setq py-start-run-py-shell nil)
(bind-keys :map python-mode-map
("C-o" . my-py-newline-at-below)
("C-M-o" . my-py-newline-at-above)
("RET" . my-py-newline-and-autoindent)
(")" . insert-and-indent)
("]" . insert-and-indent)
("}" . insert-and-indent)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment