Skip to content

Instantly share code, notes, and snippets.

@oantolin
Last active Mar 31, 2021
Embed
What would you like to do?
Primitive python docstring generator in Emacs Lisp
(defun py-docstring ()
"Primitive Python docstring generator."
(interactive)
(save-excursion
(beginning-of-defun)
(down-list)
(let* ((all-args
(mapcar
(lambda (s) (split-string s "\\s-*=\\s-*"))
(split-string (buffer-substring
(point)
(progn (up-list) (1- (point))))
"\\s-*,\\s-*")))
(args (mapcar #'car (cl-remove-if #'cdr all-args)))
(kwargs (cl-remove-if-not #'cdr all-args))
exceptions)
(search-forward ":")
(newline)
(let ((end (save-excursion (end-of-defun) (point))))
(save-excursion
(while
(search-forward-regexp "raise \\(\\_<[A-Za-z0-9_]+\\_>\\)" nil t)
(push (match-string 1) exceptions)))
(setq exceptions (nreverse exceptions)))
(insert "\"\"\"[summary]\n")
(when args
(insert "\nArguments:\n")
(dolist (arg args)
(insert (format " %s {[type]} -- [description]\n" arg))))
(when kwargs
(insert "\nKeyword arguments:\n")
(dolist (kwarg kwargs)
(insert (format " %s {[type]} -- [description] (default: {%s})\n"
(car kwarg) (cadr kwarg)))))
(when exceptions
(insert "\nRaises:\n")
(dolist (exception exceptions)
(insert (format " %s -- [description]\n" exception))))
(insert "\nReturns:\n [type] -- [description]\n\"\"\""))))
(defun next-bracketed-word ()
"Move to and delete the next bracketed word."
(interactive)
(when (search-forward-regexp "\\[\\w+\\]" nil t)
(delete-region (match-beginning 0) (match-end 0))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment