Skip to content

Instantly share code, notes, and snippets.

Last active Mar 31, 2021
What would you like to do?
Primitive python docstring generator in Emacs Lisp
(defun py-docstring ()
"Primitive Python docstring generator."
(let* ((all-args
(lambda (s) (split-string s "\\s-*=\\s-*"))
(split-string (buffer-substring
(progn (up-list) (1- (point))))
(args (mapcar #'car (cl-remove-if #'cdr all-args)))
(kwargs (cl-remove-if-not #'cdr all-args))
(search-forward ":")
(let ((end (save-excursion (end-of-defun) (point))))
(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."
(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