Skip to content

Instantly share code, notes, and snippets.

@wvxvw wvxvw/init-python.el
Last active Feb 25, 2018

Embed
What would you like to do?
Some Python mode goodies
(defun wvxvw/python-align-fargs--find ()
(save-excursion
(search-backward "(")
(while (eql (face-at-point t) 'font-lock-string-face)
(search-backward "("))
(let* ((begin (point))
(end (save-excursion (progn (forward-sexp) (point))))
(args-begin
(progn
(forward-char)
(skip-syntax-forward " >")
(point)))
args)
(goto-char args-begin)
(while (< (point) (1- end))
(forward-sexp)
(when (or (char-equal (char-after) ?,)
(char-equal (char-after) ?\)))
(setq args (cons (buffer-substring args-begin (point)) args))
(forward-char)
(skip-syntax-forward " >")
(setq args-begin (point))))
(setq args (nreverse args))
(list begin args-begin end args))))
(defun wvxvw/python-align-fargs--split ()
(save-excursion
(cl-destructuring-bind (begin args-begin end args)
(wvxvw/python-align-fargs--find)
(delete-region (1+ begin) (1- end))
(goto-char (1+ begin))
(while args
(insert "\n" (car args) ",")
(setq args (cdr args)))
(insert "\n")
(indent-region begin (1+ (point))))))
(defun wvxvw/python-align-fargs--join ()
(save-excursion
(cl-destructuring-bind (begin args-begin end args)
(wvxvw/python-align-fargs--find)
(delete-region (1+ begin) (1- end))
(goto-char (1+ begin))
(while (cdr args)
(insert (car args) ", ")
(setq args (cdr args)))
(insert (car args)))))
(defun wvxvw/python-align-fargs (&optional prefix)
(interactive "p")
(if (/= prefix 1) (wvxvw/python-align-fargs--join)
(wvxvw/python-align-fargs--split)))
(defun wvxvw/python-wrap-string (&optional prefix)
(interactive "p")
(when (eql (face-at-point t) 'font-lock-string-face)
(save-excursion
(goto-char (1- (previous-property-change (point))))
(insert "(")
(when (/= prefix 1)
(insert "\n")
(indent-for-tab-command))
(let ((chop (- fill-column 2 (current-column)))
(start (point))
(qmark (buffer-substring-no-properties (point) (1+ (point))))
(end (1+ (next-property-change (1+ (point)))))
(padding (make-string (current-column) ?\ )))
(when (< chop 1) (setf chop 1))
(let* ((str (buffer-substring-no-properties (1+ start) (1- end)))
(chunks
(cl-loop for i from 0 upto (length str) by chop
collect (substring str i (min (+ i chop) (length str))))))
(delete-region start end)
(insert qmark (car chunks) qmark "\n")
(cl-loop for s on (cdr chunks) do
(insert padding qmark (car s) qmark (if (cdr s) "\n" "")))))
(if (/= prefix 1)
(progn
(insert "\n)")
(indent-for-tab-command))
(insert ")")))))
(define-key python-mode-map (kbd "C-c C-q") 'wvxvw/python-wrap-string)
(define-key python-mode-map (kbd "C-c C-i") 'wvxvw/python-align-fargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.