Debian Codegraph @

src/heredoc.lisp

raw
1 ;;;; cl-heredoc - heredoc.lisp
2 ;;;; Copyright (C) 2010 Alexander Kahl <[email protected]>
3 ;;;; This file is part of cl-heredoc.
4 ;;;; cl-heredoc is free software; you can redistribute it and/or modify
5 ;;;; it under the terms of the GNU General Public License as published by
6 ;;;; the Free Software Foundation; either version 3 of the License, or
7 ;;;; (at your option) any later version.
8 ;;;;
9 ;;;; cl-heredoc is distributed in the hope that it will be useful,
10 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
11 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 ;;;; GNU General Public License for more details.
13 ;;;;
14 ;;;; You should have received a copy of the GNU General Public License
15 ;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 (in-package :cl-heredoc)
18
19 (defun read-until-match (stream terminal)
20 "read-until-match stream terminal => string
21
22 Read characters from STREAM until a sequence equal to string TERMINAL is read.
23 Return all characters read as string omitting TERMINAL itself. Signal error upon
24 EOF."
25 (with-output-to-string (out)
26 (do* ((match-length (length terminal))
27 (buffer (new-ring-buffer match-length))
28 (buffer-char nil)
29 (char (read-char stream t :eof t)
30 (or (setf buffer-char (ring-buffer-next buffer))
31 (read-char stream t :eof t)))
32 (match-pos 0))
33 ((eql char :eof))
34 (cond ((char= char (char terminal match-pos))
35 (when (= (incf match-pos) match-length)
36 (return))
37 (unless buffer-char
38 (ring-buffer-insert buffer char)))
39 ((zerop match-pos)
40 (write-char char out)
41 (when buffer-char
42 (ring-buffer-pop buffer)))
43 (t
44 (unless buffer-char
45 (ring-buffer-insert buffer char))
46 (write-char (ring-buffer-pop buffer) out)
47 (setf match-pos 0))))))
48
49 (defun read-heredoc (stream char arg)
50 "read-heredoc stream char arg => string
51
52 Return string from STREAM up to the point where the string read first until CHAR
53 is encountered. All evaluation is completely turned off so no quoting is
54 required at all.
55 Example:
56 CL-USER> (set-dispatch-macro-character #\# #\> #'cl-heredoc:read-heredoc)
57 CL-USER> #>eof>Write whatever (you) \"want\"!eof => Write whatever (you) \"want\"!"
58 (declare (ignore arg))
59 (read-until-match stream (read-until-match stream (string char))))