summaryrefslogtreecommitdiff
path: root/gpgscm/repl.scm
blob: 8e87a97d619a01ac7bd9bd52d1b5f2c8a513d5da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
;; A read-evaluate-print-loop for gpgscm.
;; Copyright (C) 2016 g10 Code GmbH
;;
;; This file is part of Libgpg-error.
;;
;; Libgpg-error is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 2.1 of
;; the License, or (at your option) any later version.
;;
;; Libgpg-error is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program; if not, see <https://www.gnu.org/licenses/>.

;; Interactive repl using 'prompt' function.  P must be a function
;; that given the current entered prefix returns the prompt to
;; display.
(define (repl p environment)
  (call/cc
   (lambda (exit)
     (let loop ((prefix ""))
       (let ((line (prompt (p prefix))))
	 (if (and (not (eof-object? line)) (= 0 (string-length line)))
	     (exit (loop prefix)))
	 (if (not (eof-object? line))
	     (let* ((next (string-append prefix line))
		    (c (catch (begin (echo "Parse error:" *error*)
				     (loop prefix))
			      (read (open-input-string next)))))
	       (if (not (eof-object? c))
		   (begin
		     (catch (begin
			      (display (car *error*))
			      (when (and (cadr *error*)
					 (not (null? (cadr *error*))))
				    (display ": ")
				    (write (cadr *error*)))
			      (newline)
			      (vm-history-print (caddr *error*)))
			    (echo "    ===>" (eval c environment)))
		     (exit (loop ""))))
	       (exit (loop next)))))))))

(define (prompt-append-prefix prompt prefix)
  (string-append prompt (if (> (string-length prefix) 0)
			    (string-append prefix "...")
			    "> ")))

;; Default repl run by main.c.
(define (interactive-repl . environment)
  (repl (lambda (p) (prompt-append-prefix "gpgscm " p))
	(if (null? environment) (interaction-environment) (car environment))))

;; Ask a yes/no question.
(define (prompt-yes-no? question default)
  (let ((answer (prompt (string-append question "? ["
				       (if default "Y/n" "y/N") "] "))))
    (cond
     ((= 0 (string-length answer))
      default)
     ((or (equal? "y" answer) (equal? "Y" answer))
      #t)
     (else
      #f))))