Evaluating Scheme snippets

January 3rd, 2014

Note. It is best to read the original TeXmacs file with interactive Scheme sessions where one may experiment with the code. It can be found in the project's source code, inside the directory web/miguel.

We'd like to evaluate Scheme code inside scm-code tags. Let's first write some example code to use below:

(display "hi ")
(display "there\n")

Notice that we put a label at the beginning of the code snippet to reference it later (but it could be anywhere inside the scm-code).

We now define a function to take a subtree, extract the text and evaluate it using eval-string:

Scheme]

(define (eval-scm-code* t)

(if (tree-func? t 'scm-code)

(begin

(map (lambda (x) (eval-string (texmacs->verbatim x)))

(tree-children t))

#t)

#f))

In order to use this we define a :secure routine which we will use in action tags:

Scheme]

(tm-define (eval-scm-code t)

(:secure #t)

(let* ((txt (tree->string t))

(ltrees (select (buffer-tree) '(:* label)))

(filt (list-filter ltrees

(lambda (x) (== (tree->string (tree-ref x 0)) txt)))))

(map (lambda (x) (eval-scm-code* (tree-search-upwards x 'scm-code)))

filt)))

With them we can use the action tag to evaluate that piece of code with a click. Neat!

A nice follow-up would be a way to convert a bunch of Scheme sessions into scm-code snippets with automatically generated labels and links to execute them (which should only display on-screen, using specific).