;;;; gopher.el: an emacs gopher client.
;;;; Copyright (C) 1992 scott snyder
;;;;
;;;; This file is not part of GNU Emacs, but is distributed under the
;;;; same conditions.
;;;;
;;;; GNU Emacs is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY.  No author or distributor
;;;; accepts responsibility to anyone for the consequences of using it
;;;; or for whether it serves any particular purpose or works at all,
;;;; unless he says so in writing.  Refer to the GNU Emacs General Public
;;;; License for full details.
;;;;
;;;; Everyone is granted permission to copy, modify and redistribute
;;;; GNU Emacs, but only under the conditions described in the
;;;; GNU Emacs General Public License.   A copy of this license is
;;;; supposed to have been given to you along with GNU Emacs so you
;;;; can know your rights and responsibilities.  It should be in a
;;;; file named COPYING.  Among other things, the copyright notice
;;;; and this notice must be preserved on all copies.
;;;;
;;;;
;;;; An emacs gopher client.  Currently supports directory, text, CSO,
;;;; index, and telnet objects.
;;;; Requires forms.el.
;;;; Written by scott snyder (snyder@d0gsc.fnal.gov)
;;;; Some code borrowed from GNUS (by Masanobu UMEDA).
;;;;
;;;; To use, `M-x gopher'.  To specify a different root server, use
;;;; `C-u M-x gopher'.
;;;;
;;;; In directory mode:
;;;;   Space or return selects the line point is on.
;;;;   `q', `l', or `u' will return to the previous node.
;;;;   `=' gives detailed information about an object.
;;;;
;;;; In document mode:
;;;;   Space pages forward.
;;;;   Delete pages backward.
;;;;   `q', `l' or `u' return to the last node.
;;;;
;;;; In the CSO entry form:
;;;;    `C-c RET' performs a look-up, based on the field contents
;;;;      you've filed in.
;;;;    `C-c l' returns to the previous node.
;;;;
;;;; From a telnet session:
;;;;    `C-c l' kills the session and returns to the previous node.
;;;;
;;;; Modification history:
;;;;
;;;; Version 0.9     29-JUN-1992
;;;;  * Initial release.
;;;;  
;;;; Version 0.91    30-JUN-1992
;;;;  * Deal with servers which send stuff after the CR.
;;;;  * Prevent gopher-directory-show-object from clearing the read-only flag.
;;;;  * Allow specification of port number in `C-u M-x gopher'.

(require 'electric)

(defvar gopher-root-node (vector ?1 "root" "" "gopher.micro.umn.edu" 70)
  "The root gopher server, as a gopher object.")

(defvar gopher-directory-mode-hook nil
  "*Invoked when entering a new gopher directory.")
(defvar gopher-directory-mode-map (make-keymap)
  "Keymap for gopher-directory-mode.")

(defvar gopher-document-mode-hook nil
  "*Invoked when showing gopher document.")
(defvar gopher-document-mode-map (make-keymap)
  "Keymap for gopher-document-mode.")

(defvar gopher-form-mode-hooks nil
  "*Invoked with entering a gopher form (i.e., for CSO).")
(defvar gopher-form-mode-map (make-keymap)
  "Keymap for gopher-form-mode.")

(defvar gopher-tmp-buf nil
  "Buffer used to receive output from gopher.")

(defvar gopher-debug-read t
  "*If non-nil, show the current status about reading the gopher server output.")


(defvar gopher-object-type-alist
  '(( ?0   ""          gopher-document-object)
    ( ?1   "/"         gopher-directory-object)
    ( ?2   " <CSO>"    gopher-cso-object)
    ( ?3   " <error>"  gopher-unimplemented-object)
    ( ?4   " <binhex>" gopher-binary-object)
    ( ?5   " <DOS>"    gopher-binary-object)
    ( ?6   " <UU>"     gopher-binary-object)
    ( ?7   " <?>"      gopher-index-object)
    ( ?8   " <TEL>"    gopher-telnet-object)
    ( ?9   " <bin>"    gopher-binary-object)
    ( ?T   " <T>"      gopher-unimplemented-object)
    ( ?s   " <)"       gopher-binary-object)
    ( ?M   " <MIME>"   gopher-unimplemented-object)
    ( ?h   " <html>"   gopher-unimplemented-object)
    ( ?I   " <image>"  gopher-unimplemented-object)
    ( ?c   " <cal>"    gopher-unimplemented-object)
    ( ?g   " <GIF>"    gopher-binary-object)
    )
  "*Alist describing the types of gopher objects this client know about.
The keys are the gopher type characters.
The second element in each list is the string to tag onto the end
of an object's description, to identify it to the user.
The third element is the function to use to retrieve the object.
It is called with two arguments: the gopher object to retrieve and
the buffer which should be returned to when the user is done
with this object.")


;;;
;;; The data structure describing a gopher object is a vector of five elements:
;;;    [ TYPE DESCR SELECTOR HOST PORT ]
;;;
;;;  TYPE is the type character.
;;;  DESCR is the human-readable description of the object.
;;;  SELECTOR is the opaque selector to be sent to HOST to retrieve the obj.
;;;  HOST is the name of the Internet host on which the object resides.
;;;  PORT is the TCP/IP port on which the host is listening.
;;;
;;;  The following macros set and fetch elements of this structure.
;;;  

(defmacro gopher-object-type (object)
  "Return the gopher type of OBJECT."
  (` (aref (, object) 0)))

(defmacro gopher-object-descr (object)
  "Return the gopher description of OBJECT."
  (` (aref (, object) 1)))

(defmacro gopher-object-selector (object)
  "Return the gopher selector string for OBJECT."
  (` (aref (, object) 2)))

(defmacro gopher-object-host (object)
  "Return the gopher hostname for OBJECT."
  (` (aref (, object) 3)))

(defmacro gopher-object-port (object)
  "Return the gopher TCP port number for OBJECT."
  (` (aref (, object) 4)))


(defmacro gopher-set-object-type (object type)
  "Set the gopher type of OBJECT to TYPE."
  (` (aset (, object) 0 (, type))))

(defmacro gopher-set-object-descr (object descr)
  "Set the gopher description of OBJECT to DESCR."
  (` (aset (, object) 1 (, descr))))

(defmacro gopher-set-object-selector (object selector)
  "Set the gopher selector string for OBJECT to SELECTOR."
  (` (aset (, object) 2 (, selector))))

(defmacro gopher-set-object-host (object host)
  "Set the gopher hostname for OBJECT to HOST."
  (` (aset (, object) 3 (, host))))

(defmacro gopher-set-object-port (object port)
  "Set the gopher TCP port number for OBJECT to PORT."
  (` (aset (, object) 4 (, port))))


;;;;--------------------------------------------------------------------------
;;;; main dispatching logic.
;;;;

(defun gopher (&optional askserv)
  "Start a gopher session.  With C-u, prompt for a gopher server."
  (interactive "P")
  (if askserv
      (progn
	(gopher-set-object-host
	 gopher-root-node
	 (read-string "Gopher server: "
		      (gopher-object-host gopher-root-node)))

	(let (portstr port)
	  (while (not (numberp port))
	    (setq portstr
		  (read-string "Port: "
			       (int-to-string
				(gopher-object-port gopher-root-node))))

	    (setq port (condition-case nil
			   (car (read-from-string portstr))
			 (error nil)))

	    (if (not (numberp port))
		(progn
		  (ding)
		  (message "Port must be numeric")
		  (sit-for 1)))
	    )

	  (gopher-set-object-port gopher-root-node port))))

  (gopher-dispatch-object gopher-root-node nil))


(defun gopher-dispatch-object (obj lastbuf)
  "Dispatch a gopher object depending on it's type."
  (let ((typedesc (assq (gopher-object-type obj) gopher-object-type-alist)))

    (if typedesc
	(funcall (nth 2 typedesc) obj lastbuf)
      (gopher-unimplemented-obect obj lastbuf))))


(defun gopher-unimplemented-object (obj lastbuf)
  (error "unimplemented object type"))


;;;;--------------------------------------------------------------------------
;;;; utilities
;;;;

(defun gopher-next-field nil
  "Returns as a string all chars between point and the next tab or newline.
Point is advanced to after the tab (or to the end-of-line)."

  (let ((beg (point)) s)
    (skip-chars-forward "^\t\n")
    (setq s (buffer-substring beg (point)))
    (if (eq (following-char) ?\t)
	(forward-char))
    s))


;; from GNUS
(defun gopher-make-local-vars (&rest pairs)
  ;; Take VARIABLE-VALUE pairs and makes local variables initialized to the
  ;; value.
  (while pairs
    (make-local-variable (car pairs))
    (set (car pairs) (car (cdr pairs)))
    (setq pairs (cdr (cdr pairs)))))


(defun gopher-get-tmp-buf nil
  "Get a temporary buffer in which to receive gopher output."
  (or (bufferp gopher-tmp-buf)
      (progn
	(setq gopher-tmp-buf (get-buffer-create " *gopher-tmp*"))
	(buffer-flush-undo gopher-tmp-buf)))
  gopher-tmp-buf)


(defun gopher-get-dir-buf (descr)
  "Get a new buffer suitable for a gopher directory or document."
  (let ((buf (generate-new-buffer "*gopher*")))
    (buffer-flush-undo buf)
    buf))

(fset 'gopher-get-doc-buf (symbol-function 'gopher-get-dir-buf))


(defun gopher-trim-blanks (str)
  "Remove leading and trailing blanks from STR."
  (string-match "\\`[ \t\n]*" str)
  (substring str
	     (match-end 0)
	     (string-match "[ \t\n]*\\'" str (match-end 0))))


;;;;--------------------------------------------------------------------------
;;;; directory handling
;;;;


(defun gopher-directory-object (obj oldbuf)
  "Retrieve and display a gopher directory."

  (let ((tmpbuf (gopher-get-tmp-buf))
	(dirbuf (gopher-get-dir-buf (gopher-object-descr obj))))

    ;; Get the directory...
    (gopher-retrieve-document tmpbuf
			      (gopher-object-selector obj)
			      (gopher-object-host     obj)
			      (gopher-object-port     obj))

    ;; Parse it and store our internal representation in gopher-dir.
    (switch-to-buffer dirbuf)
    (gopher-make-local-vars
     'gopher-dir (gopher-parse-directory tmpbuf)
     'gopher-last oldbuf)

    ;; Format it for your viewing pleasure.
    (gopher-format-directory gopher-dir dirbuf)
    (goto-char (point-min))
    (if (> (- (point-max) (point)) 7) (forward-char 7))

    ;; Turn on directory mode and put the description in the mode line.
    (gopher-directory-mode)
    (setq mode-line-buffer-identification (concat "Gopher: "
						  (gopher-object-descr obj)))
    ))


(defun gopher-parse-directory (buf)
  "Parse the gopher directory in buffer BUF into our internal representation.
Returns a vector of gopher objects."

  (save-excursion
    (set-buffer buf)
    (goto-char (point-min))

    (let* ((len (count-lines (point-min) (point-max)))
	   (dir (make-vector len nil))
	   (i 0))

      (while (not (eobp))
	(aset dir i (gopher-parse-directory-line))
	(setq i (1+ i))
	(forward-line 1))

      dir)))


(defun gopher-parse-directory-line nil
  "Parse the line containing point as a gopher directory entry.
Returns the corresponding gopher object."

  (let (type)
    (beginning-of-line)
    (setq type (following-char))
    (forward-char)
    (setq descr (gopher-next-field))
    (setq selector (gopher-next-field))
    (setq host (gopher-next-field))
    (setq port (gopher-next-field))

    (if (string-match "^[0-9]+$" port)
	(setq port (string-to-int port)))

    (vector type descr selector host port)))


(defun gopher-format-directory (dir buf)
  "Print the directory vector DIR into buffer BUF."

  (save-excursion
    (set-buffer buf)
    (erase-buffer)
    (let ((i 0)
	  (len (length dir)))
      (while (< i len)
	(gopher-format-directory-line (aref dir i) (1+ i))
	(setq i (1+ i)))

      )))


(defun gopher-format-directory-line (obj ndx)
  "Insert a line describing the gopher object OBJ into the current buffer.
NDX is a numeric index to display to the left of the object description."

  (let ((ndx-str (int-to-string ndx))
	(typedesc (assq (gopher-object-type obj) gopher-object-type-alist)))

    ;; display the index number.  use 5 digits, right-justified.
    (if (< (length ndx-str) 5)
	(insert (make-string (- 5 (length ndx-str)) ? )))
    (insert ndx-str)
    (insert ". ")

    ;; add the object description.
    (insert (gopher-object-descr obj))

    ;; add a tag indicating the gopher object type.
    (insert (if typedesc
		(nth 1 typedesc)
	      (concat " ???" (char-to-string (gopher-object-type obj)))))

    (insert "\n")))


(defun gopher-directory-mode nil
  "Gopher directory mode.

\\{gopher-directory-mode-map}
"
  (use-local-map gopher-directory-mode-map)
  (setq major-mode 'gopher-directory-mode)
  (setq mode-name "gopher dir")
  (run-hooks 'gopher-directory-mode-hook)
  (setq buffer-read-only t))


;;; keymap for directory mode
(suppress-keymap gopher-directory-mode-map)
(define-key gopher-directory-mode-map "\r" 'gopher-directory-choose)
(define-key gopher-directory-mode-map " " 'gopher-directory-choose)
(define-key gopher-directory-mode-map "l"  'gopher-last-node)
(define-key gopher-directory-mode-map "q"  'gopher-last-node)
(define-key gopher-directory-mode-map "u"  'gopher-last-node)
(define-key gopher-directory-mode-map "="  'gopher-directory-show-object)


(defun gopher-directory-current-obj nil
  "Returns the object described by the line point is on
(in a gopher directory buffer)."
  (aref gopher-dir (1- (count-lines (point-min) (1+ (point))))))


(defun gopher-directory-choose nil
  "Choose an item from the directory, and do whatever is appropriate
based on the object's type."
  (interactive)
  (gopher-dispatch-object (gopher-directory-current-obj) (current-buffer)))


(defun gopher-directory-show-object nil
  "Dump the internal information in a gopher object."
  (interactive)
  (let* ((obj (gopher-directory-current-obj))
	 (type (gopher-object-type obj))
	 (typespec (assq type gopher-object-type-alist))
	 (typetag (if typespec (nth 1 typespec) "?"))
	 (typeproc (if typespec (nth 2 typespec) "?")))
    (with-output-to-temp-buffer "*Gopher object*"
      (princ (format "Type        : %c   `%s'   %s\n" type typetag typeproc))
      (princ (format "Description : %s\n" (gopher-object-descr    obj)))
      (princ (format "Selector    : %s\n" (gopher-object-selector obj)))
      (princ (format "Host        : %s\n" (gopher-object-host     obj)))
      (princ (format "Port        : %d\n" (gopher-object-port     obj)))
      (current-buffer)
      ))
  (shrink-window-if-larger-than-buffer (get-buffer-window "*Gopher object*"))

  ;; shrink-window-if-larger-than-buffer screws these up...
  (set-buffer-modified-p nil)
  (setq buffer-read-only t))


(defun gopher-last-node nil
  "Return to the previous gopher node.
By convention, a gopher buffer has the local variable gopher-last which
contains the buffer to which we should return."
  (interactive)
  (let ((oldbuf (current-buffer)))
    (switch-to-buffer gopher-last)
    (kill-buffer oldbuf)))


;;;;--------------------------------------------------------------------------
;;;; gopher documents
;;;;


(defun gopher-document-object (obj oldbuf &optional end-regexp)
  "Retrieve and display a gopher document.
Optional argument END-REGEXP is used if the data will not be ended by `.'."

  (let ((docbuf (gopher-get-doc-buf (gopher-object-descr obj))))

    ;; Snarf the data into the buffer.
    (gopher-retrieve-document docbuf
			      (gopher-object-selector obj)
			      (gopher-object-host     obj)
			      (gopher-object-port     obj)
			      end-regexp)

    ;; Turn on document mode and put the description in the mode line.
    (switch-to-buffer docbuf)
    (gopher-make-local-vars
     'gopher-last oldbuf)
    (goto-char (point-min))
    (gopher-document-mode)
    (setq mode-line-buffer-identification (concat "Gopher: "
						  (gopher-object-descr obj)))
    ))


;; keymap for document mode
(suppress-keymap gopher-document-mode-map)
(define-key gopher-document-mode-map "l"  'gopher-last-node)
(define-key gopher-document-mode-map "q"  'gopher-last-node)
(define-key gopher-document-mode-map "u"  'gopher-last-node)
(define-key gopher-document-mode-map " "  'scroll-up)
(define-key gopher-document-mode-map "\C-?"  'scroll-down)
(define-key gopher-document-mode-map "\r"  'gopher-scroll-one-line-up)


(defun gopher-document-mode nil
  "Gopher document mode.

\\{gopher-document-mode-map}
"
  (use-local-map gopher-document-mode-map)
  (setq major-mode 'gopher-document-mode)
  (setq mode-name "gopher doc")
  (run-hooks 'gopher-document-mode-hook)
  (setq buffer-read-only t))


;; from gosmacs.el
(defun gopher-scroll-one-line-up (&optional arg)
  "Scroll the selected window up (forward in the text) one line (or N lines)."
  (interactive "p")
  (scroll-up (or arg 1)))


;;;;--------------------------------------------------------------------------
;;;; CSO handling.
;;;;
;;;; uses a subset of forms mode to handle data entry.
;;;;

(defun gopher-cso-object (obj oldbuf)
  "Display a CSO lookup form."

  ;; The following will create a buffer displaying the form described
  ;; by the list in the last argument (cf. forms-mode).  When the user
  ;; accepts the data in the form (by pressing `C-c RET'), the function
  ;; gopher-do-cso will be called with the data the user supplied.
  (gopher-form (gopher-object-descr obj)
	       'gopher-do-cso
	       4
	       '("====== phone directory lookup ======"
		 "\n Press `C-c RET' to lookup, `C-c l' to return to the last gopher object."
		 "\n (you must fill in at least one of the first three fields"
		 "\n"
		 "Name    : "   1
		 "\n"
		 "Phone   : "   2
		 "\n"
		 "E-Mail  : "   3
		 "\n"
		 "Address : "   4
		 ))

  ;; Record gopher-last so we gopher-last-node knows where to go.
  ;; Record gopher-obj so gopher-do-cso knows what server to query.
  (gopher-make-local-vars
   'gopher-last oldbuf
   'gopher-obj  obj))


(defconst gopher-cso-fields '("name" "phone" "email" "address")
  "Field names to use in CSO queries.")

(defun gopher-do-cso (vals)
  "Make a CSO query.  VALS is the data the user entered in the form,
as a list of strings."

  ;; Check that the required data was provided.
  (if (zerop (+ (length (nth 0 vals))
		(length (nth 1 vals))
		(length (nth 2 vals))))
      (error "Must specify name, phone, or email."))

  (let ((query "query")
	(fields gopher-cso-fields)
	(obj gopher-obj))

    ;; Form the query string
    (while vals

      (if (not (zerop (length (car vals))))
	  (setq query (concat query " " (car fields) "=" (car vals))))

      (setq vals (cdr vals))
      (setq fields (cdr fields)))

    ;; Use this string as the object selector.
    (gopher-set-object-selector gopher-obj query)

    ;; Retrieve the data from the server.  Unlike gopher, the CSO data
    ;; does not use `.' as a terminator.
    (gopher-document-object gopher-obj (current-buffer) "^[2-9]")

    ;; Strip CSO control information from the buffer.
    (gopher-clean-cso-buffer obj)))


(defun gopher-clean-cso-buffer (obj)
  "Strip CSO control information from the current buffer."

  (let ((req "")
	(buffer-read-only nil)
	beg nreq)
    (goto-char (point-min))
    (insert "\n")
    (while (not (eobp))
      (cond ((and (>= (following-char) ?3) (<= (following-char) ?9))
	     (delete-char 4)
	     (insert (concat (gopher-object-selector obj) "\n")))
	    
	    ((eq (following-char) ?-)
	     (delete-char 5)
	     (setq beg (point))
	     (skip-chars-forward "^:")
	     (setq nreq (buffer-substring beg (point)))
	     (goto-char beg)
	     (or (string= req nreq)
		 (insert (concat "--------------------------"
				 "-----------------------------\n")))
	     (setq req nreq)
	     (setq beg (point))
	     (skip-chars-forward "^:")
	     (forward-char)
	     (delete-region beg (point)))

	    (t
	     (setq beg (point))
	     (forward-line 1)
	     (delete-region beg (point))
	     (forward-line -1))
	    )
      (forward-line 1))

    (goto-char (point-min))
    (delete-char 1)))


;;;;--------------------------------------------------------------------------
;;;; indices.
;;;;
;;;; To query an index, the search string is appended to the selector.
;;;; The index returns a gopher directory.
;;;;


(defun gopher-index-object (obj oldbuf)
  "Query a gopher directory object."

  ;; Get the search string from the user.
  (let ((str (read-from-minibuffer "Key: "))
	(newobj (copy-sequence obj)))

    ;; Append it to the selector and retrieve the modified object
    ;; like a directory.
    (setq str (gopher-trim-blanks str))
    (if (> (length str) 0)
	(progn
	  (gopher-set-object-selector newobj
				      (concat (gopher-object-selector obj) "\t"
					      str))
	  (gopher-directory-object newobj (current-buffer)))
      )))



;;;;--------------------------------------------------------------------------
;;;; telnetting.
;;;;


(defun gopher-telnet-object (obj oldbuf)
  "Start a telnet session to a gopher object."

  ;; make the telnet argument string
  (let ((arg (gopher-object-host obj))
	(port (gopher-object-port obj)))
    (if (not (zerop port))
	(setq arg (concat arg 
			  (if (eq system-type 'vax-vms)
			      "/port="
			    " ")
			  port)))

    ;; start the telnet
    (telnet arg))

  ;; set things up so we can get back to the last node.
  (gopher-make-local-vars
   'gopher-last oldbuf)
  (local-set-key "\C-cl" 'gopher-last-node)

  ;; feed the login string to the telnet.
  (if (not (zerop (length (gopher-object-selector obj))))
      (progn
	(sit-for 5 t)
	(send-string (concat (gopher-object-host obj) "-telnet")
		     (concat (gopher-object-selector obj) "\n")))))


;;;;--------------------------------------------------------------------------
;;;; Various opaque objects.  Just save them in a file for now.
;;;;

(defun gopher-binary-object (obj oldbuf)
  "Retrieve a gopher object and save it to a file,
without trying to interpret it in any way."
  (let ((fname (read-file-name "File to save in: "))
	(buf (gopher-get-doc-buf (gopher-object-descr obj))))

    (gopher-retrieve-document buf
			      (gopher-object-selector obj)
			      (gopher-object-host     obj)
			      (gopher-object-port     obj)
			      'none)

    (save-excursion
      (set-buffer buf)
      (write-file fname))
    (kill-buffer buf)
    ))


;;;;--------------------------------------------------------------------------
;;;; forms stuff
;;;;
;;;; Uses some of the internal routines from forms.el to present
;;;; a form which is not associated with a file.
;;;;

(require 'forms)

(defun gopher-form (form-name accept-action number-of-fields format-list)
  "Display a buffer containing a form for the user to enter data.
The form is described by NUMBER-OF-FIELDS and FORMAT-LIST (cf. forms-mode).
FORM-NAME is a string to put in the modeline.
When the user accepts the data in the form by pressing `C-c RET', the
function ACCEPT-ACTION is called with a list of the strings which
the user entered."

  (switch-to-buffer (generate-new-buffer "*gopher form*"))

  (gopher-make-local-vars
   'forms-format-list   format-list
   'forms-number-of-fields number-of-fields
   'forms-field-sep        "\t"
   'forms-read-only        nil
   'forms-multi-line       nil
   'forms--number-of-markers nil
   'forms--markers           nil
   'forms--format            nil
   'forms--parser            nil
   'forms--dynamic-text      nil
   'forms-fields             nil
   'forms-the-record-list    nil
   'forms-accept-action      accept-action
   )

  (forms--process-format-list)
  (forms--make-format)
  (forms--make-parser)

  (erase-buffer)

  ;; make local variables
  (make-local-variable 'forms--file-buffer)
  (make-local-variable 'forms--total-records)
  (make-local-variable 'forms--current-record)
  (make-local-variable 'forms--the-record-list)
  (make-local-variable 'forms--search-rexexp)

  ;; set the major mode indicator
  (setq major-mode 'gopher-form-mode)
  (setq mode-name "gopher form")

  (set-buffer-modified-p nil)

  (use-local-map gopher-form-mode-map)

  (forms--show-record (make-string (1- number-of-fields) ?\t))

  (run-hooks 'gopher-form-mode-hooks))


(defun gopher-form-accept nil
  (interactive)

  (funcall forms-accept-action (forms--parse-form)))

(define-key gopher-form-mode-map "\C-c\r"  'gopher-form-accept)
(define-key gopher-form-mode-map "\C-cl"   'gopher-last-node)


;;;;--------------------------------------------------------------------------
;;;; low-level communications routines
;;;;

(defun gopher-retrieve-document (buf sel host port &optional end-regexp)
  "Retrieve a gopher object into BUF.
The object is identified by a SEL HOST PORT triple.
Optional argument END-REGEXP is used for data which is not `.'-terminated.
If END-REGEXP is non-nil and not a string, then it is assumed that
the data is binary, and reading will continue until the sender disconnects."

  ;; Default is single period termination.
  (or end-regexp (setq end-regexp "^\\.\r$"))

  (save-excursion
    (set-buffer buf)
    (erase-buffer)

    ;; open the connection to the server
    (let ((gopher-server-process
	   (open-network-stream "gopher" (current-buffer)
				host port)))

      ;; keep the emacs end-of-process status line out of the buffer
      (set-process-sentinel gopher-server-process 'gopher-sentinel)

      ;; send the selector to the server
      (process-send-string gopher-server-process (concat sel "\r\n"))

      ;; receive the response from the server
      ;; based on nntp.el from GNUS
      (setq wait t)
      (while wait
	(if (stringp end-regexp)
	    (progn
	      (goto-char (point-max))
	      (forward-line -1)))
	(if (and (stringp end-regexp)
		 (looking-at end-regexp))
	    (setq wait nil)
	  (if (not (memq (process-status gopher-server-process) '(open run)))
	      (progn
		(ding)
		(message "gopher: connection closed")
		(setq wait nil))
	    (if gopher-debug-read
		(message "gopher: Reading..."))
	    (if (boundp 'epoch::version)
		(accept-process-output gopher-server-process 2)
	      (accept-process-output gopher-server-process))
	    (if gopher-debug-read
		(message " ")))
	  ))

      ;; be sure the net connection has gone away...
      (condition-case nil
	  (delete-process gopher-server-process)
	(error t))

      ;; clean up the text buffer
      (if (stringp end-regexp)
	  (gopher-clean-text))
      )))


;;; adapted from GNUS
(defun gopher-clean-text ()
  "Decode text transmitted by gopher.
0. Delete status line.
1. Delete `^M' at end of line.
2. Delete `.' at end of buffer (end of text mark).
3. Delete `.' at beginning of line.   (does gopher want this?)"

  ;; Insert newline at end of buffer.
  (goto-char (point-max))
  (if (not (bolp))
      (insert "\n"))
  ;; Delete `^M' at end of line.
  (goto-char (point-min))
  (replace-regexp "\r[^\n]*$" "")
;  (goto-char (point-min))
;  (while (not (eobp))
;    (end-of-line)
;    (if (= (preceding-char) ?\r)
;	(delete-char -1))
;    (forward-line 1)
;    )
  ;; Delete `.' at end of buffer (end of text mark).
  (goto-char (point-max))
  (forward-line -1)			;(beginning-of-line)
  (while (looking-at "^\\.$")
    (delete-region (point) (progn (forward-line 1) (point)))
    (forward-line -1))
  ;; Replace `..' at beginning of line with `.'.
  (goto-char (point-min))
  ;; (replace-regexp "^\\.\\." ".")
  (while (search-forward "\n.." nil t)
    (delete-char -1))
  )


(defun gopher-sentinel (proc status)
  nil)

