Search code examples
emacsorg-modeliterate-programming

org-mode with code example as html


I'm trying to embed a literate code example as HTML in Emacs org-mode.

The idea is that I can use something like

#+BEGIN_SRC html :noweb-ref content :exports source
<span>some content </span>
#+END_SRC

#+BEGIN_HTML :noweb tangle
<<content>>
#+END_HTML

Would something like this be possible? Because currently I have to copy&paste the part I want to be included (quoted) in the HTML source and the SRC bit that I want to show in the document.

EDIT: The concrete use case is that I would like to write a document explaining some HTML constructs (as a code block) and embedding (quoted) those same constructs in the document, without copy+paste


Solution

  • The example below is adapted from something similar I've used for writing about Org-mode. It seems to work for your use case too. The #+OPTIONS: d:RESULTS ensures that the :RESULTS: drawer is exported. Put this in an Org-mode buffer and export to HTML.

    #+OPTIONS: d:RESULTS
    
    * Examples
    
    The HTML source
    #+name: eg-1
    #+begin_src org :results replace drawer :exports both :post wrap-html(text=*this*)
      A <b>bold</b> statement.
    #+end_src
    
    Results in the output
    #+results: eg-1
    
    * Utils                                                           :noexport:
    #+name: wrap-html
    #+begin_src emacs-lisp :var text="" :results raw
    (concat "#+BEGIN_HTML\n<div class=\"html-output\">\n" text "\n</div>\n#+END_HTML")
    #+end_src
    

    You can avoid repeating the headers by adding them as properties to the subtree heading, e.g.

    * Example 2
    :PROPERTIES:
    :results: replace drawer
    :exports: both
    :post: wrap-html(text=*this*)
    :END:
    
    #+name: eg-2
    #+begin_src org
      Some <i>italic</i>.
    #+end_src
    
    #+results: eg-2
    
    #+name: eg-3
    #+begin_src org
      You can <b>nest <i>inline</i> tags</b>.
    #+end_src
    
    #+results: eg-3
    

    but note that these headers will apply to every source block in the subtree unless explicitly overridden.