[plt-scheme] function for reading text from Scheme files

From: Danny Yoo (dyoo at hkn.eecs.berkeley.edu)
Date: Sun Nov 19 22:30:48 EST 2006

Hi everyone,

Geb wrote a message while back asking how to get text out of PLT-enriched 
Scheme file.  One way to do it is to use the Framework functions to get at 
an interesting editor, and then call snip-specific methods on that editor.

Here is a quick-and-dirty kludge:

(module read-snips mzscheme
   (require (lib "list.ss")
            (lib "class.ss")
            (lib "framework.ss" "framework"))

   ;; get-editor: path -> editor%
   (define (get-editor path)
     (define frame:editor% (handler:edit-file path))
     (send frame:editor% show #f)
     (send frame:editor% get-editor))

   ;; Given a path, opens it and returns a list of its snips.
   ;; read-snips: path -> (listof snip<%>)
   (define (read-snips path)
     (let ([editor (get-editor path)])
       (let loop ([snips empty]
                  [next-snip (send editor find-first-snip)])
            (loop (cons next-snip snips)
                  (send next-snip next))]
           [else (reverse snips)]))))

   ;; snips->string: (listof snip%) -> string
   (define (snips->string snips)
     (apply string-append
            (map (lambda (snip) (send snip get-text 0 (send snip get-count) 
#t)) snips)))

;;  (define (test)
;;    (printf "~a~n" (snips->string (read-snips (build-path 
;;  (test)

     * This is not robust: I really would want to somehow get the editor%
       that DrScheme is itself using, but haven't figured out how to pull
       that out of Framework yet.

       (Ideally, I'd like to get at the same editor% mixin that DrScheme
       itself figures out after Stage 1, but I have no idea how to do this
       besides bringing the heavyweight DrScheme to life!)

     * It's also not doing anything too smart when it hits image snips.
       It probably only works if there are string or image snips; I
       don't think it'd work on other kinds of snips.

     * Another limitation is that you need to run this within the context
       of a MrEd-aware setup, so 'mred' or DrScheme are the two
       environments where this will work.

Finally, I have to warn that I have no real clue if I'm doing this right 
at all. *grin* There probably is an easier way to do what I'm doing.

Anyway, happy thanksgiving!

Posted on the users mailing list.