;;; emacs-cmd.el --- Run emacs commands from a FIFO

;; Copyright (C) 2007  Mark Triggs

;; Author: Mark Triggs <mst@dishevelled.net>

;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; This file 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 General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.

;;; Commentary:

;; This uses a command proxy that listens for instructions and executes them,
;; basically allowing me to communicate with Emacs over the command-line or
;; network.  My emacs-cmd reader simply creates a FIFO and sits in a loop of
;; reading a line and printing it to stdout. 

;;; Code:

(defvar *emacs-cmd-process* nil)
(defvar *emacs-cmd-handlers* '())

(defun emacs-cmd-start ()
  (interactive)
  (setq *emacs-cmd-process*
        (start-process "emacs-cmd" nil "emacs-cmd-reader"))
  (set-process-filter *emacs-cmd-process*
                      (lambda (proc string)
                        (run-hook-with-args '*emacs-cmd-handlers*
                                            (trim-trailing string "\n")))))

(defun emacs-cmd-stop ()
  (interactive)
  (kill-process *emacs-cmd-process*)
  (setq *emacs-cmd-process* nil))

(add-hook '*emacs-cmd-handlers*
          (lambda (string)
            (when (string-match "display on \\(.*\\)$" string)
              (let ((default-frame-alist
                      (remove-if (lambda (elt)
                                   (eq elt 'font))
                                 default-frame-alist
                                 :key 'car)))
              (make-frame-on-display (match-string 1 string))))))




(provide 'emacs-cmd)
;;; emacs-cmd.el ends here
