emacs-orgmode
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Docstrings and literate programming (good practices?)


From: Juan Manuel Macías
Subject: Docstrings and literate programming (good practices?)
Date: Tue, 01 Nov 2022 14:07:52 +0000

Hi all,

I find docstrings very useful. One can learn a great deal about Elisp
just from describe-function and describe-variable. But I don't find the
best way for docstrings to fit into the "precepts" of literate
programming. I try to explain myself: today I am reviewing my Emacs
init, written in Org. I like to document the code neatly, so that my
future self knows what my present self was trying to do. But I realize
that many of those global explanations before a function or a variable
can also be in a docstring. I can duplicate the text, but it seems to be
a bit redundant, right? So what is the best way to proceed when doing
literate programming with any language that supports docstrings?
Apologies in advance if the question is a bit silly, but I'm not a
professional programmer and don't have an academic background in it,
so I don't know if there is any good practice on these things :-)

On the other hand, the following procedure has occurred to me: put the
relevant information in an Org src block. When exporting to a human
readable format (PDF, HTML, etc.), the content is exported as part of
the text. When tangling, the block content is exported as a docstring.

First, I defined this function:

  (defun my-org-format-docstring (cont)
    (with-temp-buffer
      (insert cont)
      (save-excursion
        (goto-char (point-min))
        (while (re-search-forward org-emph-re nil t)
          (replace-match (concat " " (match-string 4) " ") t nil)))
      (setq cont
            (string-trim
             (replace-regexp-in-string
              "\\(\"\\)"
              "\\\\\\1"
              (org-export-string-as (buffer-string) 'ascii t)))))
    (format "\"%s\"" cont))


And an example of use:

#+NAME: format-docstring
#+begin_src emacs-lisp :exports none :var x="" :tangle no
  (if (not org-export-current-backend)
      (my-org-format-docstring x)
    x)
#+end_src

#+NAME: docstring1
#+begin_src org :post format-docstring(*this*) :results replace :exports 
results :tangle no
  Lorem ipsum dolor sit amet.

  Consectetuer adipiscing elit. "Donec hendrerit tempor tellus". Donec pretium 
posuere
  tellus. Proin quam nisl, tincidunt et, mattis eget, convallis nec, purus. Cum 
sociis
  natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. 
#+end_src

#+begin_src emacs-lisp :noweb strip-export :exports code
  (defun foo ()
   <<docstring1()>>
    (message "hello world"))
#+end_src

The only drawback is that with :noweb strip-export an empty line is
left.

Best regards,

Juan Manuel 



reply via email to

[Prev in Thread] Current Thread [Next in Thread]