Skip to content

Instantly share code, notes, and snippets.

@kurohuku
Created July 20, 2010 14:28
Show Gist options
  • Save kurohuku/483027 to your computer and use it in GitHub Desktop.
Save kurohuku/483027 to your computer and use it in GitHub Desktop.
;;;; Emacs Lisp
(require 'cl)
(setf *opening-stream-buffers*
(make-hash-table))
(defmacro with-default-values (binds &rest body)
`(progn
,@(mapcar
(lambda (bind)
`(unless ,(first bind)
(setf ,(first bind) ,(second bind))))
binds)
,@body))
(defun open (filename &optional direction)
(with-default-values
((direction :input))
(let ((buf (create-file-buffer filename)))
(when (eq direction :input)
(with-current-buffer buf
(insert-file-contents filename)))
(setf (gethash buf *opening-stream-buffers*) (list direction filename))
buf)))
(defun close (buf)
(when (eq (first (gethash buf *opening-stream-buffers*))
:output)
(with-current-buffer buf
(write-region
(point-min) (point-max)
(second (gethash buf *opening-stream-buffers*))))
(kill-buffer buf)))
;; clause = (stream filename &optional direction)
(defmacro with-open-file (clause &rest body)
(destructuring-bind
(direction filename stream)
(let ((tmp (reverse clause)))
(if (= (length tmp) 2)
(cons :input tmp)
tmp))
`(let ((,stream (open ,filename ,direction)))
(prog1
(progn
,@body)
(close ,stream)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment