[racket] How can I save all the definitions in racket to a file?

From: Jon Rafkind (rafkind at cs.utah.edu)
Date: Thu Jun 24 13:53:10 EDT 2010

On 06/24/2010 04:03 AM, Insik Cho wrote:
> Hi buddies,
> I like a normal shell interactive environment.
> After I'm working in console 'racket,' I don't want to lose all the
> definitions I have made.
> How can I save the definitions to an external file, i.e., 'xxx.ss'?
> Thanks in advance.
> - Joe

I hacked this together. Its a start but it needs some work.

#lang racket

(require (for-syntax syntax/parse

(define-for-syntax (save-it foo)
   (with-output-to-file "definitions.rkt"
                        #:exists 'append
                        (lambda ()
                          (pretty-print (syntax->datum foo)))))

(provide (except-out (all-from-out racket) #%top-interaction))
(provide (rename-out (my-top #%top-interaction)))
(define-syntax (my-top stx)
   (syntax-parse stx
     [(_ . foo)
      (save-it #'foo)
      #'(#%top-interaction . foo)]))

Ok so what to do with this code: put it in some place like 
~/lib/top/main.rkt. When you run racket you will use this file as your 
top-level instead of the normal top-level. To get a new top-level use 
the -I switch. You also need to tell racket where to find this file 
using the -S switch.

$ racket -S /home/user/lib -I top
(note: you have to use an absolute path. there is a bug that is being 
fixed to use relative paths)

Each time you enter something in the repl it will be saved to 

An annoying issue with this top level is it saves a bunch of extra stuff 
that racket loads, but you can just ignore that for now.

$ racket -S `pwd`/lib -I top
-> 1
-> 2
-> 3
-> (define (foo x) (+ 1 2 x))
-> (x 5)
reference to undefined identifier: x

  === context ===

-> (foo 5)

$ cat definitions.rkt
'(define (foo x) (+ 1 2 x))
'(x 5)
'(foo 5)

Posted on the users mailing list.