1;; erc.el --- An Emacs Internet Relay Chat client
2
3;; Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
4;;   2006, 2007 Free Software Foundation, Inc.
5
6;; Author: Alexander L. Belikoff (alexander@belikoff.net)
7;; Contributors: Sergey Berezin (sergey.berezin@cs.cmu.edu),
8;;               Mario Lang (mlang@delysid.org),
9;;               Alex Schroeder (alex@gnu.org)
10;;               Andreas Fuchs (afs@void.at)
11;;               Gergely Nagy (algernon@midgard.debian.net)
12;;               David Edmondson (dme@dme.org)
13;; Maintainer: Michael Olson (mwolson@gnu.org)
14;; Keywords: IRC, chat, client, Internet
15
16;; This file is part of GNU Emacs.
17
18;; GNU Emacs is free software; you can redistribute it and/or modify
19;; it under the terms of the GNU General Public License as published by
20;; the Free Software Foundation; either version 2, or (at your option)
21;; any later version.
22
23;; GNU Emacs is distributed in the hope that it will be useful,
24;; but WITHOUT ANY WARRANTY; without even the implied warranty of
25;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26;; GNU General Public License for more details.
27
28;; You should have received a copy of the GNU General Public License
29;; along with GNU Emacs; see the file COPYING.  If not, write to the
30;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
31;; Boston, MA 02110-1301, USA.
32
33;;; Commentary:
34
35;; ERC is a powerful, modular, and extensible IRC client for Emacs.
36
37;; For more information, see the following URLs:
38;; * http://sv.gnu.org/projects/erc/
39;; * http://www.emacswiki.org/cgi-bin/wiki/ERC
40
41;; As of 2006-06-13, ERC development is now hosted on Savannah
42;; (http://sv.gnu.org/projects/erc).  I invite everyone who wants to
43;; hack on it to contact me <mwolson@gnu.org> in order to get write
44;; access to the shared Arch archive.
45
46;; Installation:
47
48;; Put erc.el in your load-path, and put (require 'erc) in your .emacs.
49
50;; Configuration:
51
52;; Use M-x customize-group RET erc RET to get an overview
53;; of all the variables you can tweak.
54
55;; Usage:
56
57;; To connect to an IRC server, do
58;;
59;; M-x erc RET
60;;
61;; After you are connected to a server, you can use C-h m or have a look at
62;; the ERC menu.
63
64;;; History:
65;;
66
67;;; Code:
68
69(defconst erc-version-string "Version 5.2"
70  "ERC version.  This is used by function `erc-version'.")
71
72(eval-when-compile (require 'cl))
73(require 'font-lock)
74(require 'pp)
75(require 'thingatpt)
76(require 'erc-compat)
77
78(defvar erc-official-location
79  "http://emacswiki.org/cgi-bin/wiki/ERC (mailing list: erc-discuss@gnu.org)"
80  "Location of the ERC client on the Internet.")
81
82(defgroup erc nil
83  "Emacs Internet Relay Chat client."
84  :link '(url-link "http://www.emacswiki.org/cgi-bin/wiki/ERC")
85  :prefix "erc-"
86  :group 'applications)
87
88(defgroup erc-buffers nil
89  "Creating new ERC buffers"
90  :group 'erc)
91
92(defgroup erc-display nil
93  "Settings for how various things are displayed"
94  :group 'erc)
95
96(defgroup erc-mode-line-and-header nil
97  "Displaying information in the mode-line and header"
98  :group 'erc-display)
99
100(defgroup erc-ignore nil
101  "Ignoring certain messages"
102  :group 'erc)
103
104(defgroup erc-query nil
105  "Using separate buffers for private discussions"
106  :group 'erc)
107
108(defgroup erc-quit-and-part nil
109  "Quitting and parting channels"
110  :group 'erc)
111
112(defgroup erc-paranoia nil
113  "Know what is sent and received; control the display of sensitive data."
114  :group 'erc)
115
116(defgroup erc-scripts nil
117  "Running scripts at startup and with /LOAD"
118  :group 'erc)
119
120(require 'erc-backend)
121
122;; compatibility with older ERC releases
123
124(if (fboundp 'defvaralias)
125    (progn
126      (defvaralias 'erc-announced-server-name 'erc-server-announced-name)
127      (erc-make-obsolete-variable 'erc-announced-server-name
128				  'erc-server-announced-name
129				  "ERC 5.1")
130      (defvaralias 'erc-process 'erc-server-process)
131      (erc-make-obsolete-variable 'erc-process 'erc-server-process "ERC 5.1")
132      (defvaralias 'erc-default-coding-system 'erc-server-coding-system)
133      (erc-make-obsolete-variable 'erc-default-coding-system
134				  'erc-server-coding-system
135				  "ERC 5.1"))
136  (message (concat "ERC: The function `defvaralias' is not bound.  See the "
137		   "NEWS file for variable name changes since ERC 5.0.4.")))
138
139(defalias 'erc-send-command 'erc-server-send)
140(erc-make-obsolete 'erc-send-command 'erc-server-send "ERC 5.1")
141
142;; tunable connection and authentication parameters
143
144(defcustom erc-server nil
145  "IRC server to use if one is not provided.
146See function `erc-compute-server' for more details on connection
147parameters and authentication."
148  :group 'erc
149  :type '(choice (const :tag "None" nil)
150		 (string :tag "Server")))
151
152(defcustom erc-port nil
153  "IRC port to use if not specified.
154
155This can be either a string or a number."
156  :group 'erc
157  :type '(choice (const :tag "None" nil)
158		 (integer :tag "Port number")
159		 (string :tag "Port string")))
160
161(defcustom erc-nick nil
162  "Nickname to use if one is not provided.
163
164This can be either a string, or a list of strings.
165In the latter case, if the first nick in the list is already in use,
166other nicks are tried in the list order.
167
168See function `erc-compute-nick' for more details on connection
169parameters and authentication."
170  :group 'erc
171  :type '(choice (const :tag "None" nil)
172		 (string :tag "Nickname")
173		 (repeat (string :tag "Nickname"))))
174
175(defcustom erc-nick-uniquifier "`"
176  "The string to append to the nick if it is already in use."
177  :group 'erc
178  :type 'string)
179
180(defcustom erc-try-new-nick-p t
181  "If the nickname you chose isn't available, and this option is non-nil,
182ERC should automatically attempt to connect with another nickname.
183
184You can manually set another nickname with the /NICK command."
185  :group 'erc
186  :type 'boolean)
187
188(defcustom erc-user-full-name nil
189  "User full name.
190
191This can be either a string or a function to call.
192
193See function `erc-compute-full-name' for more details on connection
194parameters and authentication."
195  :group 'erc
196  :type '(choice (const :tag "No name" nil)
197		 (string :tag "Name")
198		 (function :tag "Get from function"))
199  :set (lambda (sym val)
200	 (if (functionp val)
201	     (set sym (funcall val))
202	   (set sym val))))
203
204(defvar erc-password nil
205  "Password to use when authenticating to an IRC server.
206It is not strictly necessary to provide this, since ERC will
207prompt you for it.")
208
209(defcustom erc-user-mode nil
210  "Initial user modes to be set after a connection is established."
211  :group 'erc
212  :type '(choice (const nil) string function))
213
214
215(defcustom erc-prompt-for-password t
216  "Asks before using the default password, or whether to enter a new one."
217  :group 'erc
218  :type 'boolean)
219
220(defcustom erc-warn-about-blank-lines t
221  "Warn the user if they attempt to send a blank line."
222  :group 'erc
223  :type 'boolean)
224
225(defcustom erc-send-whitespace-lines nil
226  "If set to non-nil, send lines consisting of only whitespace."
227  :group 'erc
228  :type 'boolean)
229
230(defcustom erc-hide-prompt nil
231  "If non-nil, do not display the prompt for commands.
232
233\(A command is any input starting with a '/').
234
235See also the variables `erc-prompt' and `erc-command-indicator'."
236  :group 'erc-display
237  :type 'boolean)
238
239;; tunable GUI stuff
240
241(defcustom erc-show-my-nick t
242  "If non-nil, display one's own nickname when sending a message.
243
244If non-nil, \"<nickname>\" will be shown.
245If nil, only \"> \" will be shown."
246  :group 'erc-display
247  :type 'boolean)
248
249(define-widget 'erc-message-type 'set
250  "A set of standard IRC Message types."
251  :args '((const "JOIN")
252	  (const "KICK")
253	  (const "NICK")
254	  (const "PART")
255	  (const "QUIT")
256	  (const "MODE")
257	  (repeat :inline t :tag "Others" (string :tag "IRC Message Type"))))
258
259(defcustom erc-hide-list nil
260  "*List of IRC type messages to hide.
261A typical value would be '(\"JOIN\" \"PART\" \"QUIT\")."
262  :group 'erc-ignore
263  :type 'erc-message-type)
264
265(defvar erc-session-password nil
266  "The password used for the current session.")
267(make-variable-buffer-local 'erc-session-password)
268
269(defcustom erc-disconnected-hook nil
270  "Run this hook with arguments (NICK IP REASON) when disconnected.
271This happens before automatic reconnection.  Note, that
272`erc-server-QUIT-functions' might not be run when we disconnect,
273simply because we do not necessarily receive the QUIT event."
274  :group 'erc-hooks
275  :type 'hook)
276
277(defcustom erc-complete-functions nil
278  "These functions get called when the user hits TAB in ERC.
279Each function in turn is called until one returns non-nil to
280indicate it has handled the input."
281  :group 'erc-hooks
282  :type 'hook)
283
284(defcustom erc-join-hook nil
285  "Hook run when we join a channel.  Hook functions are called
286without arguments, with the current buffer set to the buffer of
287the new channel.
288
289See also `erc-server-JOIN-functions', `erc-part-hook'."
290  :group 'erc-hooks
291  :type 'hook)
292
293(defcustom erc-quit-hook nil
294  "Hook run when processing a quit command directed at our nick.
295
296The hook receives one argument, the current PROCESS.
297See also `erc-server-QUIT-functions' and `erc-disconnected-hook'."
298  :group 'erc-hooks
299  :type 'hook)
300
301(defcustom erc-part-hook nil
302  "Hook run when processing a PART message directed at our nick.
303
304The hook receives one argument, the current BUFFER.
305See also `erc-server-QUIT-functions', `erc-quit-hook' and
306`erc-disconnected-hook'."
307  :group 'erc-hooks
308  :type 'hook)
309
310(defcustom erc-kick-hook nil
311  "Hook run when processing a KICK message directed at our nick.
312
313The hook receives one argument, the current BUFFER.
314See also `erc-server-PART-functions' and `erc-part-hook'."
315  :group 'erc-hooks
316  :type 'hook)
317
318(defcustom erc-nick-changed-functions nil
319  "List of functions run when your nick was successfully changed.
320
321Each function should accept two arguments, NEW-NICK and OLD-NICK."
322  :group 'erc-hooks
323  :type 'hook)
324
325(defcustom erc-connect-pre-hook '(erc-initialize-log-marker)
326  "Hook called just before `erc' calls `erc-connect'.
327Functions are passed a buffer as the first argument."
328  :group 'erc-hooks
329  :type 'hook)
330
331
332(defvar erc-channel-users nil
333  "A hash table of members in the current channel, which
334associates nicknames with cons cells of the form:
335\(USER . MEMBER-DATA) where USER is a pointer to an
336erc-server-user struct, and MEMBER-DATA is a pointer to an
337erc-channel-user struct.")
338(make-variable-buffer-local 'erc-channel-users)
339
340(defvar erc-server-users nil
341  "A hash table of users on the current server, which associates
342nicknames with erc-server-user struct instances.")
343(make-variable-buffer-local 'erc-server-users)
344
345(defun erc-downcase (string)
346  "Convert STRING to IRC standard conforming downcase."
347  (let ((s (downcase string))
348	(c '((?\[ . ?\{)
349	     (?\] . ?\})
350	     (?\\ . ?\|)
351	     (?~  . ?^))))
352    (save-match-data
353      (while (string-match "[]\\[~]" s)
354	(aset s (match-beginning 0)
355	      (cdr (assq (aref s (match-beginning 0)) c)))))
356    s))
357
358(defmacro erc-with-server-buffer (&rest body)
359  "Execute BODY in the current ERC server buffer.
360If no server buffer exists, return nil."
361  (let ((buffer (make-symbol "buffer")))
362    `(let ((,buffer (erc-server-buffer)))
363       (when (buffer-live-p ,buffer)
364	 (with-current-buffer ,buffer
365	   ,@body)))))
366(put 'erc-with-server-buffer 'lisp-indent-function 0)
367(put 'erc-with-server-buffer 'edebug-form-spec '(body))
368
369(defstruct (erc-server-user (:type vector) :named)
370  ;; User data
371  nickname host login full-name info
372  ;; Buffers
373  ;;
374  ;; This is an alist of the form (BUFFER . CHANNEL-DATA), where
375  ;; CHANNEL-DATA is either nil or an erc-channel-user struct.
376  (buffers nil)
377  )
378
379(defstruct (erc-channel-user (:type vector) :named)
380  op voice
381  ;; Last message time (in the form of the return value of
382  ;; (current-time)
383  ;;
384  ;; This is useful for ordered name completion.
385  (last-message-time nil))
386
387(defsubst erc-get-channel-user (nick)
388  "Finds the (USER . CHANNEL-DATA) element corresponding to NICK
389in the current buffer's `erc-channel-users' hash table."
390  (gethash (erc-downcase nick) erc-channel-users))
391
392(defsubst erc-get-server-user (nick)
393  "Finds the USER corresponding to NICK in the current server's
394`erc-server-users' hash table."
395  (erc-with-server-buffer
396    (gethash (erc-downcase nick) erc-server-users)))
397
398(defsubst erc-add-server-user (nick user)
399  "This function is for internal use only.
400
401Adds USER with nickname NICK to the `erc-server-users' hash table."
402  (erc-with-server-buffer
403    (puthash (erc-downcase nick) user erc-server-users)))
404
405(defsubst erc-remove-server-user (nick)
406  "This function is for internal use only.
407
408Removes the user with nickname NICK from the `erc-server-users'
409hash table.  This user is not removed from the
410`erc-channel-users' lists of other buffers.
411
412See also: `erc-remove-user'."
413  (erc-with-server-buffer
414    (remhash (erc-downcase nick) erc-server-users)))
415
416(defun erc-change-user-nickname (user new-nick)
417  "This function is for internal use only.
418
419Changes the nickname of USER to NEW-NICK in the
420`erc-server-users' hash table.  The `erc-channel-users' lists of
421other buffers are also changed."
422  (let ((nick (erc-server-user-nickname user)))
423    (setf (erc-server-user-nickname user) new-nick)
424    (erc-with-server-buffer
425      (remhash (erc-downcase nick) erc-server-users)
426      (puthash (erc-downcase new-nick) user erc-server-users))
427    (dolist (buf (erc-server-user-buffers user))
428      (if (buffer-live-p buf)
429	  (with-current-buffer buf
430	    (let ((cdata (erc-get-channel-user nick)))
431	      (remhash (erc-downcase nick) erc-channel-users)
432	      (puthash (erc-downcase new-nick) cdata
433		       erc-channel-users)))))))
434
435(defun erc-remove-channel-user (nick)
436  "This function is for internal use only.
437
438Removes the user with nickname NICK from the `erc-channel-users'
439list for this channel.  If this user is not in the
440`erc-channel-users' list of any other buffers, the user is also
441removed from the server's `erc-server-users' list.
442
443See also: `erc-remove-server-user' and `erc-remove-user'."
444  (let ((channel-data (erc-get-channel-user nick)))
445    (when channel-data
446      (let ((user (car channel-data)))
447	(setf (erc-server-user-buffers user)
448	      (delq (current-buffer)
449		    (erc-server-user-buffers user)))
450	(remhash (erc-downcase nick) erc-channel-users)
451	(if (null (erc-server-user-buffers user))
452	    (erc-remove-server-user nick))))))
453
454(defun erc-remove-user (nick)
455  "This function is for internal use only.
456
457Removes the user with nickname NICK from the `erc-server-users'
458list as well as from all `erc-channel-users' lists.
459
460See also: `erc-remove-server-user' and
461`erc-remove-channel-user'."
462  (let ((user (erc-get-server-user nick)))
463    (when user
464      (let ((buffers (erc-server-user-buffers user)))
465	(dolist (buf buffers)
466	  (if (buffer-live-p buf)
467	      (with-current-buffer buf
468		(remhash (erc-downcase nick) erc-channel-users)
469		(run-hooks 'erc-channel-members-changed-hook)))))
470      (erc-remove-server-user nick))))
471
472(defun erc-remove-channel-users ()
473  "This function is for internal use only.
474
475Removes all users in the current channel.  This is called by
476`erc-server-PART' and `erc-server-QUIT'."
477  (when (and erc-server-connected
478	     (erc-server-process-alive)
479	     (hash-table-p erc-channel-users))
480    (maphash (lambda (nick cdata)
481	       (erc-remove-channel-user nick))
482	     erc-channel-users)
483    (clrhash erc-channel-users)))
484
485(defsubst erc-channel-user-op-p (nick)
486  "Return t if NICK is an operator in the current channel."
487  (and nick
488       (hash-table-p erc-channel-users)
489       (let ((cdata (erc-get-channel-user nick)))
490	 (and cdata (cdr cdata)
491	      (erc-channel-user-op (cdr cdata))))))
492
493(defsubst erc-channel-user-voice-p (nick)
494  "Return t if NICK has voice in the current channel."
495  (and nick
496       (hash-table-p erc-channel-users)
497       (let ((cdata (erc-get-channel-user nick)))
498	 (and cdata (cdr cdata)
499	      (erc-channel-user-voice (cdr cdata))))))
500
501(defun erc-get-channel-user-list ()
502  "Returns a list of users in the current channel.  Each element
503of the list is of the form (USER . CHANNEL-DATA), where USER is
504an erc-server-user struct, and CHANNEL-DATA is either `nil' or an
505erc-channel-user struct.
506
507See also: `erc-sort-channel-users-by-activity'"
508  (let (users)
509    (if (hash-table-p erc-channel-users)
510      (maphash (lambda (nick cdata)
511		 (setq users (cons cdata users)))
512	       erc-channel-users))
513    users))
514
515(defun erc-get-server-nickname-list ()
516  "Returns a list of known nicknames on the current server."
517  (erc-with-server-buffer
518    (let (nicks)
519      (when (hash-table-p erc-server-users)
520	(maphash (lambda (n user)
521		   (setq nicks
522			 (cons (erc-server-user-nickname user)
523			       nicks)))
524		 erc-server-users)
525	nicks))))
526
527(defun erc-get-channel-nickname-list ()
528  "Returns a list of known nicknames on the current channel."
529  (let (nicks)
530    (when (hash-table-p erc-channel-users)
531      (maphash (lambda (n cdata)
532		 (setq nicks
533		       (cons (erc-server-user-nickname (car cdata))
534			     nicks)))
535	       erc-channel-users)
536      nicks)))
537
538(defun erc-get-server-nickname-alist ()
539  "Returns an alist of known nicknames on the current server."
540  (erc-with-server-buffer
541    (let (nicks)
542      (when (hash-table-p erc-server-users)
543	(maphash (lambda (n user)
544		   (setq nicks
545			 (cons (cons (erc-server-user-nickname user) nil)
546			       nicks)))
547		 erc-server-users)
548	nicks))))
549
550(defun erc-get-channel-nickname-alist ()
551  "Returns an alist of known nicknames on the current channel."
552  (let (nicks)
553    (when (hash-table-p erc-channel-users)
554      (maphash (lambda (n cdata)
555		 (setq nicks
556		       (cons (cons (erc-server-user-nickname (car cdata)) nil)
557			     nicks)))
558	       erc-channel-users)
559      nicks)))
560
561(defun erc-sort-channel-users-by-activity (list)
562  "Sorts LIST such that users which have spoken most recently are
563listed first.  LIST must be of the form (USER . CHANNEL-DATA).
564
565See also: `erc-get-channel-user-list'."
566  (sort list
567	(lambda (x y)
568	  (when (and
569		 (cdr x) (cdr y))
570	    (let ((tx (erc-channel-user-last-message-time (cdr x)))
571		  (ty (erc-channel-user-last-message-time (cdr y))))
572	      (if tx
573		  (if ty
574		      (time-less-p ty tx)
575		    t)
576		nil))))))
577
578(defun erc-sort-channel-users-alphabetically (list)
579  "Sort LIST so that users' nicknames are in alphabetical order.
580LIST must be of the form (USER . CHANNEL-DATA).
581
582See also: `erc-get-channel-user-list'."
583  (sort list
584	(lambda (x y)
585	  (when (and
586		 (cdr x) (cdr y))
587	    (let ((nickx (downcase (erc-server-user-nickname (car x))))
588		  (nicky (downcase (erc-server-user-nickname (car y)))))
589	      (if nickx
590		  (if nicky
591		      (string-lessp nickx nicky)
592		    t)
593		nil))))))
594
595(defvar erc-channel-topic nil
596  "A topic string for the channel.  Should only be used in channel-buffers.")
597(make-variable-buffer-local 'erc-channel-topic)
598
599(defvar erc-channel-modes nil
600  "List of strings representing channel modes.
601E.g. '(\"i\" \"m\" \"s\" \"b Quake!*@*\")
602\(not sure the ban list will be here, but why not)")
603(make-variable-buffer-local 'erc-channel-modes)
604
605(defvar erc-insert-marker nil
606  "The place where insertion of new text in erc buffers should happen.")
607(make-variable-buffer-local 'erc-insert-marker)
608
609(defvar erc-input-marker nil
610  "The marker where input should be inserted.")
611(make-variable-buffer-local 'erc-input-marker)
612
613(defun erc-string-no-properties (string)
614  "Return a copy of STRING will all text-properties removed."
615  (let ((newstring (copy-sequence string)))
616    (set-text-properties 0 (length newstring) nil newstring)
617    newstring))
618
619(defcustom erc-prompt "ERC>"
620  "Prompt used by ERC.  Trailing whitespace is not required."
621  :group 'erc-display
622  :type '(choice string function))
623
624(defun erc-prompt ()
625  "Return the input prompt as a string.
626
627See also the variable `erc-prompt'."
628  (let ((prompt (if (functionp erc-prompt)
629		    (funcall erc-prompt)
630		  erc-prompt)))
631    (if (> (length prompt) 0)
632	(concat prompt " ")
633      prompt)))
634
635(defcustom erc-command-indicator nil
636  "Indicator used by ERC for showing commands.
637
638If non-nil, this will be used in the ERC buffer to indicate
639commands (i.e., input starting with a '/').
640
641If nil, the prompt will be constructed from the variable `erc-prompt'."
642  :group 'erc-display
643  :type '(choice (const nil) string function))
644
645(defun erc-command-indicator ()
646  "Return the command indicator prompt as a string.
647
648This only has any meaning if the variable `erc-command-indicator' is non-nil."
649  (and erc-command-indicator
650       (let ((prompt (if (functionp erc-command-indicator)
651			 (funcall erc-command-indicator)
652			 erc-command-indicator)))
653	 (if (> (length prompt) 0)
654	     (concat prompt " ")
655	     prompt))))
656
657(defcustom erc-notice-prefix "*** "
658  "*Prefix for all notices."
659  :group 'erc-display
660  :type 'string)
661
662(defcustom erc-notice-highlight-type 'all
663  "*Determines how to highlight notices.
664See `erc-notice-prefix'.
665
666The following values are allowed:
667
668    'prefix - highlight notice prefix only
669    'all    - highlight the entire notice
670
671Any other value disables notice's highlighting altogether."
672  :group 'erc-display
673  :type '(choice (const :tag "highlight notice prefix only" prefix)
674		 (const :tag "highlight the entire notice" all)
675		 (const :tag "don't highlight notices at all" nil)))
676
677(defcustom erc-echo-notice-hook nil
678  "*Specifies a list of functions to call to echo a private
679notice.  Each function is called with four arguments, the string
680to display, the parsed server message, the target buffer (or
681nil), and the sender.  The functions are called in order, until a
682function evaluates to non-nil.  These hooks are called after
683those specified in `erc-echo-notice-always-hook'.
684
685See also: `erc-echo-notice-always-hook',
686`erc-echo-notice-in-default-buffer',
687`erc-echo-notice-in-target-buffer',
688`erc-echo-notice-in-minibuffer',
689`erc-echo-notice-in-server-buffer',
690`erc-echo-notice-in-active-non-server-buffer',
691`erc-echo-notice-in-active-buffer',
692`erc-echo-notice-in-user-buffers',
693`erc-echo-notice-in-user-and-target-buffers',
694`erc-echo-notice-in-first-user-buffer'"
695  :group 'erc-hooks
696  :type 'hook
697  :options '(erc-echo-notice-in-default-buffer
698	     erc-echo-notice-in-target-buffer
699	     erc-echo-notice-in-minibuffer
700	     erc-echo-notice-in-server-buffer
701	     erc-echo-notice-in-active-non-server-buffer
702	     erc-echo-notice-in-active-buffer
703	     erc-echo-notice-in-user-buffers
704	     erc-echo-notice-in-user-and-target-buffers
705	     erc-echo-notice-in-first-user-buffer))
706
707(defcustom erc-echo-notice-always-hook
708  '(erc-echo-notice-in-default-buffer)
709  "*Specifies a list of functions to call to echo a private
710notice.  Each function is called with four arguments, the string
711to display, the parsed server message, the target buffer (or
712nil), and the sender.  The functions are called in order, and all
713functions are called.  These hooks are called before those
714specified in `erc-echo-notice-hook'.
715
716See also: `erc-echo-notice-hook',
717`erc-echo-notice-in-default-buffer',
718`erc-echo-notice-in-target-buffer',
719`erc-echo-notice-in-minibuffer',
720`erc-echo-notice-in-server-buffer',
721`erc-echo-notice-in-active-non-server-buffer',
722`erc-echo-notice-in-active-buffer',
723`erc-echo-notice-in-user-buffers',
724`erc-echo-notice-in-user-and-target-buffers',
725`erc-echo-notice-in-first-user-buffer'"
726  :group 'erc-hooks
727  :type 'hook
728  :options '(erc-echo-notice-in-default-buffer
729	     erc-echo-notice-in-target-buffer
730	     erc-echo-notice-in-minibuffer
731	     erc-echo-notice-in-server-buffer
732	     erc-echo-notice-in-active-non-server-buffer
733	     erc-echo-notice-in-active-buffer
734	     erc-echo-notice-in-user-buffers
735	     erc-echo-notice-in-user-and-target-buffers
736	     erc-echo-notice-in-first-user-buffer))
737
738;; other tunable parameters
739
740(defcustom erc-whowas-on-nosuchnick nil
741  "*If non-nil, do a whowas on a nick if no such nick."
742  :group 'erc
743  :type 'boolean)
744
745(defcustom erc-verbose-server-ping nil
746  "*If non-nil, show every time you get a PING or PONG from the server."
747  :group 'erc-paranoia
748  :type 'boolean)
749
750(defcustom erc-public-away-p nil
751  "*Let others know you are back when you are no longer marked away.
752This happens in this form:
753* <nick> is back (gone for <time>)
754
755Many consider it impolite to do so automatically."
756  :group 'erc
757  :type 'boolean)
758
759(defcustom erc-away-nickname nil
760  "*The nickname to take when you are marked as being away."
761  :group 'erc
762  :type '(choice (const nil)
763		 string))
764
765(defcustom erc-paranoid nil
766  "If non-nil, then all incoming CTCP requests will be shown."
767  :group 'erc-paranoia
768  :type 'boolean)
769
770(defcustom erc-disable-ctcp-replies nil
771  "Disable replies to CTCP requests that require a reply.
772If non-nil, then all incoming CTCP requests that normally require
773an automatic reply (like VERSION or PING) will be ignored.  Good to
774set if some hacker is trying to flood you away."
775  :group 'erc-paranoia
776  :type 'boolean)
777
778(defcustom erc-anonymous-login t
779  "Be paranoid, don't give away your machine name."
780  :group 'erc-paranoia
781  :type 'boolean)
782
783(defcustom erc-prompt-for-channel-key nil
784  "Prompt for channel key when using `erc-join-channel' interactively."
785  :group 'erc
786  :type 'boolean)
787
788(defcustom erc-email-userid "user"
789  "Use this as your email user ID."
790  :group 'erc
791  :type 'string)
792
793(defcustom erc-system-name nil
794  "Use this as the name of your system.
795If nil, ERC will call `system-name' to get this information."
796  :group 'erc
797  :type '(choice (const :tag "Default system name" nil)
798		 string))
799
800(defcustom erc-ignore-list nil
801  "*List of regexps matching user identifiers to ignore.
802
803A user identifier has the form \"nick!login@host\".  If an
804identifier matches, the message from the person will not be
805processed."
806  :group 'erc-ignore
807  :type '(repeat regexp))
808(make-variable-buffer-local 'erc-ignore-list)
809
810(defcustom erc-ignore-reply-list nil
811  "*List of regexps matching user identifiers to ignore completely.
812
813This differs from `erc-ignore-list' in that it also ignores any
814messages directed at the user.
815
816A user identifier has the form \"nick!login@host\".
817
818If an identifier matches, or a message is addressed to a nick
819whose identifier matches, the message will not be processed.
820
821CAVEAT: ERC doesn't know about the user and host of anyone who
822was already in the channel when you joined, but never said
823anything, so it won't be able to match the user and host of those
824people.  You can update the ERC internal info using /WHO *."
825  :group 'erc-ignore
826  :type '(repeat regexp))
827
828(defvar erc-flood-protect t
829  "*If non-nil, flood protection is enabled.
830Flooding is sending too much information to the server in too
831short of an interval, which may cause the server to terminate the
832connection.
833
834See `erc-server-flood-margin' for other flood-related parameters.")
835
836;; Script parameters
837
838(defcustom erc-startup-file-list
839  '("~/.emacs.d/.ercrc.el" "~/.emacs.d/.ercrc"
840    "~/.ercrc.el" "~/.ercrc" ".ercrc.el" ".ercrc")
841  "List of files to try for a startup script.
842The first existent and readable one will get executed.
843
844If the filename ends with `.el' it is presumed to be an Emacs Lisp
845script and it gets (load)ed.  Otherwise is is treated as a bunch of
846regular IRC commands."
847  :group 'erc-scripts
848  :type '(repeat file))
849
850(defcustom erc-script-path nil
851  "List of directories to look for a script in /load command.
852The script is first searched in the current directory, then in each
853directory in the list."
854  :group 'erc-scripts
855  :type '(repeat directory))
856
857(defcustom erc-script-echo t
858  "*If non-nil, echo the IRC script commands locally."
859  :group 'erc-scripts
860  :type 'boolean)
861
862(defvar erc-last-saved-position nil
863  "A marker containing the position the current buffer was last saved at.")
864(make-variable-buffer-local 'erc-last-saved-position)
865
866(defcustom erc-kill-buffer-on-part nil
867  "Kill the channel buffer on PART.
868This variable should probably stay nil, as ERC can reuse buffers if
869you rejoin them later."
870  :group 'erc-quit-and-part
871  :type 'boolean)
872
873(defcustom erc-kill-queries-on-quit nil
874  "Kill all query (also channel) buffers of this server on QUIT.
875See the variable `erc-kill-buffer-on-part' for details."
876  :group 'erc-quit-and-part
877  :type 'boolean)
878
879(defcustom erc-kill-server-buffer-on-quit nil
880  "Kill the server buffer of the process on QUIT."
881  :group 'erc-quit-and-part
882  :type 'boolean)
883
884(defcustom erc-quit-reason-various-alist nil
885  "Alist of possible arguments to the /quit command.
886
887Each element has the form:
888  (REGEXP RESULT)
889
890If REGEXP matches the argument to /quit, then its relevant RESULT
891will be used.  RESULT may be either a string, or a function.  If
892a function, it should return the quit message as a string.
893
894If no elements match, then the empty string is used.
895
896As an example:
897  (setq erc-quit-reason-various-alist
898      '((\"zippy\" erc-quit-reason-zippy)
899	(\"xmms\" dme:now-playing)
900	(\"version\" erc-quit-reason-normal)
901	(\"home\" \"Gone home !\")
902	(\"^$\" \"Default Reason\")))
903If the user types \"/quit zippy\", then a Zippy the Pinhead quotation
904will be used as the quit message."
905  :group 'erc-quit-and-part
906  :type '(repeat (list regexp (choice (string) (function)))))
907
908(defcustom erc-part-reason-various-alist nil
909  "Alist of possible arguments to the /part command.
910
911Each element has the form:
912  (REGEXP RESULT)
913
914If REGEXP matches the argument to /part, then its relevant RESULT
915will be used.  RESULT may be either a string, or a function.  If
916a function, it should return the part message as a string.
917
918If no elements match, then the empty string is used.
919
920As an example:
921  (setq erc-part-reason-various-alist
922      '((\"zippy\" erc-part-reason-zippy)
923	(\"xmms\" dme:now-playing)
924	(\"version\" erc-part-reason-normal)
925	(\"home\" \"Gone home !\")
926	(\"^$\" \"Default Reason\")))
927If the user types \"/part zippy\", then a Zippy the Pinhead quotation
928will be used as the part message."
929  :group 'erc-quit-and-part
930  :type '(repeat (list regexp (choice (string) (function)))))
931
932(defcustom erc-quit-reason 'erc-quit-reason-normal
933  "*A function which returns the reason for quitting.
934
935The function is passed a single argument, the string typed by the
936user after \"/quit\"."
937  :group 'erc-quit-and-part
938  :type '(choice (const erc-quit-reason-normal)
939		 (const erc-quit-reason-zippy)
940		 (const erc-quit-reason-various)
941		 (symbol)))
942
943(defcustom erc-part-reason 'erc-part-reason-normal
944  "A function which returns the reason for parting a channel.
945
946The function is passed a single argument, the string typed by the
947user after \"/PART\"."
948  :group 'erc-quit-and-part
949  :type '(choice (const erc-part-reason-normal)
950		 (const erc-part-reason-zippy)
951		 (const erc-part-reason-various)
952		 (symbol)))
953
954(defvar erc-grab-buffer-name "*erc-grab*"
955  "The name of the buffer created by `erc-grab-region'.")
956
957;; variables available for IRC scripts
958
959(defvar erc-user-information "ERC User"
960  "USER_INFORMATION IRC variable.")
961
962;; Hooks
963
964(defgroup erc-hooks nil
965  "Hook variables for fancy customizations of ERC."
966  :group 'erc)
967
968(defcustom erc-mode-hook nil
969  "Hook run after `erc-mode' setup is finished."
970  :group 'erc-hooks
971  :type 'hook
972  :options '(erc-add-scroll-to-bottom))
973
974(defcustom erc-timer-hook nil
975  "Put functions which should get called more or less periodically here.
976The idea is that servers always play ping pong with the client, and so there
977is no need for any idle-timer games with Emacs."
978  :group 'erc-hooks
979  :type 'hook)
980
981(defcustom erc-insert-pre-hook nil
982  "Hook called first when some text is inserted through `erc-display-line'.
983It gets called with one argument, STRING.
984To be able to modify the inserted text, use `erc-insert-modify-hook' instead.
985Filtering functions can set `erc-insert-this' to nil to avoid
986display of that particular string at all."
987  :group 'erc-hooks
988  :type 'hook)
989
990(defcustom erc-send-pre-hook nil
991  "Hook called first when some text is sent through `erc-send-current-line'.
992It gets called with one argument, STRING.
993
994To change the text that will be sent, set the variable STR which is
995used in `erc-send-current-line'.
996
997To change the text inserted into the buffer without changing the text
998that will be sent, use `erc-send-modify-hook' instead.
999
1000Filtering functions can set `erc-send-this' to nil to avoid sending of
1001that particular string at all and `erc-insert-this' to prevent
1002inserting that particular string into the buffer.
1003
1004Note that it's useless to set `erc-send-this' to nil and
1005`erc-insert-this' to t.  ERC is sane enough to not insert the text
1006anyway."
1007  :group 'erc-hooks
1008  :type 'hook)
1009
1010(defvar erc-insert-this t
1011  "Insert the text into the target buffer or not.
1012Functions on `erc-insert-pre-hook' can set this variable to nil
1013if they wish to avoid insertion of a particular string.")
1014
1015(defvar erc-send-this t
1016  "Send the text to the target or not.
1017Functions on `erc-send-pre-hook' can set this variable to nil
1018if they wish to avoid sending of a particular string.")
1019
1020(defcustom erc-insert-modify-hook ()
1021  "Insertion hook for functions that will change the text's appearance.
1022This hook is called just after `erc-insert-pre-hook' when the value
1023of `erc-insert-this' is t.
1024While this hook is run, narrowing is in effect and `current-buffer' is
1025the buffer where the text got inserted.  One possible value to add here
1026is `erc-fill'."
1027  :group 'erc-hooks
1028  :type 'hook)
1029
1030(defcustom erc-insert-post-hook nil
1031  "This hook is called just after `erc-insert-modify-hook'.
1032At this point, all modifications from prior hook functions are done."
1033  :group 'erc-hooks
1034  :type 'hook
1035  :options '(erc-truncate-buffer
1036	     erc-make-read-only
1037	     erc-save-buffer-in-logs))
1038
1039(defcustom erc-send-modify-hook nil
1040  "Sending hook for functions that will change the text's appearance.
1041This hook is called just after `erc-send-pre-hook' when the values
1042of `erc-send-this' and `erc-insert-this' are both t.
1043While this hook is run, narrowing is in effect and `current-buffer' is
1044the buffer where the text got inserted.
1045
1046Note that no function in this hook can change the appearance of the
1047text that is sent.  Only changing the sent text's appearance on the
1048sending user's screen is possible.  One possible value to add here
1049is `erc-fill'."
1050  :group 'erc-hooks
1051  :type 'hook)
1052
1053(defcustom erc-send-post-hook nil
1054  "This hook is called just after `erc-send-modify-hook'.
1055At this point, all modifications from prior hook functions are done.
1056NOTE: The functions on this hook are called _before_ sending a command
1057to the server.
1058
1059This function is called with narrowing, ala `erc-send-modify-hook'."
1060  :group 'erc-hooks
1061  :type 'hook
1062  :options '(erc-make-read-only))
1063
1064(defcustom erc-send-completed-hook
1065  (when (featurep 'emacspeak)
1066    (list (byte-compile
1067	   (lambda (str)
1068	     (emacspeak-auditory-icon 'select-object)))))
1069  "Hook called after a message has been parsed by ERC.
1070
1071The single argument to the functions is the unmodified string
1072which the local user typed."
1073  :group 'erc-hooks
1074  :type 'hook)
1075;; mode-specific tables
1076
1077(defvar erc-mode-syntax-table
1078  (let ((syntax-table (make-syntax-table)))
1079    (modify-syntax-entry ?\" ".   " syntax-table)
1080    (modify-syntax-entry ?\\ ".   " syntax-table)
1081    (modify-syntax-entry ?' "w   " syntax-table)
1082    ;; Make dabbrev-expand useful for nick names
1083    (modify-syntax-entry ?< "." syntax-table)
1084    (modify-syntax-entry ?> "." syntax-table)
1085    syntax-table)
1086  "Syntax table used while in ERC mode.")
1087
1088(defvar erc-mode-abbrev-table nil
1089  "Abbrev table used while in ERC mode.")
1090(define-abbrev-table 'erc-mode-abbrev-table ())
1091
1092(defvar erc-mode-map
1093  (let ((map (make-sparse-keymap)))
1094    (define-key map "\C-m" 'erc-send-current-line)
1095    (define-key map "\C-a" 'erc-bol)
1096    (define-key map [home] 'erc-bol)
1097    (define-key map "\C-c\C-a" 'erc-bol)
1098    (define-key map "\C-c\C-b" 'erc-iswitchb)
1099    (define-key map "\C-c\C-c" 'erc-toggle-interpret-controls)
1100    (define-key map "\C-c\C-d" 'erc-input-action)
1101    (define-key map "\C-c\C-e" 'erc-toggle-ctcp-autoresponse)
1102    (define-key map "\C-c\C-f" 'erc-toggle-flood-control)
1103    (define-key map "\C-c\C-i" 'erc-invite-only-mode)
1104    (define-key map "\C-c\C-j" 'erc-join-channel)
1105    (define-key map "\C-c\C-n" 'erc-channel-names)
1106    (define-key map "\C-c\C-o" 'erc-get-channel-mode-from-keypress)
1107    (define-key map "\C-c\C-p" 'erc-part-from-channel)
1108    (define-key map "\C-c\C-q" 'erc-quit-server)
1109    (define-key map "\C-c\C-r" 'erc-remove-text-properties-region)
1110    (define-key map "\C-c\C-t" 'erc-set-topic)
1111    (define-key map "\C-c\C-u" 'erc-kill-input)
1112    (define-key map "\M-\t" 'ispell-complete-word)
1113    (define-key map "\t" 'erc-complete-word)
1114
1115    ;; Suppress `font-lock-fontify-block' key binding since it
1116    ;; destroys face properties.
1117    (if (fboundp 'command-remapping)
1118	(define-key map [remap font-lock-fontify-block] 'undefined)
1119      (substitute-key-definition
1120       'font-lock-fontify-block 'undefined map global-map))
1121
1122    map)
1123  "ERC keymap.")
1124
1125;; Faces
1126
1127; Honestly, I have a horrible sense of color and the "defaults" below
1128; are supposed to be really bad. But colors ARE required in IRC to
1129; convey different parts of conversation. If you think you know better
1130; defaults - send them to me.
1131
1132;; Now colors are a bit nicer, at least to my eyes.
1133;; You may still want to change them to better fit your background.-- S.B.
1134
1135(defgroup erc-faces nil
1136  "Faces for ERC."
1137  :group 'erc)
1138
1139(defface erc-default-face '((t))
1140  "ERC default face."
1141  :group 'erc-faces)
1142
1143(defface erc-direct-msg-face '((t (:foreground "IndianRed")))
1144  "ERC face used for messages you receive in the main erc buffer."
1145  :group 'erc-faces)
1146
1147(defface erc-header-line
1148  '((t (:foreground "grey20" :background "grey90")))
1149  "ERC face used for the header line.
1150
1151This will only be used if `erc-header-line-face-method' is non-nil."
1152  :group 'erc-faces)
1153
1154(defface erc-input-face '((t (:foreground "brown")))
1155  "ERC face used for your input."
1156  :group 'erc-faces)
1157
1158(defface erc-prompt-face
1159  '((t (:bold t :foreground "Black" :background "lightBlue2")))
1160  "ERC face for the prompt."
1161  :group 'erc-faces)
1162
1163(defface erc-command-indicator-face
1164    '((t (:bold t)))
1165  "ERC face for the command indicator.
1166See the variable `erc-command-indicator'."
1167  :group 'erc-faces)
1168
1169(defface erc-notice-face '((t (:bold t :foreground "SlateBlue")))
1170  "ERC face for notices."
1171  :group 'erc-faces)
1172
1173(defface erc-action-face '((t (:bold t)))
1174  "ERC face for actions generated by /ME."
1175  :group 'erc-faces)
1176
1177(defface erc-error-face '((t (:foreground "red")))
1178  "ERC face for errors."
1179  :group 'erc-faces)
1180
1181;; same default color as `erc-input-face'
1182(defface erc-my-nick-face '((t (:bold t :foreground "brown")))
1183  "ERC face for your current nickname in messages sent by you.
1184See also `erc-show-my-nick'."
1185  :group 'erc-faces)
1186
1187(defface erc-nick-default-face '((t (:bold t)))
1188  "ERC nickname default face."
1189  :group 'erc-faces)
1190
1191(defface erc-nick-msg-face '((t (:bold t :foreground "IndianRed")))
1192  "ERC nickname face for private messages."
1193  :group 'erc-faces)
1194
1195;; Debugging support
1196
1197(defvar erc-log-p nil
1198  "When set to t, generate debug messages in a separate debug buffer.")
1199
1200(defvar erc-debug-log-file (expand-file-name "ERC.debug")
1201  "Debug log file name.")
1202
1203(defvar erc-dbuf nil)
1204(make-variable-buffer-local 'erc-dbuf)
1205
1206(defmacro define-erc-module (name alias doc enable-body disable-body
1207			     &optional local-p)
1208  "Define a new minor mode using ERC conventions.
1209Symbol NAME is the name of the module.
1210Symbol ALIAS is the alias to use, or nil.
1211DOC is the documentation string to use for the minor mode.
1212ENABLE-BODY is a list of expressions used to enable the mode.
1213DISABLE-BODY is a list of expressions used to disable the mode.
1214If LOCAL-P is non-nil, the mode will be created as a buffer-local
1215mode, rather than a global one.
1216
1217This will define a minor mode called erc-NAME-mode, possibly
1218an alias erc-ALIAS-mode, as well as the helper functions
1219erc-NAME-enable, and erc-NAME-disable.
1220
1221Example:
1222
1223  ;;;###autoload (autoload 'erc-replace-mode \"erc-replace\")
1224  (define-erc-module replace nil
1225    \"This mode replaces incoming text according to `erc-replace-alist'.\"
1226    ((add-hook 'erc-insert-modify-hook
1227	       'erc-replace-insert))
1228    ((remove-hook 'erc-insert-modify-hook
1229		  'erc-replace-insert)))"
1230  (let* ((sn (symbol-name name))
1231	 (mode (intern (format "erc-%s-mode" (downcase sn))))
1232	 (group (intern (format "erc-%s" (downcase sn))))
1233	 (enable (intern (format "erc-%s-enable" (downcase sn))))
1234	 (disable (intern (format "erc-%s-disable" (downcase sn)))))
1235    `(progn
1236       (erc-define-minor-mode
1237	,mode
1238	,(format "Toggle ERC %S mode.
1239With arg, turn ERC %S mode on if and only if arg is positive.
1240%s" name name doc)
1241	nil nil nil
1242	:global ,(not local-p) :group (quote ,group)
1243	(if ,mode
1244	    (,enable)
1245	  (,disable)))
1246       (defun ,enable ()
1247	 ,(format "Enable ERC %S mode."
1248		  name)
1249	 (interactive)
1250	 (add-to-list 'erc-modules (quote ,name))
1251	 (setq ,mode t)
1252	 ,@enable-body)
1253       (defun ,disable ()
1254	 ,(format "Disable ERC %S mode."
1255		  name)
1256	 (interactive)
1257	 (setq erc-modules (delq (quote ,name) erc-modules))
1258	 (setq ,mode nil)
1259	 ,@disable-body)
1260       ,(when (and alias (not (eq name alias)))
1261	  `(defalias
1262	     (quote
1263	      ,(intern
1264		(format "erc-%s-mode"
1265			(downcase (symbol-name alias)))))
1266	     (quote
1267	      ,mode)))
1268       ;; For find-function and find-variable.
1269       (put ',mode    'definition-name ',name)
1270       (put ',enable  'definition-name ',name)
1271       (put ',disable 'definition-name ',name))))
1272
1273(put 'define-erc-module 'doc-string-elt 3)
1274
1275(defun erc-once-with-server-event (event &rest forms)
1276  "Execute FORMS the next time EVENT occurs in the `current-buffer'.
1277
1278You should make sure that `current-buffer' is a server buffer.
1279
1280This function temporarily adds a function to EVENT's hook to
1281execute FORMS.  After FORMS are run, the function is removed from
1282EVENT's hook.  The last expression of FORMS should be either nil
1283or t, where nil indicates that the other functions on EVENT's hook
1284should be run too, and t indicates that other functions should
1285not be run.
1286
1287Please be sure to use this function in server-buffers.  In
1288channel-buffers it may not work at all, as it uses the LOCAL
1289argument of `add-hook' and `remove-hook' to ensure multiserver
1290capabilities."
1291  (unless (erc-server-buffer-p)
1292    (error
1293     "You should only run `erc-once-with-server-event' in a server buffer"))
1294  (let ((fun (make-symbol "fun"))
1295	(hook (erc-get-hook event)))
1296     (put fun 'erc-original-buffer (current-buffer))
1297     (fset fun `(lambda (proc parsed)
1298		  (with-current-buffer (get ',fun 'erc-original-buffer)
1299		    (remove-hook ',hook ',fun t))
1300		  (fmakunbound ',fun)
1301		  ,@forms))
1302     (add-hook hook fun nil t)
1303     fun))
1304
1305(defun erc-once-with-server-event-global (event &rest forms)
1306  "Execute FORMS the next time EVENT occurs in any server buffer.
1307
1308This function temporarily prepends a function to EVENT's hook to
1309execute FORMS.  After FORMS are run, the function is removed from
1310EVENT's hook.  The last expression of FORMS should be either nil
1311or t, where nil indicates that the other functions on EVENT's hook
1312should be run too, and t indicates that other functions should
1313not be run.
1314
1315When FORMS execute, the current buffer is the server buffer associated with the
1316connection over which the data was received that triggered EVENT."
1317  (let ((fun (make-symbol "fun"))
1318	(hook (erc-get-hook event)))
1319     (fset fun `(lambda (proc parsed)
1320		  (remove-hook ',hook ',fun)
1321		  (fmakunbound ',fun)
1322		  ,@forms))
1323     (add-hook hook fun nil nil)
1324     fun))
1325
1326(defmacro erc-log (string)
1327  "Logs STRING if logging is on (see `erc-log-p')."
1328  `(when erc-log-p
1329     (erc-log-aux ,string)))
1330
1331(defun erc-server-buffer ()
1332  "Return the server buffer for the current buffer's process.
1333The buffer-local variable `erc-server-process' is used to find
1334the process buffer."
1335  (and (erc-server-buffer-live-p)
1336       (process-buffer erc-server-process)))
1337
1338(defun erc-server-buffer-live-p ()
1339  "Return t if the server buffer has not been killed."
1340  (and (processp erc-server-process)
1341       (buffer-live-p (process-buffer erc-server-process))))
1342
1343(defun erc-server-buffer-p (&optional buffer)
1344  "Return non-nil if argument BUFFER is an ERC server buffer.
1345
1346If BUFFER is nil, the current buffer is used."
1347  (with-current-buffer (or buffer (current-buffer))
1348    (and (eq major-mode 'erc-mode)
1349	 (null (erc-default-target)))))
1350
1351(defun erc-open-server-buffer-p (&optional buffer)
1352  "Return non-nil if argument BUFFER is an ERC server buffer that
1353has an open IRC process.
1354
1355If BUFFER is nil, the current buffer is used."
1356  (and (erc-server-buffer-p)
1357       (erc-server-process-alive)))
1358
1359(defun erc-query-buffer-p (&optional buffer)
1360  "Return non-nil if BUFFER is an ERC query buffer.
1361If BUFFER is nil, the current buffer is used."
1362  (with-current-buffer (or buffer (current-buffer))
1363    (let ((target (erc-default-target)))
1364      (and (eq major-mode 'erc-mode)
1365	   target
1366	   (not (memq (aref target 0) '(?# ?& ?+ ?!)))))))
1367
1368(defun erc-ison-p (nick)
1369  "Return non-nil if NICK is online."
1370  (interactive "sNick: ")
1371  (erc-with-server-buffer
1372    (let ((erc-online-p 'unknown))
1373      (erc-once-with-server-event
1374       303
1375       `(let ((ison (split-string (aref parsed 3))))
1376	  (setq erc-online-p (car (erc-member-ignore-case ,nick ison)))
1377	  t))
1378      (erc-server-send (format "ISON %s" nick))
1379      (while (eq erc-online-p 'unknown) (accept-process-output))
1380      (if (interactive-p)
1381	  (message "%s is %sonline"
1382		   (or erc-online-p nick)
1383		   (if erc-online-p "" "not "))
1384	erc-online-p))))
1385
1386(defun erc-log-aux (string)
1387  "Do the debug logging of STRING."
1388  (let ((cb (current-buffer))
1389	(point 1)
1390	(was-eob nil)
1391	(session-buffer (erc-server-buffer)))
1392    (if session-buffer
1393	(progn
1394	  (set-buffer session-buffer)
1395	  (if (not (and erc-dbuf (bufferp erc-dbuf) (buffer-live-p erc-dbuf)))
1396	      (progn
1397		(setq erc-dbuf (get-buffer-create
1398				(concat "*ERC-DEBUG: "
1399					erc-session-server "*")))))
1400	  (set-buffer erc-dbuf)
1401	  (setq point (point))
1402	  (setq was-eob (eobp))
1403	  (goto-char (point-max))
1404	  (insert (concat "** " string "\n"))
1405	  (if was-eob (goto-char (point-max))
1406	    (goto-char point))
1407	  (set-buffer cb))
1408      (message "ERC: ** %s" string))))
1409
1410;; Last active buffer, to print server messages in the right place
1411
1412(defvar erc-active-buffer nil
1413  "The current active buffer, the one where the user typed the last command.
1414Defaults to the server buffer, and should only be set in the
1415server buffer.")
1416(make-variable-buffer-local 'erc-active-buffer)
1417
1418(defun erc-active-buffer ()
1419  "Return the value of `erc-active-buffer' for the current server.
1420Defaults to the server buffer."
1421  (erc-with-server-buffer
1422    (if (buffer-live-p erc-active-buffer)
1423	erc-active-buffer
1424      (setq erc-active-buffer (current-buffer)))))
1425
1426(defun erc-set-active-buffer (buffer)
1427  "Set the value of `erc-active-buffer' to BUFFER."
1428  (cond ((erc-server-buffer)
1429	 (with-current-buffer (erc-server-buffer)
1430	   (setq erc-active-buffer buffer)))
1431	(t (setq erc-active-buffer buffer))))
1432
1433;; Mode activation routines
1434
1435(defun erc-mode ()
1436  "Major mode for Emacs IRC.
1437Special commands:
1438
1439\\{erc-mode-map}
1440
1441Turning on `erc-mode' runs the hook `erc-mode-hook'."
1442  (kill-all-local-variables)
1443  (use-local-map erc-mode-map)
1444  (setq mode-name "ERC"
1445	major-mode 'erc-mode
1446	local-abbrev-table erc-mode-abbrev-table)
1447  (set-syntax-table erc-mode-syntax-table)
1448  (when (boundp 'next-line-add-newlines)
1449    (set (make-local-variable 'next-line-add-newlines) nil))
1450  (setq line-move-ignore-invisible t)
1451  (set (make-local-variable 'paragraph-separate)
1452       (concat "\C-l\\|\\(^" (regexp-quote (erc-prompt)) "\\)"))
1453  (set (make-local-variable 'paragraph-start)
1454       (concat "\\(" (regexp-quote (erc-prompt)) "\\)"))
1455  ;; Run the mode hooks
1456  (run-hooks 'erc-mode-hook))
1457
1458;; activation
1459
1460(defconst erc-default-server "irc.freenode.net"
1461  "IRC server to use if it cannot be detected otherwise.")
1462
1463(defconst erc-default-port "6667"
1464  "IRC port to use if it cannot be detected otherwise.")
1465
1466(defcustom erc-join-buffer 'buffer
1467  "Determines how to display the newly created IRC buffer.
1468'window - in another window,
1469'window-noselect - in another window, but don't select that one,
1470'frame - in another frame,
1471'bury - bury it in a new buffer,
1472any other value - in place of the current buffer."
1473  :group 'erc-buffers
1474  :type '(choice (const window)
1475		 (const window-noselect)
1476		 (const frame)
1477		 (const bury)
1478		 (const buffer)))
1479
1480(defcustom erc-frame-alist nil
1481  "*Alist of frame parameters for creating erc frames.
1482A value of nil means to use `default-frame-alist'."
1483  :group 'erc-buffers
1484  :type '(repeat (cons :format "%v"
1485		       (symbol :tag "Parameter")
1486		       (sexp :tag "Value"))))
1487
1488(defcustom erc-frame-dedicated-flag nil
1489  "*Non-nil means the erc frames are dedicated to that buffer.
1490This only has effect when `erc-join-buffer' is set to `frame'."
1491  :group 'erc-buffers
1492  :type 'boolean)
1493
1494(defun erc-channel-p (channel)
1495  "Return non-nil if CHANNEL seems to be an IRC channel name."
1496  (cond ((stringp channel)
1497	 (memq (aref channel 0) '(?# ?& ?+ ?!)))
1498	((and (bufferp channel) (buffer-live-p channel))
1499	 (with-current-buffer channel
1500	   (erc-channel-p (erc-default-target))))
1501	(t nil)))
1502
1503(defcustom erc-reuse-buffers t
1504  "*If nil, create new buffers on joining a channel/query.
1505If non-nil, a new buffer will only be created when you join
1506channels with same names on different servers, or have query buffers
1507open with nicks of the same name on different servers.  Otherwise,
1508the existing buffers will be reused."
1509  :group 'erc-buffers
1510  :type 'boolean)
1511
1512(defun erc-normalize-port (port)
1513  "Normalize the port specification PORT to integer form.
1514PORT may be an integer, a string or a symbol.  If it is a string or a
1515symbol, it may have these values:
1516* irc         -> 194
1517* ircs        -> 994
1518* ircd        -> 6667
1519* ircd-dalnet -> 7000"
1520  (cond
1521   ((symbolp port)
1522    (erc-normalize-port (symbol-name port)))
1523   ((stringp port)
1524    (let ((port-nr (string-to-number port)))
1525      (cond
1526       ((> port-nr 0)
1527	port-nr)
1528       ((string-equal port "irc")
1529	194)
1530       ((string-equal port "ircs")
1531	994)
1532       ((string-equal port "ircd")
1533	6667)
1534       ((string-equal port "ircd-dalnet")
1535	7000)
1536       (t
1537	nil))))
1538   ((numberp port)
1539    port)
1540   (t
1541    nil)))
1542
1543(defun erc-port-equal (a b)
1544  "Check whether ports A and B are equal."
1545  (= (erc-normalize-port a) (erc-normalize-port b)))
1546
1547(defun erc-generate-new-buffer-name (server port target &optional proc)
1548  "Create a new buffer name based on the arguments."
1549  (when (numberp port) (setq port (number-to-string port)))
1550  (let* ((buf-name (or target
1551		       (or (let ((name (concat server ":" port)))
1552			     (when (> (length name) 1)
1553			       name))
1554			   ; This fallback should in fact never happen
1555			   "*erc-server-buffer*"))))
1556    ;; Reuse existing buffers, but not if the buffer is a connected server
1557    ;; buffer and not if its associated with a different server than the
1558    ;; current ERC buffer.
1559    (if (and erc-reuse-buffers
1560	     (get-buffer buf-name)
1561	     (or target
1562		 (with-current-buffer (get-buffer buf-name)
1563		   (and (erc-server-buffer-p)
1564			(not (erc-server-process-alive)))))
1565	     (with-current-buffer (get-buffer buf-name)
1566	       (and (string= erc-session-server server)
1567		    (erc-port-equal erc-session-port port))))
1568	buf-name
1569      (generate-new-buffer-name buf-name))))
1570
1571(defun erc-get-buffer-create (server port target &optional proc)
1572  "Create a new buffer based on the arguments."
1573  (get-buffer-create (erc-generate-new-buffer-name server port target proc)))
1574
1575
1576(defun erc-member-ignore-case (string list)
1577  "Return non-nil if STRING is a member of LIST.
1578
1579All strings are compared according to IRC protocol case rules, see
1580`erc-downcase'."
1581  (setq string (erc-downcase string))
1582  (catch 'result
1583    (while list
1584      (if (string= string (erc-downcase (car list)))
1585	  (throw 'result list)
1586	(setq list (cdr list))))))
1587
1588(defmacro erc-with-buffer (spec &rest body)
1589  "Execute BODY in the buffer associated with SPEC.
1590
1591SPEC should have the form
1592
1593 (TARGET [PROCESS])
1594
1595If TARGET is a buffer, use it.  Otherwise, use the buffer
1596matching TARGET in the process specified by PROCESS.
1597
1598If PROCESS is nil, use the current `erc-server-process'.
1599See `erc-get-buffer' for details.
1600
1601See also `with-current-buffer'.
1602
1603\(fn (TARGET [PROCESS]) BODY...)"
1604  (let ((buf (make-symbol "buf"))
1605	(proc (make-symbol "proc"))
1606	(target (make-symbol "target"))
1607	(process (make-symbol "process")))
1608    `(let* ((,target ,(car spec))
1609	    (,process ,(cadr spec))
1610	    (,buf (if (bufferp ,target)
1611		      ,target
1612		    (let ((,proc (or ,process
1613				     (and (processp erc-server-process)
1614					  erc-server-process))))
1615		      (if (and ,target ,proc)
1616			  (erc-get-buffer ,target ,proc))))))
1617       (when (buffer-live-p ,buf)
1618	 (with-current-buffer ,buf
1619	   ,@body)))))
1620(put 'erc-with-buffer 'lisp-indent-function 1)
1621(put 'erc-with-buffer 'edebug-form-spec '((form &optional form) body))
1622
1623(defun erc-get-buffer (target &optional proc)
1624  "Return the buffer matching TARGET in the process PROC.
1625If PROC is not supplied, all processes are searched."
1626  (let ((downcased-target (erc-downcase target)))
1627    (catch 'buffer
1628      (erc-buffer-filter
1629       (lambda ()
1630	 (let ((current (erc-default-target)))
1631	   (and (stringp current)
1632		(string-equal downcased-target (erc-downcase current))
1633		(throw 'buffer (current-buffer)))))
1634       proc))))
1635
1636(defun erc-buffer-filter (predicate &optional proc)
1637  "Return a list of `erc-mode' buffers matching certain criteria.
1638PREDICATE is a function executed with each buffer, if it returns t, that buffer
1639is considered a valid match.
1640
1641PROC is either an `erc-server-process', identifying a certain
1642server connection, or nil which means all open connections."
1643  (save-excursion
1644    (delq
1645     nil
1646     (mapcar (lambda (buf)
1647	       (when (buffer-live-p buf)
1648		 (with-current-buffer buf
1649		   (and (eq major-mode 'erc-mode)
1650			(or (not proc)
1651			    (eq proc erc-server-process))
1652			(funcall predicate)
1653			buf))))
1654	     (buffer-list)))))
1655
1656(defun erc-buffer-list (&optional predicate proc)
1657  "Return a list of ERC buffers.
1658PREDICATE is a function which executes with every buffer satisfying
1659the predicate.  If PREDICATE is passed as nil, return a list of all ERC
1660buffers.  If PROC is given, the buffers local variable `erc-server-process'
1661needs to match PROC."
1662  (unless predicate
1663    (setq predicate (lambda () t)))
1664  (erc-buffer-filter predicate proc))
1665
1666(defmacro erc-with-all-buffers-of-server (process pred &rest forms)
1667  "Execute FORMS in all buffers which have same process as this server.
1668FORMS will be evaluated in all buffers having the process PROCESS and
1669where PRED matches or in all buffers of the server process if PRED is
1670nil."
1671  ;; Make the evaluation have the correct order
1672  (let ((pre (make-symbol "pre"))
1673	(pro (make-symbol "pro")))
1674    `(let ((,pro ,process)
1675	   (,pre ,pred))
1676       (mapcar (lambda (buffer)
1677		 (with-current-buffer buffer
1678		   ,@forms))
1679	       (erc-buffer-list ,pre
1680				,pro)))))
1681(put 'erc-with-all-buffers-of-server 'lisp-indent-function 1)
1682(put 'erc-with-all-buffers-of-server 'edebug-form-spec '(form form body))
1683
1684(defun erc-iswitchb (&optional arg)
1685  "Use `iswitchb-read-buffer' to prompt for a ERC buffer to switch to.
1686When invoked with prefix argument, use all erc buffers.  Without prefix
1687ARG, allow only buffers related to same session server.
1688If `erc-track-mode' is in enabled, put the last element of
1689`erc-modified-channels-alist' in front of the buffer list.
1690
1691Due to some yet unresolved reason, global function `iswitchb-mode'
1692needs to be active for this function to work."
1693  (interactive "P")
1694  (eval-when-compile
1695    (require 'iswitchb))
1696  (let ((enabled iswitchb-mode))
1697    (or enabled (iswitchb-mode 1))
1698    (unwind-protect
1699	(let ((iswitchb-make-buflist-hook
1700	       (lambda ()
1701		 (setq iswitchb-temp-buflist
1702		       (mapcar 'buffer-name
1703			       (erc-buffer-list
1704				nil
1705				(when arg erc-server-process)))))))
1706	  (switch-to-buffer
1707	   (iswitchb-read-buffer
1708	    "Switch-to: "
1709	    (if (boundp 'erc-modified-channels-alist)
1710		(buffer-name (caar (last erc-modified-channels-alist)))
1711	      nil)
1712	    t)))
1713      (or enabled (iswitchb-mode -1)))))
1714
1715(defun erc-channel-list (proc)
1716  "Return a list of channel buffers.
1717PROC is the process for the server connection.  If PROC is nil, return
1718all channel buffers on all servers."
1719  (erc-buffer-filter
1720   (lambda ()
1721     (and (erc-default-target)
1722	  (erc-channel-p (erc-default-target))))
1723   proc))
1724
1725(defun erc-buffer-list-with-nick (nick proc)
1726  "Return buffers containing NICK in the `erc-channel-users' list."
1727  (with-current-buffer (process-buffer proc)
1728    (let ((user (gethash (erc-downcase nick) erc-server-users)))
1729      (if user
1730	  (erc-server-user-buffers user)
1731	nil))))
1732
1733;; Some local variables
1734
1735(defvar erc-default-recipients nil
1736  "List of default recipients of the current buffer.")
1737(make-variable-buffer-local 'erc-default-recipients)
1738
1739(defvar erc-session-user-full-name nil
1740  "Full name of the user on the current server.")
1741(make-variable-buffer-local 'erc-session-user-full-name)
1742
1743(defvar erc-channel-user-limit nil
1744  "Limit of users per channel.")
1745(make-variable-buffer-local 'erc-channel-user-limit)
1746
1747(defvar erc-channel-key nil
1748  "Key needed to join channel.")
1749(make-variable-buffer-local 'erc-channel-key)
1750
1751(defvar erc-invitation nil
1752  "Last invitation channel.")
1753(make-variable-buffer-local 'erc-invitation)
1754
1755(defvar erc-away nil
1756  "Non-nil indicates that we are away.
1757
1758Use `erc-away-time' to access this if you might be in a channel
1759buffer rather than a server buffer.")
1760(make-variable-buffer-local 'erc-away)
1761
1762(defvar erc-channel-list nil
1763  "Server channel list.")
1764(make-variable-buffer-local 'erc-channel-list)
1765
1766(defvar erc-bad-nick nil
1767  "Non-nil indicates that we got a `nick in use' error while connecting.")
1768(make-variable-buffer-local 'erc-bad-nick)
1769
1770(defvar erc-logged-in nil
1771  "Non-nil indicates that we are logged in.")
1772(make-variable-buffer-local 'erc-logged-in)
1773
1774(defvar erc-default-nicks nil
1775  "The local copy of `erc-nick' - the list of nicks to choose from.")
1776(make-variable-buffer-local 'erc-default-nicks)
1777
1778(defvar erc-nick-change-attempt-count 0
1779  "Used to keep track of how many times an attempt at changing nick is made.")
1780(make-variable-buffer-local 'erc-nick-change-attempt-count)
1781
1782(defun erc-migrate-modules (mods)
1783  "Migrate old names of ERC modules to new ones."
1784  ;; modify `transforms' to specify what needs to be changed
1785  ;; each item is in the format '(old . new)
1786  (let ((transforms '((pcomplete . completion))))
1787    (erc-delete-dups
1788     (mapcar (lambda (m) (or (cdr (assoc m transforms)) m))
1789	     mods))))
1790
1791(defcustom erc-modules '(netsplit fill button match track completion readonly
1792				  ring autojoin noncommands irccontrols
1793				  stamp menu)
1794  "A list of modules which ERC should enable.
1795If you set the value of this without using `customize' remember to call
1796\(erc-update-modules) after you change it.  When using `customize', modules
1797removed from the list will be disabled."
1798  :get (lambda (sym)
1799	 ;; replace outdated names with their newer equivalents
1800	 (erc-migrate-modules (symbol-value sym)))
1801  :set (lambda (sym val)
1802	 ;; disable modules which have just been removed
1803	 (when (and (boundp 'erc-modules) erc-modules val)
1804	   (dolist (module erc-modules)
1805	     (unless (member module val)
1806	       (let ((f (intern-soft (format "erc-%s-mode" module))))
1807		 (when (and (fboundp f) (boundp f) (symbol-value f))
1808		   (message "Disabling `erc-%s'" module)
1809		   (funcall f 0))))))
1810	 (set sym val)
1811	 ;; this test is for the case where erc hasn't been loaded yet
1812	 (when (fboundp 'erc-update-modules)
1813	   (erc-update-modules)))
1814  :type
1815  '(set
1816    :greedy t
1817    (const :tag "autoaway: Set away status automatically" autoaway)
1818    (const :tag "autojoin: Join channels automatically" autojoin)
1819    (const :tag "button: Buttonize URLs, nicknames, and other text" button)
1820    (const :tag "capab: Mark unidentified users on servers supporting CAPAB"
1821	   capab-identify)
1822    (const :tag "completion: Complete nicknames and commands (programmable)"
1823	   completion)
1824    (const :tag "hecomplete: Complete nicknames and commands (old)" hecomplete)
1825    (const :tag "fill: Wrap long lines" fill)
1826    (const :tag "identd: Launch an identd server on port 8113" identd)
1827    (const :tag "irccontrols: Highlight or remove IRC control characters"
1828	   irccontrols)
1829    (const :tag "log: Save buffers in logs" log)
1830    (const :tag "match: Highlight pals, fools, and other keywords" match)
1831    (const :tag "menu: Display a menu in ERC buffers" menu)
1832    (const :tag "netsplit: Detect netsplits" netsplit)
1833    (const :tag "noncommands: Don't display non-IRC commands after evaluation"
1834	   noncommands)
1835    (const :tag
1836	   "notify: Notify when the online status of certain users changes"
1837	   notify)
1838    (const :tag "page: Process CTCP PAGE requests from IRC" page)
1839    (const :tag "readonly: Make displayed lines read-only" readonly)
1840    (const :tag "replace: Replace text in messages" replace)
1841    (const :tag "ring: Enable an input history" ring)
1842    (const :tag "scrolltobottom: Scroll to the bottom of the buffer"
1843	   scrolltobottom)
1844    (const :tag "services: Identify to Nickserv (IRC Services) automatically"
1845	   services)
1846    (const :tag "smiley: Convert smileys to pretty icons" smiley)
1847    (const :tag "sound: Play sounds when you receive CTCP SOUND requests"
1848	   sound)
1849    (const :tag "stamp: Add timestamps to messages" stamp)
1850    (const :tag "spelling: Check spelling" spelling)
1851    (const :tag "track: Track channel activity in the mode-line" track)
1852    (const :tag "truncate: Truncate buffers to a certain size" truncate)
1853    (const :tag "unmorse: Translate morse code in messages" unmorse)
1854    (repeat :tag "Others" :inline t symbol))
1855  :group 'erc)
1856
1857(defun erc-update-modules ()
1858  "Run this to enable erc-foo-mode for all modules in `erc-modules'."
1859  (let (req)
1860    (dolist (mod erc-modules)
1861      (setq req (concat "erc-" (symbol-name mod)))
1862      (cond
1863       ;; yuck. perhaps we should bring the filenames into sync?
1864       ((string= req "erc-capab-identify")
1865	(setq req "erc-capab"))
1866       ((string= req "erc-completion")
1867	(setq req "erc-pcomplete"))
1868       ((string= req "erc-pcomplete")
1869	(setq mod 'completion))
1870       ((string= req "erc-autojoin")
1871	(setq req "erc-join")))
1872      (condition-case nil
1873	  (require (intern req))
1874	(error nil))
1875      (let ((sym (intern-soft (concat "erc-" (symbol-name mod) "-mode"))))
1876	(if (fboundp sym)
1877	    (funcall sym 1)
1878	  (error "`%s' is not a known ERC module" mod))))))
1879
1880(defun erc-setup-buffer (buffer)
1881  "Consults `erc-join-buffer' to find out how to display `BUFFER'."
1882  (cond ((eq erc-join-buffer 'window)
1883	 (if (active-minibuffer-window)
1884	     (display-buffer buffer)
1885	   (switch-to-buffer-other-window buffer)))
1886	((eq erc-join-buffer 'window-noselect)
1887	 (display-buffer buffer))
1888	((eq erc-join-buffer 'bury)
1889	 nil)
1890	((eq erc-join-buffer 'frame)
1891	 (funcall '(lambda (frame)
1892		     (raise-frame frame)
1893		     (select-frame frame))
1894		  (make-frame (or erc-frame-alist
1895				  default-frame-alist)))
1896	 (switch-to-buffer buffer)
1897	 (when erc-frame-dedicated-flag
1898	   (set-window-dedicated-p (selected-window) t)))
1899	(t
1900	 (if (active-minibuffer-window)
1901	     (display-buffer buffer)
1902	   (switch-to-buffer buffer)))))
1903
1904(defun erc-open (&optional server port nick full-name
1905			   connect passwd tgt-list channel process)
1906  "Connect to SERVER on PORT as NICK with FULL-NAME.
1907
1908If CONNECT is non-nil, connect to the server.  Otherwise assume
1909already connected and just create a separate buffer for the new
1910target CHANNEL.
1911
1912Use PASSWD as user password on the server.  If TGT-LIST is
1913non-nil, use it to initialise `erc-default-recipients'.
1914
1915Returns the buffer for the given server or channel."
1916  (let ((server-announced-name (when (and (boundp 'erc-session-server)
1917					  (string= server erc-session-server))
1918				 erc-server-announced-name))
1919	(connected-p (unless connect erc-server-connected))
1920	(buffer (erc-get-buffer-create server port channel))
1921	(old-buffer (current-buffer))
1922	old-point
1923	continued-session)
1924    (when connect (run-hook-with-args 'erc-before-connect server port nick))
1925    (erc-update-modules)
1926    (set-buffer buffer)
1927    (setq old-point (point))
1928    (erc-mode)
1929    (setq erc-server-announced-name server-announced-name)
1930    (setq erc-server-connected connected-p)
1931    ;; connection parameters
1932    (setq erc-server-process process)
1933    (setq erc-insert-marker (make-marker))
1934    (setq erc-input-marker (make-marker))
1935    ;; go to the end of the buffer and open a new line
1936    ;; (the buffer may have existed)
1937    (goto-char (point-max))
1938    (forward-line 0)
1939    (when (get-text-property (point) 'erc-prompt)
1940      (setq continued-session t)
1941      (set-marker erc-input-marker
1942		  (or (next-single-property-change (point) 'erc-prompt)
1943		      (point-max))))
1944    (unless continued-session
1945      (goto-char (point-max))
1946      (insert "\n"))
1947    (set-marker erc-insert-marker (point))
1948    ;; stack of default recipients
1949    (setq erc-default-recipients tgt-list)
1950    (setq erc-server-current-nick nil)
1951    ;; Initialize erc-server-users and erc-channel-users
1952    (if connect
1953	(progn ;; server buffer
1954	  (setq erc-server-users
1955		(make-hash-table :test 'equal))
1956	  (setq erc-channel-users nil))
1957      (progn ;; target buffer
1958	(setq erc-server-users nil)
1959	(setq erc-channel-users
1960	      (make-hash-table :test 'equal))))
1961    ;; clear last incomplete line read
1962    (setq erc-server-filter-data nil)
1963    (setq erc-channel-topic "")
1964    ;; limit on the number of users on the channel (mode +l)
1965    (setq erc-channel-user-limit nil)
1966    (setq erc-channel-key nil)
1967    ;; last active buffer, defaults to this one
1968    (erc-set-active-buffer buffer)
1969    ;; last invitation channel
1970    (setq erc-invitation nil)
1971    ;; Server channel list
1972    (setq erc-channel-list ())
1973    ;; login-time 'nick in use' error
1974    (setq erc-bad-nick nil)
1975    ;; whether we have logged in
1976    (setq erc-logged-in nil)
1977    ;; The local copy of `erc-nick' - the list of nicks to choose
1978    (setq erc-default-nicks (if (consp erc-nick) erc-nick (list erc-nick)))
1979    ;; password stuff
1980    (setq erc-session-password passwd)
1981    ;; debug output buffer
1982    (setq erc-dbuf
1983	  (when erc-log-p
1984	    (get-buffer-create (concat "*ERC-DEBUG: " server "*"))))
1985    ;; set up prompt
1986    (unless continued-session
1987      (goto-char (point-max))
1988      (insert "\n"))
1989    (if continued-session
1990	(goto-char old-point)
1991      (set-marker erc-insert-marker (point))
1992      (erc-display-prompt)
1993      (goto-char (point-max)))
1994
1995    (erc-determine-parameters server port nick full-name)
1996
1997    ;; Saving log file on exit
1998    (run-hook-with-args 'erc-connect-pre-hook buffer)
1999
2000    (when connect
2001      (erc-server-connect erc-session-server erc-session-port buffer))
2002    (erc-update-mode-line)
2003
2004    ;; Now display the buffer in a window as per user wishes.
2005    (unless (eq buffer old-buffer)
2006      (when erc-log-p
2007	;; we can't log to debug buffer, it may not exist yet
2008	(message "erc: old buffer %s, switching to %s"
2009		 old-buffer buffer))
2010      (erc-setup-buffer buffer))
2011
2012    buffer))
2013
2014(defun erc-initialize-log-marker (buffer)
2015  "Initialize the `erc-last-saved-position' marker to a sensible position.
2016BUFFER is the current buffer."
2017  (with-current-buffer buffer
2018    (setq erc-last-saved-position (make-marker))
2019    (move-marker erc-last-saved-position
2020		 (1- (marker-position erc-insert-marker)))))
2021
2022;; interactive startup
2023
2024(defvar erc-server-history-list nil
2025  "IRC server interactive selection history list.")
2026
2027(defvar erc-nick-history-list nil
2028  "Nickname interactive selection history list.")
2029
2030(defun erc-already-logged-in (server port nick)
2031  "Return the buffers corresponding to a NICK on PORT of a session SERVER.
2032This is determined by looking for the appropriate buffer and checking
2033whether the connection is still alive.
2034If no buffer matches, return nil."
2035  (erc-buffer-list
2036   (lambda ()
2037     (and (erc-server-process-alive)
2038	  (string= erc-session-server server)
2039	  (erc-port-equal erc-session-port port)
2040	  (erc-current-nick-p nick)))))
2041
2042(if (not (fboundp 'read-passwd))
2043    (defun read-passwd (prompt)
2044      "Substitute for `read-passwd' in early emacsen."
2045      (read-from-minibuffer prompt)))
2046
2047(defcustom erc-before-connect nil
2048  "Hook called before connecting to a server.
2049This hook gets executed before `erc' actually invokes `erc-mode'
2050with your input data.  The functions in here get called with three
2051parameters, SERVER, PORT and NICK."
2052  :group 'erc-hooks
2053  :type 'hook)
2054
2055(defcustom erc-after-connect nil
2056  "Hook called after connecting to a server.
2057This hook gets executed when an end of MOTD has been received.  All
2058functions in here get called with the parameters SERVER and NICK."
2059  :group 'erc-hooks
2060  :type 'hook)
2061
2062;;;###autoload
2063(defun erc-select-read-args ()
2064  "Prompt the user for values of nick, server, port, and password."
2065  (let (user-input server port nick passwd)
2066    (setq user-input (read-from-minibuffer
2067		      "IRC server: "
2068		      (erc-compute-server) nil nil 'erc-server-history-list))
2069
2070    (if (string-match "\\(.*\\):\\(.*\\)\\'" user-input)
2071	(setq port (erc-string-to-port (match-string 2 user-input))
2072	      user-input (match-string 1 user-input))
2073      (setq port
2074	    (erc-string-to-port (read-from-minibuffer
2075				 "IRC port: " (erc-port-to-string
2076					       (erc-compute-port))))))
2077
2078    (if (string-match "\\`\\(.*\\)@\\(.*\\)" user-input)
2079	(setq nick (match-string 1 user-input)
2080	      user-input (match-string 2 user-input))
2081      (setq nick
2082	    (if (erc-already-logged-in server port nick)
2083		(read-from-minibuffer
2084		 (erc-format-message 'nick-in-use ?n nick)
2085		 nick
2086		 nil nil 'erc-nick-history-list)
2087	      (read-from-minibuffer
2088	       "Nickname: " (erc-compute-nick nick)
2089	       nil nil 'erc-nick-history-list))))
2090
2091    (setq server user-input)
2092
2093    (setq passwd (if erc-prompt-for-password
2094		     (if (and erc-password
2095			      (y-or-n-p "Use the default password? "))
2096			 erc-password
2097		       (read-passwd "Password: "))
2098		   erc-password))
2099    (when (and passwd (string= "" passwd))
2100      (setq passwd nil))
2101
2102    (while (erc-already-logged-in server port nick)
2103      ;; hmm, this is a problem when using multiple connections to a bnc
2104      ;; with the same nick. Currently this code prevents using more than one
2105      ;; bnc with the same nick. actually it would be nice to have
2106      ;; bncs transparent, so that erc-compute-buffer-name displays
2107      ;; the server one is connected to.
2108      (setq nick (read-from-minibuffer
2109		  (erc-format-message 'nick-in-use ?n nick)
2110		  nick
2111		  nil nil 'erc-nick-history-list)))
2112    (list :server server :port port :nick nick :password passwd)))
2113
2114;;;###autoload
2115(defun* erc (&key (server (erc-compute-server))
2116		  (port   (erc-compute-port))
2117		  (nick   (erc-compute-nick))
2118		  password
2119		  (full-name (erc-compute-full-name)))
2120  "ERC is a powerful, modular, and extensible IRC client.
2121This function is the main entry point for ERC.
2122
2123It permits you to select connection parameters, and then starts ERC.
2124
2125Non-interactively, it takes the keyword arguments
2126   (server (erc-compute-server))
2127   (port   (erc-compute-port))
2128   (nick   (erc-compute-nick))
2129   password
2130   (full-name (erc-compute-full-name)))
2131
2132That is, if called with
2133
2134   (erc :server \"irc.freenode.net\" :full-name \"Harry S Truman\")
2135
2136then the server and full-name will be set to those values, whereas
2137`erc-compute-port', `erc-compute-nick' and `erc-compute-full-name' will
2138be invoked for the values of the other parameters."
2139  (interactive (erc-select-read-args))
2140  (erc-open server port nick full-name t password))
2141
2142;;;###autoload
2143(defalias 'erc-select 'erc)
2144
2145(defun erc-ssl (&rest r)
2146  "Interactively select SSL connection parameters and run ERC.
2147Arguments are the same as for `erc'."
2148  (interactive (erc-select-read-args))
2149  (let ((erc-server-connect-function 'erc-open-ssl-stream))
2150    (apply 'erc r)))
2151
2152(defalias 'erc-select-ssl 'erc-ssl)
2153
2154(defun erc-open-ssl-stream (name buffer host port)
2155  "Open an SSL stream to an IRC server.
2156The process will be given the name NAME, its target buffer will be
2157BUFFER.  HOST and PORT specify the connection target."
2158  (when (require 'tls)
2159    (let ((proc (open-tls-stream name buffer host port)))
2160      ;; Ugly hack, but it works for now. Problem is it is
2161      ;; very hard to detect when ssl is established, because s_client
2162      ;; doesn't give any CONNECTIONESTABLISHED kind of message, and
2163      ;; most IRC servers send nothing and wait for you to identify.
2164      ;; Disabled when switching to tls.el -- jas
2165      ;(sit-for 5)
2166      proc)))
2167
2168;;; Debugging the protocol
2169
2170(defvar erc-debug-irc-protocol nil
2171  "If non-nil, log all IRC protocol traffic to the buffer \"*erc-protocol*\".
2172
2173The buffer is created if it doesn't exist.
2174
2175NOTE: If this variable is non-nil, and you kill the only
2176visible \"*erc-protocol*\" buffer, it will be recreated shortly,
2177but you won't see it.
2178
2179WARNING: Do not set this variable directly!  Instead, use the
2180function `erc-toggle-debug-irc-protocol' to toggle its value.")
2181
2182(defun erc-log-irc-protocol (string &optional outbound)
2183  "Append STRING to the buffer *erc-protocol*.
2184
2185This only has any effect if `erc-debug-irc-protocol' is non-nil.
2186
2187The buffer is created if it doesn't exist.
2188
2189If OUTBOUND is non-nil, STRING is being sent to the IRC server
2190and appears in face `erc-input-face' in the buffer."
2191  (when erc-debug-irc-protocol
2192    (let ((network-name (or (ignore-errors (erc-network-name))
2193			    "???")))
2194      (with-current-buffer (get-buffer-create "*erc-protocol*")
2195	(save-excursion
2196	  (goto-char (point-max))
2197	  (let ((inhibit-read-only t))
2198	    (insert (if (not outbound)
2199			;; Cope with the fact that string might
2200			;; contain multiple lines of text.
2201			(let ((lines (delete "" (split-string string
2202							      "\n\\|\r\n")))
2203			      (result ""))
2204			  (dolist (line lines)
2205			    (setq result (concat result network-name
2206						 " << " line "\n")))
2207			  result)
2208		      (erc-propertize
2209			(concat network-name " >> " string
2210				(if (/= ?\n
2211					(aref string
2212					      (1- (length string))))
2213				    "\n"))
2214			'face 'erc-input-face)))))
2215	(let ((orig-win (selected-window))
2216	      (debug-buffer-window (get-buffer-window (current-buffer) t)))
2217	  (when debug-buffer-window
2218	     (select-window debug-buffer-window)
2219	     (when (= 1 (count-lines (point) (point-max)))
2220	       (goto-char (point-max))
2221	       (recenter -1))
2222	     (select-window orig-win)))))))
2223
2224(defun erc-toggle-debug-irc-protocol (&optional arg)
2225  "Toggle the value of `erc-debug-irc-protocol'.
2226
2227If ARG is non-nil, show the *erc-protocol* buffer."
2228  (interactive "P")
2229  (let* ((buf (get-buffer-create "*erc-protocol*")))
2230    (with-current-buffer buf
2231      (erc-view-mode-enter 1)
2232      (when (null (current-local-map))
2233	(let ((inhibit-read-only t))
2234	  (insert (erc-make-notice "This buffer displays all IRC protocol traffic exchanged with each server.\n"))
2235	  (insert (erc-make-notice "Kill this buffer to terminate protocol logging.\n\n")))
2236	(use-local-map (make-sparse-keymap))
2237	(local-set-key (kbd "RET") 'erc-toggle-debug-irc-protocol))
2238      (add-hook 'kill-buffer-hook
2239		#'(lambda () (setq erc-debug-irc-protocol nil))
2240		nil 'local)
2241      (goto-char (point-max))
2242      (let ((inhibit-read-only t))
2243	(insert (erc-make-notice
2244		 (format "IRC protocol logging %s at %s -- Press ENTER to toggle logging.\n"
2245			 (if erc-debug-irc-protocol "disabled" "enabled")
2246			 (current-time-string))))))
2247    (setq erc-debug-irc-protocol (not erc-debug-irc-protocol))
2248    (if (and arg
2249	     (not (get-buffer-window "*erc-protocol*" t)))
2250	(display-buffer buf t))
2251    (message "IRC protocol traffic logging %s (see buffer *erc-protocol*)."
2252	     (if erc-debug-irc-protocol "enabled" "disabled"))))
2253
2254;;; I/O interface
2255
2256;; send interface
2257
2258(defun erc-send-action (tgt str &optional force)
2259  "Send CTCP ACTION information described by STR to TGT."
2260  (erc-send-ctcp-message tgt (format "ACTION %s" str) force)
2261  (erc-display-message
2262   nil 'input (current-buffer)
2263   'ACTION ?n (erc-current-nick) ?a str ?u "" ?h ""))
2264
2265;; Display interface
2266
2267(defun erc-string-invisible-p (string)
2268  "Check whether STRING is invisible or not.
2269I.e. any char in it has the `invisible' property set."
2270  (text-property-any 0 (length string) 'invisible t string))
2271
2272(defun erc-display-line-1 (string buffer)
2273  "Display STRING in `erc-mode' BUFFER.
2274Auxiliary function used in `erc-display-line'.  The line gets filtered to
2275interpret the control characters.  Then, `erc-insert-pre-hook' gets called.
2276If `erc-insert-this' is still t, STRING gets inserted into the buffer.
2277Afterwards, `erc-insert-modify' and `erc-insert-post-hook' get called.
2278If STRING is nil, the function does nothing."
2279  (when string
2280    (save-excursion
2281      (set-buffer (or buffer (process-buffer erc-server-process)))
2282      (let ((insert-position (or (marker-position erc-insert-marker)
2283				 (point-max))))
2284	(let ((string string) ;; FIXME! Can this be removed?
2285	      (buffer-undo-list t)
2286	      (inhibit-read-only t))
2287	  (unless (string-match "\n$" string)
2288	    (setq string (concat string "\n"))
2289	    (when (erc-string-invisible-p string)
2290	      (erc-put-text-properties 0 (length string) string
2291				       '(invisible intangible))))
2292	  (erc-log (concat "erc-display-line: " string
2293			   (format "(%S)" string) " in buffer "
2294			   (format "%s" buffer)))
2295	  (setq erc-insert-this t)
2296	  (run-hook-with-args 'erc-insert-pre-hook string)
2297	  (if (null erc-insert-this)
2298	      ;; Leave erc-insert-this set to t as much as possible.  Fran
2299	      ;; Litterio <franl> has seen erc-insert-this set to nil while
2300	      ;; erc-send-pre-hook is running, which should never happen.  This
2301	      ;; may cure it.
2302	      (setq erc-insert-this t)
2303	    (save-excursion ;; to restore point in the new buffer
2304	      (save-restriction
2305		(widen)
2306		(goto-char insert-position)
2307		(insert-before-markers string)
2308		;; run insertion hook, with point at restored location
2309		(save-restriction
2310		  (narrow-to-region insert-position (point))
2311		  (run-hooks 'erc-insert-modify-hook)
2312		  (run-hooks 'erc-insert-post-hook))))))
2313	(erc-update-undo-list (- (or (marker-position erc-insert-marker)
2314				     (point-max))
2315				 insert-position))))))
2316
2317(defun erc-update-undo-list (shift)
2318  ;; Translate buffer positions in buffer-undo-list by SHIFT.
2319  (unless (or (zerop shift) (atom buffer-undo-list))
2320    (let ((list buffer-undo-list) elt)
2321      (while list
2322	(setq elt (car list))
2323	(cond ((integerp elt)		; POSITION
2324	       (incf (car list) shift))
2325	      ((or (atom elt)		; nil, EXTENT
2326		   ;; (eq t (car elt))	; (t HIGH . LOW)
2327		   (markerp (car elt)))	; (MARKER . DISTANCE)
2328	       nil)
2329	      ((integerp (car elt))	; (BEGIN . END)
2330	       (incf (car elt) shift)
2331	       (incf (cdr elt) shift))
2332	      ((stringp (car elt))	; (TEXT . POSITION)
2333	       (incf (cdr elt) (* (if (natnump (cdr elt)) 1 -1) shift)))
2334	      ((null (car elt))		; (nil PROPERTY VALUE BEG . END)
2335	       (let ((cons (nthcdr 3 elt)))
2336		 (incf (car cons) shift)
2337		 (incf (cdr cons) shift)))
2338	      ((and (featurep 'xemacs)
2339		    (extentp (car elt))) ; (EXTENT START END)
2340	       (incf (nth 1 elt) shift)
2341	       (incf (nth 2 elt) shift)))
2342	(setq list (cdr list))))))
2343
2344(defvar erc-valid-nick-regexp "[]a-zA-Z^[;\\`_{}|][]^[;\\`_{}|a-zA-Z0-9-]*"
2345  "Regexp which matches all legal characters in a IRC nickname.")
2346
2347(defun erc-is-valid-nick-p (nick)
2348  "Check if NICK is a valid IRC nickname."
2349  (string-match (concat "^" erc-valid-nick-regexp "$") nick))
2350
2351(defun erc-display-line (string &optional buffer)
2352  "Display STRING in the ERC BUFFER.
2353All screen output must be done through this function.  If BUFFER is nil
2354or omitted, the default ERC buffer for the `erc-session-server' is used.
2355The BUFFER can be an actual buffer, a list of buffers, 'all or 'active.
2356If BUFFER = 'all, the string is displayed in all the ERC buffers for the
2357current session.  'active means the current active buffer
2358\(`erc-active-buffer').  If the buffer can't be resolved, the current
2359buffer is used.  `erc-display-line-1' is used to display STRING.
2360
2361If STRING is nil, the function does nothing."
2362  (let ((inhibit-point-motion-hooks t)
2363	new-bufs)
2364    (dolist (buf (cond
2365		  ((bufferp buffer) (list buffer))
2366		  ((listp buffer) buffer)
2367		  ((processp buffer) (list (process-buffer buffer)))
2368		  ((eq 'all buffer)
2369		   ;; Hmm, or all of the same session server?
2370		   (erc-buffer-list nil erc-server-process))
2371		  ((and (eq 'active buffer) (erc-active-buffer))
2372		   (list (erc-active-buffer)))
2373		  ((erc-server-buffer-live-p)
2374		   (list (process-buffer erc-server-process)))
2375		  (t (list (current-buffer)))))
2376      (when (buffer-live-p buf)
2377	(erc-display-line-1 string buf)
2378	(add-to-list 'new-bufs buf)))
2379    (when (null new-bufs)
2380      (if (erc-server-buffer-live-p)
2381	  (erc-display-line-1 string (process-buffer erc-server-process))
2382	(erc-display-line-1 string (current-buffer))))))
2383
2384(defun erc-display-message-highlight (type string)
2385  "Highlight STRING according to TYPE, where erc-TYPE-face is an ERC face.
2386
2387See also `erc-make-notice'."
2388  (cond ((eq type 'notice)
2389	 (erc-make-notice string))
2390	(t
2391	 (erc-put-text-property
2392	  0 (length string)
2393	  'face (or (intern-soft
2394		     (concat "erc-" (symbol-name type) "-face"))
2395		    "erc-default-face")
2396	  string)
2397	 string)))
2398
2399(defun erc-display-message (parsed type buffer msg &rest args)
2400  "Display MSG in BUFFER.
2401
2402ARGS, PARSED, and TYPE are used to format MSG sensibly.
2403
2404See also `erc-format-message' and `erc-display-line'."
2405  (let ((string (if (symbolp msg)
2406		    (apply 'erc-format-message msg args)
2407		  msg)))
2408    (setq string
2409	  (cond
2410	   ((null type)
2411	    string)
2412	   ((listp type)
2413	    (mapc (lambda (type)
2414		    (setq string
2415			  (erc-display-message-highlight type string)))
2416		  type)
2417	    string)
2418	   ((symbolp type)
2419	    (erc-display-message-highlight type string))))
2420
2421    (if (not (erc-response-p parsed))
2422	(erc-display-line string buffer)
2423      (unless (member (erc-response.command parsed) erc-hide-list)
2424	(erc-put-text-property 0 (length string) 'erc-parsed parsed string)
2425	(erc-put-text-property 0 (length string) 'rear-sticky t string)
2426	(erc-display-line string buffer)))))
2427
2428(defun erc-message-type-member (position list)
2429  "Return non-nil if the erc-parsed text-property at POSITION is in LIST.
2430
2431This function relies on the erc-parsed text-property being
2432present."
2433  (let ((prop-val (erc-get-parsed-vector position)))
2434    (and prop-val (member (erc-response.command prop-val) list))))
2435
2436(defvar erc-send-input-line-function 'erc-send-input-line)
2437(make-variable-buffer-local 'erc-send-input-line-function)
2438
2439(defun erc-send-input-line (target line &optional force)
2440  "Send LINE to TARGET.
2441
2442See also `erc-server-send'."
2443  (setq line (format "PRIVMSG %s :%s"
2444		     target
2445		     ;; If the line is empty, we still want to
2446		     ;; send it - i.e. an empty pasted line.
2447		     (if (string= line "\n")
2448			 " \n"
2449		       line)))
2450  (erc-server-send line force target))
2451
2452(defun erc-get-arglist (fun)
2453  "Return the argument list of a function without the parens."
2454  (let ((arglist (format "%S" (erc-function-arglist fun))))
2455    (if (string-match "^(\\(.*\\))$" arglist)
2456	(match-string 1 arglist)
2457      arglist)))
2458
2459(defun erc-command-name (cmd)
2460  "For CMD being the function name of a ERC command, something like
2461erc-cmd-FOO, this returns a string /FOO."
2462  (let ((command-name (symbol-name cmd)))
2463    (if (string-match "^erc-cmd-\\(.*\\)$" command-name)
2464	(concat "/" (match-string 1 command-name))
2465      command-name)))
2466
2467(defun erc-process-input-line (line &optional force no-command)
2468  "Translate LINE to an RFC1459 command and send it based.
2469Returns non-nil if the command is actually sent to the server, and nil
2470otherwise.
2471
2472If the command in the LINE is not bound as a function `erc-cmd-<COMMAND>',
2473it is passed to `erc-cmd-default'.  If LINE is not a command (i.e. doesn't
2474start with /<COMMAND>) then it is sent as a message.
2475
2476An optional FORCE argument forces sending the line when flood
2477protection is in effect.  The optional NO-COMMAND argument prohibits
2478this function from interpreting the line as a command."
2479  (let ((command-list (erc-extract-command-from-line line)))
2480    (if	(and command-list
2481	     (not no-command))
2482	(let* ((cmd  (nth 0 command-list))
2483	       (args (nth 1 command-list)))
2484	  (condition-case nil
2485	      (if (listp args)
2486		  (apply cmd args)
2487		(funcall cmd args))
2488	    (wrong-number-of-arguments
2489	     (erc-display-message nil 'error (current-buffer) 'incorrect-args
2490				  ?c (erc-command-name cmd)
2491				  ?u (or (erc-get-arglist cmd)
2492					 "")
2493				  ?d (format "%s\n"
2494					     (or (documentation cmd) "")))
2495	     nil)))
2496      (let ((r (erc-default-target)))
2497	(if r
2498	    (funcall erc-send-input-line-function r line force)
2499	  (erc-display-message nil 'error (current-buffer) 'no-target)
2500	  nil)))))
2501
2502;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2503;;		      Input commands handlers
2504;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2505
2506(defun erc-cmd-AMSG (line)
2507  "Send LINE to all channels of the current server that you are on."
2508  (interactive "sSend to all channels you're on: ")
2509  (setq line (erc-trim-string line))
2510  (erc-with-all-buffers-of-server nil
2511   (lambda ()
2512     (erc-channel-p (erc-default-target)))
2513   (erc-send-message line)))
2514(put 'erc-cmd-AMSG 'do-not-parse-args t)
2515
2516(defun erc-cmd-SAY (line)
2517  "Send LINE to the current query or channel as a message, not a command.
2518
2519Use this when you want to send a message with a leading '/'.  Note
2520that since multi-line messages are never a command, you don't
2521need this when pasting multiple lines of text."
2522  (if (string-match "^\\s-*$" line)
2523      nil
2524    (string-match "^ ?\\(.*\\)" line)
2525    (erc-process-input-line (match-string 1 line) nil t)))
2526(put 'erc-cmd-SAY 'do-not-parse-args t)
2527
2528(defun erc-cmd-SET (line)
2529  "Set the variable named by the first word in LINE to some VALUE.
2530VALUE is computed by evaluating the rest of LINE in Lisp."
2531  (cond
2532   ((string-match "^\\s-*\\(\\S-+\\)\\s-+\\(.*\\)$" line)
2533    (let ((var (read (concat "erc-" (match-string 1 line))))
2534	  (val (read (match-string 2 line))))
2535      (if (boundp var)
2536	  (progn
2537	    (set var (eval val))
2538	    (erc-display-message
2539	     nil nil 'active (format "Set %S to %S" var val))
2540	    t)
2541	(setq var (read (match-string 1 line)))
2542	(if (boundp var)
2543	    (progn
2544	      (set var (eval val))
2545	      (erc-display-message
2546	       nil nil 'active (format "Set %S to %S" var val))
2547	      t)
2548	  (erc-display-message nil 'error 'active 'variable-not-bound)
2549	  nil))))
2550   ((string-match "^\\s-*$" line)
2551    (erc-display-line
2552     (concat "Available user variables:\n"
2553	     (apply
2554	      'concat
2555	      (mapcar
2556	       (lambda (var)
2557		 (let ((val (symbol-value var)))
2558		   (concat (format "%S:" var)
2559			   (if (consp val)
2560			       (concat "\n" (pp-to-string val))
2561			     (format " %S\n" val)))))
2562	       (apropos-internal "^erc-" 'user-variable-p))))
2563     (current-buffer)) t)
2564   (t nil)))
2565(defalias 'erc-cmd-VAR 'erc-cmd-SET)
2566(defalias 'erc-cmd-VARIABLE 'erc-cmd-SET)
2567(put 'erc-cmd-SET 'do-not-parse-args t)
2568
2569(defun erc-cmd-default (line)
2570  "Fallback command.
2571
2572Commands for which no erc-cmd-xxx exists, are tunnelled through
2573this function.  LINE is sent to the server verbatim, and
2574therefore has to contain the command itself as well."
2575  (erc-log (format "cmd: DEFAULT: %s" line))
2576  (erc-server-send (substring line 1))
2577  t)
2578
2579(defun erc-cmd-IGNORE (&optional user)
2580  "Ignore USER.  This should be a regexp matching nick!user@host.
2581If no USER argument is specified, list the contents of `erc-ignore-list'."
2582  (if user
2583      (let ((quoted (regexp-quote user)))
2584	(when (and (not (string= user quoted))
2585		   (y-or-n-p (format "Use regexp-quoted form (%s) instead? "
2586				     quoted)))
2587	  (setq user quoted))
2588	(erc-display-line
2589	 (erc-make-notice (format "Now ignoring %s" user))
2590	 'active)
2591	(erc-with-server-buffer (add-to-list 'erc-ignore-list user)))
2592    (if (null (erc-with-server-buffer erc-ignore-list))
2593	(erc-display-line (erc-make-notice "Ignore list is empty") 'active)
2594      (erc-display-line (erc-make-notice "Ignore list:") 'active)
2595      (mapc #'(lambda (item)
2596		(erc-display-line (erc-make-notice item)
2597				  'active))
2598	    (erc-with-server-buffer erc-ignore-list))))
2599  t)
2600
2601(defun erc-cmd-UNIGNORE (user)
2602  "Remove the user specified in USER from the ignore list."
2603  (let ((ignored-nick (car (erc-with-server-buffer
2604			     (erc-member-ignore-case (regexp-quote user)
2605						     erc-ignore-list)))))
2606    (unless ignored-nick
2607      (if (setq ignored-nick (erc-ignored-user-p user))
2608	  (unless (y-or-n-p (format "Remove this regexp (%s)? "
2609				    ignored-nick))
2610	    (setq ignored-nick nil))
2611	(erc-display-line
2612	 (erc-make-notice (format "%s is not currently ignored!" user))
2613	 'active)))
2614    (when ignored-nick
2615      (erc-display-line
2616       (erc-make-notice (format "No longer ignoring %s" user))
2617       'active)
2618      (erc-with-server-buffer
2619	(setq erc-ignore-list (delete ignored-nick erc-ignore-list)))))
2620  t)
2621
2622(defun erc-cmd-CLEAR ()
2623  "Clear the window content."
2624  (recenter 0)
2625  t)
2626
2627(defun erc-cmd-OPS ()
2628  "Show the ops in the current channel."
2629  (interactive)
2630  (let ((ops nil))
2631    (if erc-channel-users
2632	(maphash (lambda (nick user-data)
2633		   (let ((cuser (cdr user-data)))
2634		     (if (and cuser
2635			      (erc-channel-user-op cuser))
2636			 (setq ops (cons (erc-server-user-nickname
2637					  (car user-data))
2638					 ops)))))
2639		 erc-channel-users))
2640    (setq ops (sort ops 'string-lessp))
2641    (if ops
2642	(erc-display-message
2643	 nil 'notice (current-buffer) 'ops
2644	 ?i (length ops) ?s (if (> (length ops) 1) "s" "")
2645	 ?o (mapconcat 'identity ops " "))
2646      (erc-display-message nil 'notice (current-buffer) 'ops-none)))
2647  t)
2648
2649(defun erc-cmd-COUNTRY (tld)
2650  "Display the country associated with the top level domain TLD."
2651  (require 'mail-extr)
2652  (let ((co (ignore-errors (what-domain tld))))
2653    (if co
2654	(erc-display-message
2655	 nil 'notice 'active 'country ?c co ?d tld)
2656      (erc-display-message
2657       nil 'notice 'active 'country-unknown ?d tld))
2658  t))
2659
2660(defun erc-cmd-AWAY (line)
2661  "Mark the user as being away, the reason being indicated by LINE.
2662If no reason is given, unset away status."
2663  (when (string-match "^\\s-*\\(.*\\)$" line)
2664    (let ((reason (match-string 1 line)))
2665      (erc-log (format "cmd: AWAY: %s" reason))
2666      (erc-server-send
2667       (if (string= reason "")
2668	   "AWAY"
2669	 (concat "AWAY :" reason))))
2670    t))
2671(put 'erc-cmd-AWAY 'do-not-parse-args t)
2672
2673(defun erc-cmd-GAWAY (line)
2674  "Mark the user as being away everywhere, the reason being indicated by LINE."
2675  ;; on all server buffers.
2676  (erc-with-all-buffers-of-server nil
2677    #'erc-open-server-buffer-p
2678    (erc-cmd-AWAY line)))
2679(put 'erc-cmd-GAWAY 'do-not-parse-args t)
2680
2681(defun erc-cmd-CTCP (nick cmd &rest args)
2682  "Send a Client To Client Protocol message to NICK.
2683
2684CMD is the CTCP command, possible values being ECHO, FINGER, CLIENTINFO, TIME,
2685VERSION and so on.  It is called with ARGS."
2686  (let ((str (concat cmd
2687		     (when args
2688		       (concat " " (mapconcat #'identity args " "))))))
2689    (erc-log (format "cmd: CTCP [%s]: [%s]" nick str))
2690    (erc-send-ctcp-message nick str)
2691    t))
2692
2693(defun erc-cmd-HELP (&optional func)
2694  "Popup help information.
2695
2696If FUNC contains a valid function or variable, help about that
2697will be displayed.  If FUNC is empty, display an apropos about
2698ERC commands.  Otherwise, do `apropos' in the ERC namespace
2699\(\"erc-.*LINE\"\).
2700
2701Examples:
2702To find out about erc and bbdb, do
2703  /help bbdb.*
2704
2705For help about the WHOIS command, do:
2706  /help whois
2707
2708For a list of user commands (/join /part, ...):
2709  /help."
2710  (if func
2711    (let* ((sym (or (let ((sym (intern-soft
2712				(concat "erc-cmd-" (upcase func)))))
2713		      (if (and sym (or (boundp sym) (fboundp sym)))
2714			  sym
2715			nil))
2716		    (let ((sym (intern-soft func)))
2717		      (if (and sym (or (boundp sym) (fboundp sym)))
2718			  sym
2719			nil))
2720		    (let ((sym (intern-soft (concat "erc-" func))))
2721		      (if (and sym (or (boundp sym) (fboundp sym)))
2722			  sym
2723			nil)))))
2724      (if sym
2725	  (cond
2726	   ((boundp sym) (describe-variable sym))
2727	   ((fboundp sym) (describe-function sym))
2728	   (t nil))
2729	(apropos-command (concat "erc-.*" func) nil
2730			 (lambda (x)
2731			   (or (commandp x)
2732			       (get x 'custom-type))))
2733	t))
2734    (apropos "erc-cmd-")
2735    (message "Type C-h m to get additional information about keybindings.")
2736    t))
2737
2738(defalias 'erc-cmd-H 'erc-cmd-HELP)
2739
2740(defun erc-cmd-JOIN (channel &optional key)
2741  "Join the channel given in CHANNEL, optionally with KEY.
2742If CHANNEL is specified as \"-invite\", join the channel to which you
2743were most recently invited.  See also `invitation'."
2744  (let (chnl)
2745    (if (string= (upcase channel) "-INVITE")
2746	(if erc-invitation
2747	    (setq chnl erc-invitation)
2748	  (erc-display-message nil 'error (current-buffer) 'no-invitation))
2749      (setq chnl (erc-ensure-channel-name channel)))
2750    (when chnl
2751      ;; Prevent double joining of same channel on same server.
2752      (let ((joined-channels
2753	     (mapcar #'(lambda (chanbuf)
2754			 (with-current-buffer chanbuf (erc-default-target)))
2755		     (erc-channel-list erc-server-process))))
2756	(if (erc-member-ignore-case chnl joined-channels)
2757	    (switch-to-buffer (car (erc-member-ignore-case chnl
2758							   joined-channels)))
2759	  (erc-log (format "cmd: JOIN: %s" chnl))
2760	  (if (and chnl key)
2761	      (erc-server-send (format "JOIN %s %s" chnl key))
2762	    (erc-server-send (format "JOIN %s" chnl)))))))
2763  t)
2764
2765(defalias 'erc-cmd-CHANNEL 'erc-cmd-JOIN)
2766(defalias 'erc-cmd-J 'erc-cmd-JOIN)
2767
2768(defvar erc-channel-new-member-names nil
2769  "If non-nil, a names list is currently being received.
2770
2771If non-nil, this variable is a hash-table that associates
2772received nicks with t.")
2773(make-variable-buffer-local 'erc-channel-new-member-names)
2774
2775(defun erc-cmd-NAMES (&optional channel)
2776  "Display the users in CHANNEL.
2777If CHANNEL is not specified, display the users in the current channel.
2778This function clears the channel name list first, then sends the
2779command."
2780  (let ((tgt (or (and (erc-channel-p channel) channel)
2781		 (erc-default-target))))
2782    (if (and tgt (erc-channel-p tgt))
2783	(progn
2784	  (erc-log (format "cmd: DEFAULT: NAMES %s" tgt))
2785	  (erc-with-buffer
2786	   (tgt)
2787	   (erc-channel-begin-receiving-names))
2788	  (erc-server-send (concat "NAMES " tgt)))
2789      (erc-display-message nil 'error (current-buffer) 'no-default-channel)))
2790  t)
2791(defalias 'erc-cmd-N 'erc-cmd-NAMES)
2792
2793(defun erc-cmd-KICK (target &optional reason-or-nick &rest reasonwords)
2794  "Kick the user indicated in LINE from the current channel.
2795LINE has the format: \"#CHANNEL NICK REASON\" or \"NICK REASON\"."
2796  (let ((reasonstring (mapconcat 'identity reasonwords " ")))
2797    (if (string= "" reasonstring)
2798	(setq reasonstring (format "Kicked by %s" (erc-current-nick))))
2799    (if (erc-channel-p target)
2800	(let ((nick reason-or-nick))
2801	  (erc-log (format "cmd: KICK: %s/%s: %s" nick target reasonstring))
2802	  (erc-server-send (format "KICK %s %s :%s" target nick reasonstring)
2803			   nil target)
2804	  t)
2805      (when target
2806	(let ((ch (erc-default-target)))
2807	  (setq reasonstring (concat
2808			      (if reason-or-nick (concat reason-or-nick " "))
2809			      reasonstring))
2810	  (if ch
2811	      (progn
2812		(erc-log
2813		 (format "cmd: KICK: %s/%s: %s" target ch reasonstring))
2814		(erc-server-send
2815		 (format "KICK %s %s :%s" ch target reasonstring) nil ch))
2816	    (erc-display-message nil 'error (current-buffer)
2817				 'no-default-channel))
2818	  t)))))
2819
2820(defvar erc-script-args nil)
2821
2822(defun erc-cmd-LOAD (line)
2823  "Load the script provided in the LINE.
2824If LINE continues beyond the file name, the rest of
2825it is put in a (local) variable `erc-script-args',
2826which can be used in Emacs Lisp scripts.
2827
2828The optional FORCE argument is ignored here - you can't force loading
2829a script after exceeding the flood threshold."
2830  (cond
2831   ((string-match "^\\s-*\\(\\S-+\\)\\(.*\\)$" line)
2832    (let* ((file-to-find (match-string 1 line))
2833	   (erc-script-args (match-string 2 line))
2834	   (file (erc-find-file file-to-find erc-script-path)))
2835      (erc-log (format "cmd: LOAD: %s" file-to-find))
2836      (cond
2837       ((not file)
2838	(erc-display-message nil 'error (current-buffer)
2839			     'cannot-find-file ?f file-to-find))
2840       ((not (file-readable-p file))
2841	(erc-display-message nil 'error (current-buffer)
2842			     'cannot-read-file ?f file))
2843       (t
2844	(message "Loading \'%s\'..." file)
2845	(erc-load-script file)
2846	(message "Loading \'%s\'...done" file))))
2847    t)
2848   (t nil)))
2849
2850(defun erc-cmd-WHOIS (user &optional server)
2851  "Display whois information for USER.
2852
2853If SERVER is non-nil, use that, rather than the current server."
2854  ;; FIXME: is the above docstring correct?  -- Lawrence 2004-01-08
2855  (let ((send (if server
2856		  (format "WHOIS %s %s" user server)
2857		(format "WHOIS %s" user))))
2858    (erc-log (format "cmd: %s" send))
2859    (erc-server-send send)
2860  t))
2861(defalias 'erc-cmd-WI 'erc-cmd-WHOIS)
2862
2863(defun erc-cmd-WHOAMI ()
2864  "Display whois information about yourself."
2865  (erc-cmd-WHOIS (erc-current-nick))
2866  t)
2867
2868(defun erc-cmd-IDLE (nick)
2869  "Show the length of time NICK has been idle."
2870  (let ((origbuf (current-buffer))
2871	symlist)
2872    (erc-with-server-buffer
2873      (add-to-list 'symlist
2874		   (cons (erc-once-with-server-event
2875			  311 `(string= ,nick
2876					(second
2877					 (erc-response.command-args parsed))))
2878			 'erc-server-311-functions))
2879      (add-to-list 'symlist
2880		   (cons (erc-once-with-server-event
2881			  312 `(string= ,nick
2882					(second
2883					 (erc-response.command-args parsed))))
2884			 'erc-server-312-functions))
2885      (add-to-list 'symlist
2886		   (cons (erc-once-with-server-event
2887			  318 `(string= ,nick
2888					(second
2889					 (erc-response.command-args parsed))))
2890			 'erc-server-318-functions))
2891      (add-to-list 'symlist
2892		   (cons (erc-once-with-server-event
2893			  319 `(string= ,nick
2894					(second
2895					 (erc-response.command-args parsed))))
2896			 'erc-server-319-functions))
2897      (add-to-list 'symlist
2898		   (cons (erc-once-with-server-event
2899			  320 `(string= ,nick
2900					(second
2901					 (erc-response.command-args parsed))))
2902			 'erc-server-320-functions))
2903      (add-to-list 'symlist
2904		   (cons (erc-once-with-server-event
2905			  330 `(string= ,nick
2906					(second
2907					 (erc-response.command-args parsed))))
2908			 'erc-server-330-functions))
2909      (add-to-list 'symlist
2910		   (cons (erc-once-with-server-event
2911			  317
2912			  `(let ((idleseconds
2913				  (string-to-number
2914				   (third
2915				    (erc-response.command-args parsed)))))
2916			     (erc-display-line
2917			      (erc-make-notice
2918			       (format "%s has been idle for %s."
2919				       (erc-string-no-properties ,nick)
2920				       (erc-seconds-to-string idleseconds)))
2921			      ,origbuf))
2922			  t)
2923			 'erc-server-317-functions))
2924
2925      ;; Send the WHOIS command.
2926      (erc-cmd-WHOIS nick)
2927
2928      ;; Remove the uninterned symbols from the server hooks that did not run.
2929      (run-at-time 20 nil `(lambda ()
2930			     (with-current-buffer ,(current-buffer)
2931			       (dolist (sym ',symlist)
2932				 (let ((hooksym (cdr sym))
2933				       (funcsym (car sym)))
2934				   (remove-hook hooksym funcsym t))))))))
2935  t)
2936
2937(defun erc-cmd-DESCRIBE (line)
2938  "Pose some action to a certain user.
2939LINE has the format \"USER ACTION\"."
2940  (cond
2941   ((string-match
2942     "^\\s-*\\(\\S-+\\)\\s-\\(.*\\)$" line)
2943    (let ((dst (match-string 1 line))
2944	  (s (match-string 2 line)))
2945      (erc-log (format "cmd: DESCRIBE: [%s] %s" dst s))
2946      (erc-send-action dst s))
2947    t)
2948   (t nil)))
2949(put 'erc-cmd-DESCRIBE 'do-not-parse-args t)
2950
2951(defun erc-cmd-ME (line)
2952  "Send LINE as an action."
2953  (cond
2954   ((string-match "^\\s-\\(.*\\)$" line)
2955    (let ((s (match-string 1 line)))
2956      (erc-log (format "cmd: ME: %s" s))
2957      (erc-send-action (erc-default-target) s))
2958    t)
2959   (t nil)))
2960(put 'erc-cmd-ME 'do-not-parse-args t)
2961
2962(defun erc-cmd-LASTLOG (line)
2963  "Show all lines in the current buffer matching the regexp LINE.
2964
2965If a match spreads across multiple lines, all those lines are shown.
2966
2967The lines are shown in a buffer named `*Occur*'.
2968It serves as a menu to find any of the occurrences in this buffer.
2969\\[describe-mode] in that buffer will explain how.
2970
2971If LINE contains upper case characters (excluding those preceded by `\'),
2972the matching is case-sensitive."
2973  (occur line)
2974  t)
2975(put 'erc-cmd-LASTLOG 'do-not-parse-args t)
2976
2977(defun erc-send-message (line &optional force)
2978  "Send LINE to the current channel or user and display it.
2979
2980See also `erc-message' and `erc-display-line'."
2981  (erc-message "PRIVMSG" (concat (erc-default-target) " " line) force)
2982  (erc-display-line
2983   (concat (erc-format-my-nick) line)
2984     (current-buffer))
2985  ;; FIXME - treat multiline, run hooks, or remove me?
2986  t)
2987
2988(defun erc-cmd-MODE (line)
2989  "Change or display the mode value of a channel or user.
2990The first word specifies the target.  The rest is the mode string
2991to send.
2992
2993If only one word is given, display the mode of that target.
2994
2995A list of valid mode strings for Freenode may be found at
2996`http://freenode.net/using_the_network.shtml'."
2997  (cond
2998   ((string-match "^\\s-\\(.*\\)$" line)
2999    (let ((s (match-string 1 line)))
3000      (erc-log (format "cmd: MODE: %s" s))
3001      (erc-server-send (concat "MODE " line)))
3002    t)
3003   (t nil)))
3004(put 'erc-cmd-MODE 'do-not-parse-args t)
3005
3006(defun erc-cmd-NOTICE (channel-or-user &rest message)
3007  "Send a notice to the channel or user given as the first word.
3008The rest is the message to send."
3009  (erc-message "NOTICE" (concat channel-or-user " "
3010				(mapconcat #'identity message " "))))
3011
3012(defun erc-cmd-MSG (line)
3013  "Send a message to the channel or user given as the first word in LINE.
3014
3015The rest of LINE is the message to send."
3016  (erc-message "PRIVMSG" line))
3017
3018(defalias 'erc-cmd-M 'erc-cmd-MSG)
3019(put 'erc-cmd-MSG 'do-not-parse-args t)
3020
3021(defun erc-cmd-SQUERY (line)
3022  "Send a Service Query to the service given as the first word in LINE.
3023
3024The rest of LINE is the message to send."
3025  (erc-message "SQUERY" line))
3026
3027(defun erc-cmd-NICK (nick)
3028  "Change current nickname to NICK."
3029  (erc-log (format "cmd: NICK: %s (erc-bad-nick: %S)" nick erc-bad-nick))
3030  (let ((nicklen (cdr (assoc "NICKLEN" (erc-with-server-buffer
3031					 erc-server-parameters)))))
3032    (and nicklen (> (length nick) (string-to-number nicklen))
3033	 (erc-display-message
3034	  nil 'notice 'active 'nick-too-long
3035	  ?i (length nick) ?l nicklen)))
3036  (erc-server-send (format "NICK %s" nick))
3037  (cond (erc-bad-nick
3038	 (erc-set-current-nick nick)
3039	 (erc-update-mode-line)
3040	 (setq erc-bad-nick nil)))
3041  t)
3042
3043(defun erc-cmd-PART (line)
3044  "When LINE is an empty string, leave the current channel.
3045Otherwise leave the channel indicated by LINE."
3046  (cond
3047   ((string-match "^\\s-*\\([&#+!]\\S-+\\)\\s-?\\(.*\\)$" line)
3048    (let* ((ch (match-string 1 line))
3049	   (msg (match-string 2 line))
3050	   (reason (funcall erc-part-reason (if (equal msg "") nil msg))))
3051      (erc-log (format "cmd: PART: %s: %s" ch reason))
3052      (erc-server-send (if (string= reason "")
3053			   (format "PART %s" ch)
3054			 (format "PART %s :%s" ch reason))
3055		       nil ch))
3056    t)
3057   ((string-match "^\\s-*\\(.*\\)$" line)
3058    (let* ((ch (erc-default-target))
3059	   (msg (match-string 1 line))
3060	   (reason (funcall erc-part-reason (if (equal msg "") nil msg))))
3061      (if (and ch (erc-channel-p ch))
3062	  (progn
3063	    (erc-log (format "cmd: PART: %s: %s" ch reason))
3064	    (erc-server-send (if (string= reason "")
3065				 (format "PART %s" ch)
3066			       (format "PART %s :%s" ch reason))
3067			     nil ch))
3068	(erc-display-message nil 'error (current-buffer) 'no-target)))
3069    t)
3070   (t nil)))
3071(put 'erc-cmd-PART 'do-not-parse-args t)
3072
3073(defalias 'erc-cmd-LEAVE 'erc-cmd-PART)
3074
3075(defun erc-cmd-PING (recipient)
3076  "Ping RECIPIENT."
3077  (let ((time (format "%f" (erc-current-time))))
3078    (erc-log (format "cmd: PING: %s" time))
3079    (erc-cmd-CTCP recipient "PING" time)))
3080
3081(defun erc-cmd-QUOTE (line)
3082  "Send LINE directly to the server.
3083All the text given as argument is sent to the sever as unmodified,
3084just as you provided it.  Use this command with care!"
3085  (cond
3086   ((string-match "^ ?\\(.+\\)$" line)
3087    (erc-server-send (match-string 1 line)))
3088   (t nil)))
3089(put 'erc-cmd-QUOTE 'do-not-parse-args t)
3090
3091(defun erc-cmd-QUERY (&optional user)
3092  "Open a query with USER.
3093The type of query window/frame/etc will depend on the value of
3094`erc-join-buffer'.  If USER is omitted, close the current query buffer if one
3095exists - except this is broken now ;-)"
3096  (interactive
3097   (list (read-from-minibuffer "Start a query with: " nil)))
3098  (let ((session-buffer (erc-server-buffer)))
3099    (if user
3100	(erc-query user session-buffer)
3101      ;; currently broken, evil hack to display help anyway
3102      ;(erc-delete-query))))
3103      (signal 'wrong-number-of-arguments ""))))
3104(defalias 'erc-cmd-Q 'erc-cmd-QUERY)
3105
3106(defun erc-quit-reason-normal (&optional s)
3107  "Normal quit message.
3108
3109If S is non-nil, it will be used as the quit reason."
3110  (or s
3111      (format "\C-bERC\C-b %s (IRC client for Emacs)"; - \C-b%s\C-b"
3112	      erc-version-string) ; erc-official-location)
3113  ))
3114
3115(defun erc-quit-reason-zippy (&optional s)
3116  "Zippy quit message.
3117
3118If S is non-nil, it will be used as the quit reason."
3119  (or s
3120      (erc-replace-regexp-in-string "\n" "" (yow))))
3121
3122(defun erc-quit-reason-various (s)
3123  "Choose a quit reason based on S (a string)."
3124  (when (featurep 'xemacs) (require 'poe))
3125  (let ((res (car (assoc-default (or s "")
3126		   erc-quit-reason-various-alist 'string-match))))
3127    (cond
3128     ((functionp res) (funcall res))
3129     ((stringp res) res)
3130     (s s)
3131     (t (erc-quit-reason-normal)))))
3132
3133(defun erc-part-reason-normal (&optional s)
3134  "Normal part message.
3135
3136If S is non-nil, it will be used as the quit reason."
3137  (or s
3138      (format "\C-bERC\C-b %s (IRC client for Emacs)"; - \C-b%s\C-b"
3139	      erc-version-string) ; erc-official-location)
3140  ))
3141
3142(defun erc-part-reason-zippy (&optional s)
3143  "Zippy part message.
3144
3145If S is non-nil, it will be used as the quit reason."
3146  (or s
3147      (erc-replace-regexp-in-string "\n" "" (yow))))
3148
3149(defun erc-part-reason-various (s)
3150  "Choose a part reason based on S (a string)."
3151  (when (featurep 'xemacs) (require 'poe))
3152  (let ((res (car (assoc-default (or s "")
3153		   erc-part-reason-various-alist 'string-match))))
3154    (cond
3155     ((functionp res) (funcall res))
3156     ((stringp res) res)
3157     (s s)
3158     (t (erc-part-reason-normal)))))
3159
3160(defun erc-cmd-QUIT (reason)
3161  "Disconnect from the current server.
3162If REASON is omitted, display a default quit message, otherwise display
3163the message given by REASON."
3164  (unless reason
3165    (setq reason ""))
3166  (cond
3167   ((string-match "^\\s-*\\(.*\\)$" reason)
3168    (let* ((s (match-string 1 reason))
3169	   (buffer (erc-server-buffer))
3170	   (reason (funcall erc-quit-reason (if (equal s "") nil s)))
3171	   server-proc)
3172      (with-current-buffer (if (and buffer
3173				    (bufferp buffer))
3174			       buffer
3175			     (current-buffer))
3176	(erc-log (format "cmd: QUIT: %s" reason))
3177	(setq erc-server-quitting t)
3178	(erc-set-active-buffer (erc-server-buffer))
3179	(setq server-proc erc-server-process)
3180	(erc-server-send (format "QUIT :%s" reason)))
3181      (run-hook-with-args 'erc-quit-hook server-proc)
3182      (when erc-kill-queries-on-quit
3183	(erc-kill-query-buffers server-proc))
3184      ;; if the process has not been killed within 4 seconds, kill it
3185      (run-at-time 4 nil
3186		   (lambda (proc)
3187		     (when (and (processp proc)
3188				(memq (process-status proc) '(run open)))
3189		       (delete-process proc)))
3190		   server-proc))
3191    t)
3192   (t nil)))
3193
3194(defalias 'erc-cmd-BYE 'erc-cmd-QUIT)
3195(defalias 'erc-cmd-EXIT 'erc-cmd-QUIT)
3196(defalias 'erc-cmd-SIGNOFF 'erc-cmd-QUIT)
3197(put 'erc-cmd-QUIT 'do-not-parse-args t)
3198
3199(defun erc-cmd-GQUIT (reason)
3200  "Disconnect from all servers at once with the same quit REASON."
3201  (erc-with-all-buffers-of-server nil #'erc-open-server-buffer-p
3202				  (erc-cmd-QUIT reason)))
3203
3204(defalias 'erc-cmd-GQ 'erc-cmd-GQUIT)
3205(put 'erc-cmd-GQUIT 'do-not-parse-args t)
3206
3207(defun erc-cmd-RECONNECT ()
3208  "Try to reconnect to the current IRC server."
3209  (let ((buffer (or (erc-server-buffer) (current-buffer)))
3210	(process nil))
3211    (with-current-buffer (if (bufferp buffer) buffer (current-buffer))
3212      (setq erc-server-quitting nil)
3213      (setq erc-server-reconnecting t)
3214      (setq erc-server-reconnect-count 0)
3215      (setq process (get-buffer-process (erc-server-buffer)))
3216      (if process
3217	  (delete-process process)
3218	(erc-server-reconnect))
3219      (setq erc-server-reconnecting nil)))
3220  t)
3221
3222(defun erc-cmd-SERVER (server)
3223  "Connect to SERVER, leaving existing connection intact."
3224  (erc-log (format "cmd: SERVER: %s" server))
3225  (condition-case nil
3226      (erc :server server :nick (erc-current-nick))
3227    (error
3228     (message "Cannot find host %s." server)
3229     (beep)))
3230  t)
3231
3232(eval-when-compile
3233  (defvar motif-version-string)
3234  (defvar gtk-version-string))
3235
3236(defun erc-cmd-SV ()
3237  "Say the current ERC and Emacs version into channel."
3238  (erc-send-message (format "I'm using ERC %s with %s %s (%s%s) of %s."
3239			    erc-version-string
3240			    (if (featurep 'xemacs) "XEmacs" "GNU Emacs")
3241			    emacs-version
3242			    system-configuration
3243			    (concat
3244			     (cond ((featurep 'motif)
3245				    (concat ", " (substring
3246						  motif-version-string 4)))
3247				   ((featurep 'gtk)
3248				    (concat ", GTK+ Version "
3249					    gtk-version-string))
3250				   ((featurep 'mac-carbon) ", Mac Carbon")
3251				   ((featurep 'x-toolkit) ", X toolkit")
3252				   (t ""))
3253			     (if (and (boundp 'x-toolkit-scroll-bars)
3254				      (memq x-toolkit-scroll-bars
3255					    '(xaw xaw3d)))
3256				 (format ", %s scroll bars"
3257					 (capitalize (symbol-name
3258						      x-toolkit-scroll-bars)))
3259			       "")
3260			     (if (featurep 'multi-tty) ", multi-tty" ""))
3261			    erc-emacs-build-time))
3262  t)
3263
3264(defun erc-cmd-SM ()
3265  "Say the current ERC modes into channel."
3266  (erc-send-message (format "I'm using the following modules: %s!"
3267			    (erc-modes)))
3268  t)
3269
3270(defun erc-cmd-DEOP (&rest people)
3271  "Remove the operator setting from user(s) given in PEOPLE."
3272  (when (> (length people) 0)
3273    (erc-server-send (concat "MODE " (erc-default-target)
3274			      " -"
3275			      (make-string (length people) ?o)
3276			      " "
3277			      (mapconcat 'identity people " ")))
3278    t))
3279
3280(defun erc-cmd-OP (&rest people)
3281  "Add the operator setting to users(s) given in PEOPLE."
3282  (when (> (length people) 0)
3283    (erc-server-send (concat "MODE " (erc-default-target)
3284			      " +"
3285			      (make-string (length people) ?o)
3286			      " "
3287			      (mapconcat 'identity people " ")))
3288    t))
3289
3290(defun erc-cmd-TIME (&optional line)
3291  "Request the current time and date from the current server."
3292  (cond
3293   ((and line (string-match "^\\s-*\\(.*\\)$" line))
3294    (let ((args (match-string 1 line)))
3295      (erc-log (format "cmd: TIME: %s" args))
3296      (erc-server-send (concat "TIME " args)))
3297    t)
3298   (t (erc-server-send "TIME"))))
3299(defalias 'erc-cmd-DATE 'erc-cmd-TIME)
3300
3301(defun erc-cmd-TOPIC (topic)
3302  "Set or request the topic for a channel.
3303LINE has the format: \"#CHANNEL TOPIC\", \"#CHANNEL\", \"TOPIC\"
3304or the empty string.
3305
3306If no #CHANNEL is given, the default channel is used.  If TOPIC is
3307given, the channel topic is modified, otherwise the current topic will
3308be displayed."
3309  (cond
3310   ;; /topic #channel TOPIC
3311   ((string-match "^\\s-*\\([&#+!]\\S-+\\)\\s-\\(.*\\)$" topic)
3312    (let ((ch (match-string 1 topic))
3313	  (topic (match-string 2 topic)))
3314      (erc-log (format "cmd: TOPIC [%s]: %s" ch topic))
3315      (erc-server-send (format "TOPIC %s :%s" ch topic) nil ch))
3316    t)
3317   ;; /topic #channel
3318   ((string-match "^\\s-*\\([&#+!]\\S-+\\)" topic)
3319    (let ((ch (match-string 1 topic)))
3320      (erc-server-send (format "TOPIC %s" ch) nil ch)
3321      t))
3322   ;; /topic
3323   ((string-match "^\\s-*$" topic)
3324    (let ((ch (erc-default-target)))
3325      (erc-server-send (format "TOPIC %s" ch) nil ch)
3326      t))
3327   ;; /topic TOPIC
3328   ((string-match "^\\s-*\\(.*\\)$" topic)
3329    (let ((ch (erc-default-target))
3330	  (topic (match-string 1 topic)))
3331      (if (and ch (erc-channel-p ch))
3332	  (progn
3333	    (erc-log (format "cmd: TOPIC [%s]: %s" ch topic))
3334	    (erc-server-send (format "TOPIC %s :%s" ch topic) nil ch))
3335	(erc-display-message nil 'error (current-buffer) 'no-target)))
3336    t)
3337   (t nil)))
3338(defalias 'erc-cmd-T 'erc-cmd-TOPIC)
3339(put 'erc-cmd-TOPIC 'do-not-parse-args t)
3340
3341(defun erc-cmd-APPENDTOPIC (topic)
3342  "Append TOPIC to the current channel topic, separated by a space."
3343  (let ((oldtopic erc-channel-topic))
3344    ;; display help when given no arguments
3345    (when (string-match "^\\s-*$" topic)
3346      (signal 'wrong-number-of-arguments nil))
3347    ;; strip trailing ^O
3348    (when (string-match "\\(.*\\)\C-o" oldtopic)
3349      (erc-cmd-TOPIC (concat (match-string 1 oldtopic) topic)))))
3350(defalias 'erc-cmd-AT 'erc-cmd-APPENDTOPIC)
3351(put 'erc-cmd-APPENDTOPIC 'do-not-parse-args t)
3352
3353(defun erc-cmd-CLEARTOPIC (&optional channel)
3354  "Clear the topic for a CHANNEL.
3355If CHANNEL is not specified, clear the topic for the default channel."
3356  (interactive "sClear topic of channel (RET is current channel): ")
3357  (let ((chnl (or (and (erc-channel-p channel) channel) (erc-default-target))))
3358    (when chnl
3359      (erc-server-send (format "TOPIC %s :" chnl))
3360      t)))
3361
3362;;; Banlists
3363
3364(defvar erc-channel-banlist nil
3365  "A list of bans seen for the current channel.
3366
3367Each ban is an alist of the form:
3368  (WHOSET . MASK)
3369
3370The property `received-from-server' indicates whether
3371or not the ban list has been requested from the server.")
3372(make-variable-buffer-local 'erc-channel-banlist)
3373(put 'erc-channel-banlist 'received-from-server nil)
3374
3375(defun erc-cmd-BANLIST ()
3376  "Pretty-print the contents of `erc-channel-banlist'.
3377
3378The ban list is fetched from the server if necessary."
3379  (let ((chnl (erc-default-target))
3380	(chnl-name (buffer-name)))
3381
3382    (cond
3383     ((not (erc-channel-p chnl))
3384      (erc-display-line (erc-make-notice "You're not on a channel\n")
3385			'active))
3386
3387     ((not (get 'erc-channel-banlist 'received-from-server))
3388      (let ((old-367-hook erc-server-367-functions))
3389	(setq erc-server-367-functions 'erc-banlist-store
3390	      erc-channel-banlist nil)
3391	;; fetch the ban list then callback
3392	(erc-with-server-buffer
3393	  (erc-once-with-server-event
3394	   368
3395	   `(with-current-buffer ,chnl-name
3396	      (put 'erc-channel-banlist 'received-from-server t)
3397	      (setq erc-server-367-functions ',old-367-hook)
3398	      (erc-cmd-BANLIST)
3399	      t))
3400	  (erc-server-send (format "MODE %s b" chnl)))))
3401
3402     ((null erc-channel-banlist)
3403      (erc-display-line (erc-make-notice
3404			 (format "No bans for channel: %s\n" chnl))
3405			'active)
3406      (put 'erc-channel-banlist 'received-from-server nil))
3407
3408     (t
3409      (let* ((erc-fill-column (or (and (boundp 'erc-fill-column)
3410				       erc-fill-column)
3411				  (and (boundp 'fill-column)
3412				       fill-column)
3413				  (1- (window-width))))
3414	     (separator (make-string erc-fill-column ?=))
3415	     (fmt (concat
3416		   "%-" (number-to-string (/ erc-fill-column 2)) "s"
3417		   "%" (number-to-string (/ erc-fill-column 2)) "s")))
3418
3419	(erc-display-line
3420	 (erc-make-notice (format "Ban list for channel: %s\n"
3421				  (erc-default-target)))
3422	 'active)
3423
3424	(erc-display-line separator 'active)
3425	(erc-display-line (format fmt "Ban Mask" "Banned By") 'active)
3426	(erc-display-line separator 'active)
3427
3428	(mapc
3429	 (lambda (x)
3430	   (erc-display-line
3431	    (format fmt
3432		    (truncate-string-to-width (cdr x) (/ erc-fill-column 2))
3433		    (if (car x)
3434			(truncate-string-to-width (car x) (/ erc-fill-column 2))
3435		      ""))
3436	    'active))
3437	 erc-channel-banlist)
3438
3439	(erc-display-line (erc-make-notice "End of Ban list")
3440			  'active)
3441	(put 'erc-channel-banlist 'received-from-server nil)))))
3442  t)
3443
3444(defalias 'erc-cmd-BL 'erc-cmd-BANLIST)
3445
3446(defun erc-cmd-MASSUNBAN ()
3447  "Mass Unban.
3448
3449Unban all currently banned users in the current channel."
3450  (let ((chnl (erc-default-target)))
3451    (cond
3452
3453     ((not (erc-channel-p chnl))
3454      (erc-display-line
3455       (erc-make-notice "You're not on a channel\n")
3456       'active))
3457
3458     ((not (get 'erc-channel-banlist 'received-from-server))
3459      (let ((old-367-hook erc-server-367-functions))
3460	(setq erc-server-367-functions 'erc-banlist-store)
3461      ;; fetch the ban list then callback
3462      (erc-with-server-buffer
3463	(erc-once-with-server-event
3464	 368
3465	 `(with-current-buffer ,chnl
3466	    (put 'erc-channel-banlist 'received-from-server t)
3467	      (setq erc-server-367-functions ,old-367-hook)
3468	    (erc-cmd-MASSUNBAN)
3469	    t))
3470	  (erc-server-send (format "MODE %s b" chnl)))))
3471
3472     (t (let ((bans (mapcar 'cdr erc-channel-banlist)))
3473    (when bans
3474      ;; Glob the bans into groups of three, and carry out the unban.
3475      ;; eg. /mode #foo -bbb a*!*@* b*!*@* c*!*@*
3476      (mapc
3477       (lambda (x)
3478	 (erc-server-send
3479	  (format "MODE %s -%s %s" (erc-default-target)
3480		  (make-string (length x) ?b)
3481			(mapconcat 'identity x " "))))
3482       (erc-group-list bans 3))))
3483	t))))
3484
3485(defalias 'erc-cmd-MUB 'erc-cmd-MASSUNBAN)
3486
3487;;;; End of IRC commands
3488
3489(defun erc-ensure-channel-name (channel)
3490  "Return CHANNEL if it is a valid channel name.
3491Eventually add a # in front of it, if that turns it into a valid channel name."
3492  (if (erc-channel-p channel)
3493      channel
3494    (concat "#" channel)))
3495
3496(defun erc-grab-region (start end)
3497  "Copy the region between START and END in a recreatable format.
3498
3499Converts all the IRC text properties in each line of the region
3500into control codes and writes them to a separate buffer.  The
3501resulting text may be used directly as a script to generate this
3502text again."
3503  (interactive "r")
3504  (erc-set-active-buffer (current-buffer))
3505  (save-excursion
3506    (let* ((cb (current-buffer))
3507	   (buf (generate-new-buffer erc-grab-buffer-name))
3508	   (region (buffer-substring start end))
3509	   (lines (erc-split-multiline-safe region)))
3510      (set-buffer buf)
3511      (dolist (line lines)
3512	(insert (concat line "\n")))
3513      (set-buffer cb)
3514      (switch-to-buffer-other-window buf)))
3515  (message "erc-grab-region doesn't grab colors etc. anymore. If you use this, please tell the maintainers.")
3516  (ding))
3517
3518(defun erc-display-prompt (&optional buffer pos prompt face)
3519  "Display PROMPT in BUFFER at position POS.
3520Display an ERC prompt in BUFFER.
3521
3522If PROMPT is nil, one is constructed with the function `erc-prompt'.
3523If BUFFER is nil, the `current-buffer' is used.
3524If POS is nil, PROMPT will be displayed at `point'.
3525If FACE is non-nil, it will be used to propertize the prompt.  If it is nil,
3526`erc-prompt-face' will be used."
3527  (let* ((prompt (or prompt (erc-prompt)))
3528	 (l (length prompt))
3529	 (ob (current-buffer)))
3530    ;; We cannot use save-excursion because we move point, therefore
3531    ;; we resort to the ol' ob trick to restore this.
3532    (when (and buffer (bufferp buffer))
3533      (set-buffer buffer))
3534
3535    ;; now save excursion again to store where point and mark are
3536    ;; in the current buffer
3537    (save-excursion
3538      (setq pos (or pos (point)))
3539      (goto-char pos)
3540      (when (> l 0)
3541	;; Do not extend the text properties when typing at the end
3542	;; of the prompt, but stuff typed in front of the prompt
3543	;; shall remain part of the prompt.
3544	(setq prompt (erc-propertize prompt
3545				     'start-open t ; XEmacs
3546				     'rear-nonsticky t ; Emacs
3547				     'erc-prompt t
3548				     'front-sticky t
3549				     'read-only t))
3550	(erc-put-text-property 0 (1- (length prompt))
3551			       'face (or face 'erc-prompt-face)
3552			       prompt)
3553	(insert prompt))
3554      ;; Set the input marker
3555      (set-marker erc-input-marker (point)))
3556
3557    ;; Now we are back at the old position.  If the prompt was
3558    ;; inserted here or before us, advance point by the length of
3559    ;; the prompt.
3560    (when (or (not pos) (<= (point) pos))
3561      (forward-char l))
3562    ;; Clear the undo buffer now, so the user can undo his stuff,
3563    ;; but not the stuff we did. Sneaky!
3564    (setq buffer-undo-list nil)
3565    (set-buffer ob)))
3566
3567;; interactive operations
3568
3569(defun erc-input-message ()
3570  "Read input from the minibuffer."
3571  (interactive)
3572  (let ((minibuffer-allow-text-properties t)
3573	(read-map minibuffer-local-map))
3574    (insert (read-from-minibuffer "Message: "
3575				  (string last-command-char) read-map))
3576    (erc-send-current-line)))
3577
3578(defvar erc-action-history-list ()
3579  "History list for interactive action input.")
3580
3581(defun erc-input-action ()
3582  "Interactively input a user action and send it to IRC."
3583  (interactive "")
3584  (erc-set-active-buffer (current-buffer))
3585  (let ((action (read-from-minibuffer
3586		 "Action: " nil nil nil 'erc-action-history-list)))
3587    (if (not (string-match "^\\s-*$" action))
3588	(erc-send-action (erc-default-target) action))))
3589
3590(defun erc-join-channel (channel &optional key)
3591  "Join CHANNEL.
3592
3593If `point' is at the beginning of a channel name, use that as default."
3594  (interactive
3595   (list
3596    (let ((chnl (if (looking-at "\\([&#+!][^ \n]+\\)") (match-string 1) ""))
3597	  (table (when (erc-server-buffer-live-p)
3598		   (set-buffer (process-buffer erc-server-process))
3599		   erc-channel-list)))
3600      (completing-read "Join channel: " table nil nil nil nil chnl))
3601    (when erc-prompt-for-channel-key
3602      (read-from-minibuffer "Channel key (RET for none): " nil))))
3603  (erc-cmd-JOIN channel (when (>= (length key) 1) key)))
3604
3605(defun erc-part-from-channel (reason)
3606  "Part from the current channel and prompt for a REASON."
3607  (interactive
3608   (list
3609    (if (and (boundp 'reason) (stringp reason) (not (string= reason "")))
3610	reason
3611      (read-from-minibuffer (concat "Reason for leaving " (erc-default-target)
3612				    ": ")))))
3613  (erc-cmd-PART (concat (erc-default-target)" " reason)))
3614
3615(defun erc-set-topic (topic)
3616  "Prompt for a TOPIC for the current channel."
3617  (interactive
3618   (list
3619    (read-from-minibuffer
3620     (concat "Set topic of " (erc-default-target) ": ")
3621     (when erc-channel-topic
3622       (cons (apply 'concat (butlast (split-string erc-channel-topic "\C-o")))
3623	     0)))))
3624  (let ((topic-list (split-string topic "\C-o"))) ; strip off the topic setter
3625    (erc-cmd-TOPIC (concat (erc-default-target) " " (car topic-list)))))
3626
3627(defun erc-set-channel-limit (&optional limit)
3628  "Set a LIMIT for the current channel.  Remove limit if nil.
3629Prompt for one if called interactively."
3630  (interactive (list (read-from-minibuffer
3631		      (format "Limit for %s (RET to remove limit): "
3632			      (erc-default-target)))))
3633  (let ((tgt (erc-default-target)))
3634    (if (and limit (>= (length limit) 1))
3635	(erc-server-send (format "MODE %s +l %s" tgt limit))
3636      (erc-server-send (format "MODE %s -l" tgt)))))
3637
3638(defun erc-set-channel-key (&optional key)
3639  "Set a KEY for the current channel.  Remove key if nil.
3640Prompt for one if called interactively."
3641  (interactive (list (read-from-minibuffer
3642		      (format "Key for %s (RET to remove key): "
3643			      (erc-default-target)))))
3644  (let ((tgt (erc-default-target)))
3645    (if (and key (>= (length key) 1))
3646	(erc-server-send (format "MODE %s +k %s" tgt key))
3647      (erc-server-send (format "MODE %s -k" tgt)))))
3648
3649(defun erc-quit-server (reason)
3650  "Disconnect from current server after prompting for REASON.
3651`erc-quit-reason' works with this just like with `erc-cmd-QUIT'."
3652  (interactive (list (read-from-minibuffer
3653		      (format "Reason for quitting %s: "
3654			      (or erc-server-announced-name
3655				  erc-session-server)))))
3656  (erc-cmd-QUIT reason))
3657
3658;; Movement of point
3659
3660(defun erc-bol ()
3661  "Move `point' to the beginning of the current line.
3662
3663This places `point' just after the prompt, or at the beginning of the line."
3664  (interactive)
3665  (forward-line 0)
3666  (when (get-text-property (point) 'erc-prompt)
3667    (goto-char erc-input-marker))
3668  (point))
3669
3670(defun erc-kill-input ()
3671  "Kill current input line using `erc-bol' followed by `kill-line'."
3672  (interactive)
3673  (when (and (erc-bol)
3674	     (/= (point) (point-max))) ;; Prevent a (ding) and an error when
3675				       ;; there's nothing to kill
3676    (if (boundp 'erc-input-ring-index)
3677	(setq erc-input-ring-index nil))
3678    (kill-line)))
3679
3680(defun erc-complete-word ()
3681  "Complete the word before point.
3682
3683This function uses `erc-complete-functions'."
3684  (interactive)
3685  (unless (run-hook-with-args-until-success 'erc-complete-functions)
3686    (beep)))
3687
3688;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3689;;
3690;;			  IRC SERVER INPUT HANDLING
3691;;
3692;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3693
3694;;;; New Input parsing
3695
3696; Stolen from ZenIRC. I just wanna test this code, so here is
3697; experiment area.
3698
3699(defcustom erc-default-server-hook '(erc-debug-missing-hooks
3700				     erc-default-server-handler)
3701  "*Default for server messages which aren't covered by `erc-server-hooks'."
3702  :group 'erc-server-hooks
3703  :type 'hook)
3704
3705(defun erc-default-server-handler (proc parsed)
3706  "Default server handler.
3707
3708Displays PROC and PARSED appropriately using `erc-display-message'."
3709  (erc-display-message
3710   parsed 'notice proc
3711   (mapconcat
3712    'identity
3713    (let (res)
3714      (mapc #'(lambda (x)
3715		(if (stringp x)
3716		    (setq res (append res (list x)))))
3717	    parsed)
3718      res)
3719    " ")))
3720
3721(defvar erc-server-vectors
3722  '(["msgtype" "sender" "to" "arg1" "arg2" "arg3" "..."])
3723  "List of received server messages which ERC does not specifically handle.
3724See `erc-debug-missing-hooks'.")
3725;(make-variable-buffer-local 'erc-server-vectors)
3726
3727(defun erc-debug-missing-hooks (proc parsed)
3728  "Add PARSED server message ERC does not yet handle to `erc-server-vectors'.
3729These vectors can be helpful when adding new server message handlers to ERC.
3730See `erc-default-server-hook'."
3731  (nconc erc-server-vectors (list parsed))
3732  nil)
3733
3734(defun erc-query (target server)
3735  "Open a query buffer on TARGET, using SERVER.
3736To change how this query window is displayed, use `let' to bind
3737`erc-join-buffer' before calling this."
3738  (unless (and server
3739	       (buffer-live-p server)
3740	       (set-buffer server))
3741    (error "Couldn't switch to server buffer"))
3742  (let ((buf (erc-open erc-session-server
3743		       erc-session-port
3744		       (erc-current-nick)
3745		       erc-session-user-full-name
3746		       nil
3747		       nil
3748		       (list target)
3749		       target
3750		       erc-server-process)))
3751    (unless buf
3752      (error "Couldn't open query window"))
3753    (erc-update-mode-line)
3754    buf))
3755
3756(defcustom erc-auto-query 'bury
3757  "If non-nil, create a query buffer each time you receive a private message.
3758
3759If the buffer doesn't already exist it is created.  This can be
3760set to a symbol, to control how the new query window should
3761appear.  See the documentation for `erc-join-buffer' for
3762available choices."
3763  :group 'erc-query
3764  :type '(choice (const nil)
3765		 (const buffer)
3766		 (const window)
3767		 (const window-noselect)
3768		 (const bury)
3769		 (const frame)))
3770
3771(defcustom erc-query-on-unjoined-chan-privmsg t
3772  "If non-nil create query buffer on receiving any PRIVMSG at all.
3773This includes PRIVMSGs directed to channels.  If you are using an IRC
3774bouncer, such as dircproxy, to keep a log of channels when you are
3775disconnected, you should set this option to t."
3776  :group 'erc-query
3777  :type 'boolean)
3778
3779(defcustom erc-format-query-as-channel-p t
3780  "If non-nil, format text from others in a query buffer like in a channel,
3781otherwise format like a private message."
3782  :group 'erc-query
3783  :type 'boolean)
3784
3785(defcustom erc-minibuffer-notice nil
3786  "If non-nil, print ERC notices for the user in the minibuffer.
3787Only happens when the session buffer isn't visible."
3788  :group 'erc-display
3789  :type 'boolean)
3790
3791(defcustom erc-minibuffer-ignored nil
3792  "If non-nil, print a message in the minibuffer if we ignored something."
3793  :group 'erc-ignore
3794  :type 'boolean)
3795
3796(defun erc-wash-quit-reason (reason nick login host)
3797  "Remove duplicate text from quit REASON.
3798Specifically in relation to NICK (user@host) information.  Returns REASON
3799unmodified if nothing can be removed.
3800E.g. \"Read error to Nick [user@some.host]: 110\" would be shortened to
3801\"Read error: 110\". The same applies for \"Ping Timeout\"."
3802  (setq nick (regexp-quote nick)
3803	login (regexp-quote login)
3804	host (regexp-quote host))
3805  (or (when (string-match (concat "^\\(Read error\\) to "
3806				  nick "\\[" host "\\]: "
3807				  "\\(.+\\)$") reason)
3808	(concat (match-string 1 reason) ": " (match-string 2 reason)))
3809      (when (string-match (concat "^\\(Ping timeout\\) for "
3810				  nick "\\[" host "\\]$") reason)
3811	(match-string 1 reason))
3812      reason))
3813
3814(defun erc-nickname-in-use (nick reason)
3815  "If NICK is unavailable, tell the user the REASON.
3816
3817See also `erc-display-error-notice'."
3818  (if (or (not erc-try-new-nick-p)
3819	  ;; how many default-nicks are left + one more try...
3820	  (eq erc-nick-change-attempt-count
3821	      (if (consp erc-nick)
3822		  (+ (length erc-nick) 1)
3823		1)))
3824      (erc-display-error-notice
3825       nil
3826       (format "Nickname %s is %s, try another." nick reason))
3827    (setq erc-nick-change-attempt-count (+ erc-nick-change-attempt-count 1))
3828    (let ((newnick (nth 1 erc-default-nicks))
3829	  (nicklen (cdr (assoc "NICKLEN"
3830			       (erc-with-server-buffer
3831				 erc-server-parameters)))))
3832      (setq erc-bad-nick t)
3833      ;; try to use a different nick
3834      (if erc-default-nicks
3835	  (setq erc-default-nicks (cdr erc-default-nicks)))
3836      (if (not newnick)
3837	  (setq newnick (concat (truncate-string-to-width
3838				 nick
3839				 (if (and erc-server-connected nicklen)
3840				     (- (string-to-number nicklen)
3841					(length erc-nick-uniquifier))
3842				   ;; rfc2812 max nick length = 9
3843				   ;; we must assume this is the
3844				   ;; server's setting if we haven't
3845				   ;; established a connection yet
3846				   (- 9 (length erc-nick-uniquifier))))
3847				erc-nick-uniquifier)))
3848      (erc-cmd-NICK newnick)
3849      (erc-display-error-notice
3850       nil
3851       (format "Nickname %s is %s, trying %s"
3852	       nick reason newnick)))))
3853
3854;;; Server messages
3855
3856(defgroup erc-server-hooks nil
3857  "Server event callbacks.
3858Every server event - like numeric replies - has its own hook.
3859Those hooks are all called using `run-hook-with-args-until-success'.
3860They receive as first argument the process object from where the event
3861originated from,
3862and as second argument the event parsed as a vector."
3863  :group 'erc-hooks)
3864
3865(defun erc-display-server-message (proc parsed)
3866  "Display the message sent by the server as a notice."
3867  (erc-display-message
3868   parsed 'notice 'active (erc-response.contents parsed)))
3869
3870(defun erc-auto-query (proc parsed)
3871  ;; FIXME: This needs more documentation, unless it's not a user function --
3872  ;; Lawrence 2004-01-08
3873  "Put this on `erc-server-PRIVMSG-functions'."
3874  (when erc-auto-query
3875    (let* ((nick (car (erc-parse-user (erc-response.sender parsed))))
3876	   (target (car (erc-response.command-args parsed)))
3877	   (msg (erc-response.contents parsed))
3878	   (query  (if (not erc-query-on-unjoined-chan-privmsg)
3879		       nick
3880		     (if (erc-current-nick-p target)
3881			 nick
3882		       target))))
3883      (and (not (erc-ignored-user-p (erc-response.sender parsed)))
3884	   (or erc-query-on-unjoined-chan-privmsg
3885	       (string= target (erc-current-nick)))
3886	   (not (erc-get-buffer query proc))
3887	   (not (erc-is-message-ctcp-and-not-action-p msg))
3888	   (let ((erc-join-buffer erc-auto-query))
3889	     (erc-cmd-QUERY query))
3890	   nil))))
3891
3892(defun erc-is-message-ctcp-p (message)
3893  "Check if MESSAGE is a CTCP message or not."
3894  (string-match "^\C-a\\([^\C-a]*\\)\C-a?$" message))
3895
3896(defun erc-is-message-ctcp-and-not-action-p (message)
3897  "Check if MESSAGE is a CTCP message or not."
3898  (and (erc-is-message-ctcp-p message)
3899       (not (string-match "^\C-a\\ACTION.*\C-a$" message))))
3900
3901(defun erc-format-privmessage (nick msg privp msgp)
3902  "Format a PRIVMSG in an insertible fashion."
3903  (let* ((mark-s (if msgp (if privp "*" "<") "-"))
3904	 (mark-e (if msgp (if privp "*" ">") "-"))
3905	 (str	 (format "%s%s%s %s" mark-s nick mark-e msg))
3906	 (nick-face (if privp 'erc-nick-msg-face 'erc-nick-default-face))
3907	 (msg-face (if privp 'erc-direct-msg-face 'erc-default-face)))
3908    ;; add text properties to text before the nick, the nick and after the nick
3909    (erc-put-text-property 0 (length mark-s) 'face msg-face str)
3910    (erc-put-text-property (length mark-s) (+ (length mark-s) (length nick))
3911			   'face nick-face str)
3912    (erc-put-text-property (+ (length mark-s) (length nick)) (length str)
3913			   'face msg-face str)
3914    str))
3915
3916(defcustom erc-format-nick-function 'erc-format-nick
3917  "*Function to format a nickname for message display."
3918  :group 'erc-display
3919  :type 'function)
3920
3921(defun erc-format-nick (&optional user channel-data)
3922  "Return the nickname of USER.
3923See also `erc-format-nick-function'."
3924  (when user (erc-server-user-nickname user)))
3925
3926(defun erc-format-@nick (&optional user channel-data)
3927  "Format the nickname of USER showing if USER is an operator or has voice.
3928Operators have \"@\" and users with voice have \"+\" as a prefix.
3929Use CHANNEL-DATA to determine op and voice status.
3930See also `erc-format-nick-function'."
3931  (when user
3932    (let ((op (and channel-data (erc-channel-user-op channel-data) "@"))
3933	  (voice (and channel-data (erc-channel-user-voice channel-data) "+")))
3934      (concat voice op (erc-server-user-nickname user)))))
3935
3936(defun erc-format-my-nick ()
3937  "Return the beginning of this user's message, correctly propertized."
3938  (if erc-show-my-nick
3939      (let ((open "<")
3940	    (close "> ")
3941	    (nick (erc-current-nick)))
3942	(concat
3943	 (erc-propertize open 'face 'erc-default-face)
3944	 (erc-propertize nick 'face 'erc-my-nick-face)
3945	 (erc-propertize close 'face 'erc-default-face)))
3946    (let ((prefix "> "))
3947      (erc-propertize prefix 'face 'erc-default-face))))
3948
3949(defun erc-echo-notice-in-default-buffer (s parsed buffer sender)
3950  "Echos a private notice in the default buffer, namely the
3951target buffer specified by BUFFER, or there is no target buffer,
3952the server buffer.  This function is designed to be added to
3953either `erc-echo-notice-hook' or `erc-echo-notice-always-hook',
3954and always returns t."
3955  (erc-display-message parsed nil buffer s)
3956  t)
3957
3958(defun erc-echo-notice-in-target-buffer (s parsed buffer sender)
3959  "Echos a private notice in BUFFER, if BUFFER is non-nil.  This
3960function is designed to be added to either `erc-echo-notice-hook'
3961or `erc-echo-notice-always-hook', and returns non-nil iff BUFFER
3962is non-nil."
3963  (if buffer
3964      (progn (erc-display-message parsed nil buffer s) t)
3965    nil))
3966
3967(defun erc-echo-notice-in-minibuffer (s parsed buffer sender)
3968  "Echos a private notice in the minibuffer.  This function is
3969designed to be added to either `erc-echo-notice-hook' or
3970`erc-echo-notice-always-hook', and always returns t."
3971  (message "%s" (concat "NOTICE: " s))
3972  t)
3973
3974(defun erc-echo-notice-in-server-buffer (s parsed buffer sender)
3975  "Echos a private notice in the server buffer.  This function is
3976designed to be added to either `erc-echo-notice-hook' or
3977`erc-echo-notice-always-hook', and always returns t."
3978  (erc-display-message parsed nil nil s)
3979  t)
3980
3981(defun erc-echo-notice-in-active-non-server-buffer (s parsed buffer sender)
3982  "Echos a private notice in the active buffer if the active
3983buffer is not the server buffer.  This function is designed to be
3984added to either `erc-echo-notice-hook' or
3985`erc-echo-notice-always-hook', and returns non-nil iff the active
3986buffer is not the server buffer."
3987  (if (not (eq (erc-server-buffer) (erc-active-buffer)))
3988      (progn (erc-display-message parsed nil 'active s) t)
3989    nil))
3990
3991(defun erc-echo-notice-in-active-buffer (s parsed buffer sender)
3992  "Echos a private notice in the active buffer.  This function is
3993designed to be added to either `erc-echo-notice-hook' or
3994`erc-echo-notice-always-hook', and always returns t."
3995  (erc-display-message parsed nil 'active s)
3996  t)
3997
3998(defun erc-echo-notice-in-user-buffers (s parsed buffer sender)
3999  "Echos a private notice in all of the buffers for which SENDER
4000is a member.  This function is designed to be added to either
4001`erc-echo-notice-hook' or `erc-echo-notice-always-hook', and
4002returns non-nil iff there is at least one buffer for which the
4003sender is a member.
4004
4005See also: `erc-echo-notice-in-first-user-buffer',
4006`erc-buffer-list-with-nick'."
4007  (let ((buffers (erc-buffer-list-with-nick sender erc-server-process)))
4008    (if buffers
4009	(progn (erc-display-message parsed nil buffers s) t)
4010      nil)))
4011
4012(defun erc-echo-notice-in-user-and-target-buffers (s parsed buffer sender)
4013  "Echos a private notice in BUFFER and in all of the buffers for
4014which SENDER is a member.  This function is designed to be added
4015to either `erc-echo-notice-hook' or
4016`erc-echo-notice-always-hook', and returns non-nil iff there is
4017at least one buffer for which the sender is a member or the
4018default target.
4019
4020See also: `erc-echo-notice-in-user-buffers',
4021`erc-buffer-list-with-nick'."
4022  (let ((buffers (erc-buffer-list-with-nick sender erc-server-process)))
4023    (add-to-list 'buffers buffer)
4024    (if buffers
4025	(progn (erc-display-message parsed nil buffers s) t)
4026      nil)))
4027
4028(defun erc-echo-notice-in-first-user-buffer (s parsed buffer sender)
4029  "Echos a private notice in one of the buffers for which SENDER
4030is a member.  This function is designed to be added to either
4031`erc-echo-notice-hook' or `erc-echo-notice-always-hook', and
4032returns non-nil iff there is at least one buffer for which the
4033sender is a member.
4034
4035See also: `erc-echo-notice-in-user-buffers',
4036`erc-buffer-list-with-nick'."
4037  (let ((buffers (erc-buffer-list-with-nick sender erc-server-process)))
4038    (if buffers
4039	(progn (erc-display-message parsed nil (car buffers) s) t)
4040      nil)))
4041
4042;;; Ban manipulation
4043
4044(defun erc-banlist-store (proc parsed)
4045  "Record ban entries for a channel."
4046  (multiple-value-bind (channel mask whoset)
4047      (cdr (erc-response.command-args parsed))
4048    ;; Determine to which buffer the message corresponds
4049    (let ((buffer (erc-get-buffer channel proc)))
4050      (with-current-buffer buffer
4051	(unless (member (cons whoset mask) erc-channel-banlist)
4052	  (setq erc-channel-banlist (cons (cons whoset mask)
4053					  erc-channel-banlist))))))
4054  nil)
4055
4056(defun erc-banlist-finished (proc parsed)
4057  "Record that we have received the banlist."
4058  (let* ((channel (second (erc-response.command-args parsed)))
4059	 (buffer (erc-get-buffer channel proc)))
4060    (with-current-buffer buffer
4061      (put 'erc-channel-banlist 'received-from-server t)))
4062  t)					; suppress the 'end of banlist' message
4063
4064(defun erc-banlist-update (proc parsed)
4065  "Check MODE commands for bans and update the banlist appropriately."
4066  ;; FIXME: Possibly incorrect. -- Lawrence 2004-05-11
4067  (let* ((tgt (first (erc-response.command-args parsed)))
4068	 (mode (erc-response.contents parsed))
4069	 (whoset (erc-response.sender parsed))
4070	 (buffer (erc-get-buffer tgt proc)))
4071    (when buffer
4072      (with-current-buffer buffer
4073	(cond ((not (get 'erc-channel-banlist 'received-from-server)) nil)
4074	      ((string-match "^\\([+-]\\)b" mode)
4075	       ;; This is a ban
4076	       (cond
4077		((string-match "^-" mode)
4078		 ;; Remove the unbanned masks from the ban list
4079		 (setq erc-channel-banlist
4080		       (erc-delete-if
4081			#'(lambda (y)
4082			    (member (upcase (cdr y))
4083				    (mapcar #'upcase
4084					    (cdr (split-string mode)))))
4085			erc-channel-banlist)))
4086		((string-match "^+" mode)
4087		 ;; Add the banned mask(s) to the ban list
4088		 (mapc
4089		  (lambda (mask)
4090		    (unless (member (cons whoset mask) erc-channel-banlist)
4091		      (setq erc-channel-banlist
4092			    (cons (cons whoset mask) erc-channel-banlist))))
4093		  (cdr (split-string mode))))))))))
4094  nil)
4095
4096;; used for the banlist cmds
4097(defun erc-group-list (list n)
4098  "Group LIST into sublists of length N."
4099  (cond ((null list) nil)
4100	((null (nthcdr n list)) (list list))
4101	(t (cons (erc-subseq list 0 n) (erc-group-list (nthcdr n list) n)))))
4102
4103
4104;;; MOTD numreplies
4105
4106(defun erc-handle-login ()
4107  "Handle the logging in process of connection."
4108  (unless erc-logged-in
4109    (setq erc-logged-in t)
4110    (message "Logging in as \'%s\'... done" (erc-current-nick))
4111    ;; execute a startup script
4112    (let ((f (erc-select-startup-file)))
4113      (when f
4114	(erc-load-script f)))))
4115
4116(defun erc-connection-established (proc parsed)
4117  "Run just after connection.
4118
4119Set user modes and run `erc-after-connect' hook."
4120  (with-current-buffer (process-buffer proc)
4121    (unless erc-server-connected ; only once per session
4122      (let ((server (or erc-server-announced-name
4123			(erc-response.sender parsed)))
4124	    (nick (car (erc-response.command-args parsed)))
4125	    (buffer (process-buffer proc)))
4126	(setq erc-server-connected t)
4127	(erc-update-mode-line)
4128	(erc-set-initial-user-mode nick buffer)
4129	(erc-server-setup-periodical-ping buffer)
4130	(run-hook-with-args 'erc-after-connect server nick)))))
4131
4132(defun erc-set-initial-user-mode (nick buffer)
4133  "If `erc-user-mode' is non-nil for NICK, set the user modes.
4134The server buffer is given by BUFFER."
4135  (with-current-buffer buffer
4136    (when erc-user-mode
4137      (let ((mode (if (functionp erc-user-mode)
4138		      (funcall erc-user-mode)
4139		    erc-user-mode)))
4140	(when (stringp mode)
4141	  (erc-log (format "changing mode for %s to %s" nick mode))
4142	  (erc-server-send (format "MODE %s %s" nick mode)))))))
4143
4144(defun erc-display-error-notice (parsed string)
4145  "Display STRING as an error notice.
4146
4147See also `erc-display-message'."
4148  (erc-display-message
4149   parsed '(notice error) 'active string))
4150
4151(defun erc-process-ctcp-query (proc parsed nick login host)
4152  ;; FIXME: This needs a proper docstring -- Lawrence 2004-01-08
4153  "Process a CTCP query."
4154  (let ((queries (delete "" (split-string (erc-response.contents parsed)
4155					  "\C-a"))))
4156    (if (> (length queries) 4)
4157	(erc-display-message
4158	 parsed (list 'notice 'error) proc 'ctcp-too-many)
4159      (if (= 0 (length queries))
4160	  (erc-display-message
4161	   parsed (list 'notice 'error) proc
4162	   'ctcp-empty ?n nick)
4163	(while queries
4164	  (let* ((type (upcase (car (split-string (car queries)))))
4165		 (hook (intern-soft (concat "erc-ctcp-query-" type "-hook"))))
4166	    (if (and hook (boundp hook))
4167		(if (string-equal type "ACTION")
4168		    (run-hook-with-args-until-success
4169		     hook proc parsed nick login host
4170		     (car (erc-response.command-args parsed))
4171		     (car queries))
4172		  (when erc-paranoid
4173		    (if (erc-current-nick-p
4174			 (car (erc-response.command-args parsed)))
4175			(erc-display-message
4176			 parsed 'error 'active 'ctcp-request
4177			 ?n nick ?u login ?h host ?r (car queries))
4178		      (erc-display-message
4179		       parsed 'error 'active 'ctcp-request-to
4180		       ?n nick ?u login ?h host ?r (car queries)
4181		       ?t (car (erc-response.command-args parsed)))))
4182		  (run-hook-with-args-until-success
4183		   hook proc nick login host
4184		   (car (erc-response.command-args parsed))
4185		   (car queries)))
4186	      (erc-display-message
4187	       parsed (list 'notice 'error) proc
4188	       'undefined-ctcp)))
4189	  (setq queries (cdr queries)))))))
4190
4191(defvar erc-ctcp-query-ACTION-hook '(erc-ctcp-query-ACTION))
4192
4193(defun erc-ctcp-query-ACTION (proc parsed nick login host to msg)
4194  "Respond to a CTCP ACTION query."
4195  (when (string-match "^ACTION\\s-\\(.*\\)\\s-*$" msg)
4196    (let ((s (match-string 1 msg))
4197	  (buf (or (erc-get-buffer to proc)
4198		   (erc-get-buffer nick proc)
4199		   (process-buffer proc))))
4200      (erc-display-message
4201       parsed 'action buf
4202       'ACTION ?n nick ?u login ?h host ?a s))))
4203
4204(defvar erc-ctcp-query-CLIENTINFO-hook '(erc-ctcp-query-CLIENTINFO))
4205
4206(defun erc-ctcp-query-CLIENTINFO (proc nick login host to msg)
4207  "Respond to a CTCP CLIENTINFO query."
4208  (when (string-match "^CLIENTINFO\\(\\s-*\\|\\s-+.*\\)$" msg)
4209    (let ((s (erc-client-info (erc-trim-string (match-string 1 msg)))))
4210      (unless erc-disable-ctcp-replies
4211	  (erc-send-ctcp-notice nick (format "CLIENTINFO %s" s)))))
4212  nil)
4213
4214(defvar erc-ctcp-query-ECHO-hook '(erc-ctcp-query-ECHO))
4215(defun erc-ctcp-query-ECHO (proc nick login host to msg)
4216  "Respond to a CTCP ECHO query."
4217  (when (string-match "^ECHO\\s-+\\(.*\\)\\s-*$" msg)
4218    (let ((s (match-string 1 msg)))
4219      (unless erc-disable-ctcp-replies
4220	(erc-send-ctcp-notice nick (format "ECHO %s" s)))))
4221  nil)
4222
4223(defvar erc-ctcp-query-FINGER-hook '(erc-ctcp-query-FINGER))
4224(defun erc-ctcp-query-FINGER (proc nick login host to msg)
4225  "Respond to a CTCP FINGER query."
4226  (unless erc-disable-ctcp-replies
4227    (let ((s (if erc-anonymous-login
4228		 (format "FINGER I'm %s." (erc-current-nick))
4229	       (format "FINGER %s (%s@%s)."
4230		       (user-full-name)
4231		       (user-login-name)
4232		       (system-name))))
4233	  (ns (erc-time-diff erc-server-last-sent-time (erc-current-time))))
4234	(when (> ns 0)
4235	    (setq s (concat s " Idle for " (erc-sec-to-time ns))))
4236	(erc-send-ctcp-notice nick s)))
4237  nil)
4238
4239(defvar erc-ctcp-query-PING-hook '(erc-ctcp-query-PING))
4240(defun erc-ctcp-query-PING (proc nick login host to msg)
4241  "Respond to a CTCP PING query."
4242  (when (string-match "^PING\\s-+\\(.*\\)" msg)
4243    (unless erc-disable-ctcp-replies
4244      (let ((arg (match-string 1 msg)))
4245	(erc-send-ctcp-notice nick (format "PING %s" arg)))))
4246  nil)
4247
4248(defvar erc-ctcp-query-TIME-hook '(erc-ctcp-query-TIME))
4249(defun erc-ctcp-query-TIME (proc nick login host to msg)
4250  "Respond to a CTCP TIME query."
4251  (unless erc-disable-ctcp-replies
4252    (erc-send-ctcp-notice nick (format "TIME %s" (current-time-string))))
4253  nil)
4254
4255(defvar erc-ctcp-query-USERINFO-hook '(erc-ctcp-query-USERINFO))
4256(defun erc-ctcp-query-USERINFO (proc nick login host to msg)
4257  "Respond to a CTCP USERINFO query."
4258  (unless erc-disable-ctcp-replies
4259    (erc-send-ctcp-notice nick (format "USERINFO %s" erc-user-information)))
4260  nil)
4261
4262(defvar erc-ctcp-query-VERSION-hook '(erc-ctcp-query-VERSION))
4263(defun erc-ctcp-query-VERSION (proc nick login host to msg)
4264  "Respond to a CTCP VERSION query."
4265  (unless erc-disable-ctcp-replies
4266    (erc-send-ctcp-notice
4267     nick (format
4268	   "VERSION \C-bERC\C-b %s - an IRC client for emacs (\C-b%s\C-b)"
4269	   erc-version-string
4270	   erc-official-location)))
4271  nil)
4272
4273(defun erc-process-ctcp-reply (proc parsed nick login host msg)
4274  "Process MSG as a CTCP reply."
4275  (let* ((type (car (split-string msg)))
4276	 (hook (intern (concat "erc-ctcp-reply-" type "-hook"))))
4277    (if (boundp hook)
4278	(run-hook-with-args-until-success
4279	 hook proc nick login host
4280	 (car (erc-response.command-args parsed)) msg)
4281      (erc-display-message
4282       parsed 'notice 'active
4283       'CTCP-UNKNOWN ?n nick ?u login ?h host ?m msg))))
4284
4285(defvar erc-ctcp-reply-ECHO-hook '(erc-ctcp-reply-ECHO))
4286(defun erc-ctcp-reply-ECHO (proc nick login host to msg)
4287  "Handle a CTCP ECHO reply."
4288  (when (string-match "^ECHO\\s-+\\(.*\\)\\s-*$" msg)
4289    (let ((message (match-string 1 msg)))
4290      (erc-display-message
4291       nil '(notice action) 'active
4292       'CTCP-ECHO ?n nick ?m message)))
4293  nil)
4294
4295(defvar erc-ctcp-reply-CLIENTINFO-hook '(erc-ctcp-reply-CLIENTINFO))
4296(defun erc-ctcp-reply-CLIENTINFO (proc nick login host to msg)
4297  "Handle a CTCP CLIENTINFO reply."
4298  (when (string-match "^CLIENTINFO\\s-+\\(.*\\)\\s-*$" msg)
4299    (let ((message (match-string 1 msg)))
4300      (erc-display-message
4301       nil 'notice 'active
4302       'CTCP-CLIENTINFO ?n nick ?m message)))
4303  nil)
4304
4305(defvar erc-ctcp-reply-FINGER-hook '(erc-ctcp-reply-FINGER))
4306(defun erc-ctcp-reply-FINGER (proc nick login host to msg)
4307  "Handle a CTCP FINGER reply."
4308  (when (string-match "^FINGER\\s-+\\(.*\\)\\s-*$" msg)
4309    (let ((message (match-string 1 msg)))
4310      (erc-display-message
4311       nil 'notice 'active
4312       'CTCP-FINGER ?n nick ?m message)))
4313  nil)
4314
4315(defvar erc-ctcp-reply-PING-hook '(erc-ctcp-reply-PING))
4316(defun erc-ctcp-reply-PING (proc nick login host to msg)
4317  "Handle a CTCP PING reply."
4318  (if (not (string-match "^PING\\s-+\\([0-9.]+\\)" msg))
4319      nil
4320    (let ((time (match-string 1 msg)))
4321      (condition-case nil
4322	  (let ((delta (erc-time-diff (string-to-number time)
4323				      (erc-current-time))))
4324	    (erc-display-message
4325	     nil 'notice 'active
4326	     'CTCP-PING ?n nick
4327	     ?t (erc-sec-to-time delta)))
4328	(range-error
4329	 (erc-display-message
4330	  nil 'error 'active
4331	  'bad-ping-response ?n nick ?t time))))))
4332
4333(defvar erc-ctcp-reply-TIME-hook '(erc-ctcp-reply-TIME))
4334(defun erc-ctcp-reply-TIME (proc nick login host to msg)
4335  "Handle a CTCP TIME reply."
4336  (when (string-match "^TIME\\s-+\\(.*\\)\\s-*$" msg)
4337    (let ((message (match-string 1 msg)))
4338      (erc-display-message
4339       nil 'notice 'active
4340       'CTCP-TIME ?n nick ?m message)))
4341  nil)
4342
4343(defvar erc-ctcp-reply-VERSION-hook '(erc-ctcp-reply-VERSION))
4344(defun erc-ctcp-reply-VERSION (proc nick login host to msg)
4345  "Handle a CTCP VERSION reply."
4346  (when (string-match "^VERSION\\s-+\\(.*\\)\\s-*$" msg)
4347    (let ((message (match-string 1 msg)))
4348      (erc-display-message
4349       nil 'notice 'active
4350       'CTCP-VERSION ?n nick ?m message)))
4351  nil)
4352
4353(defun erc-process-away (proc away-p)
4354  "Toggle the away status of the user depending on the value of AWAY-P.
4355
4356If nil, set the user as away.
4357If non-nil, return from being away."
4358  (let ((sessionbuf (process-buffer proc)))
4359    (when sessionbuf
4360      (with-current-buffer sessionbuf
4361	(when erc-away-nickname
4362	  (erc-log (format "erc-process-away: away-nick: %s, away-p: %s"
4363			   erc-away-nickname away-p))
4364	  (erc-cmd-NICK (if away-p
4365			    erc-away-nickname
4366			  erc-nick)))
4367	(cond
4368	 (away-p
4369	  (setq erc-away (current-time)))
4370	 (t
4371	  (let ((away-time erc-away))
4372	    ;; away must be set to NIL BEFORE sending anything to prevent
4373	    ;; an infinite recursion
4374	    (setq erc-away nil)
4375	    (save-excursion
4376	      (set-buffer (erc-active-buffer))
4377	      (when erc-public-away-p
4378		(erc-send-action
4379		 (erc-default-target)
4380		 (if away-time
4381		     (format "is back (gone for %s)"
4382			     (erc-sec-to-time
4383			      (erc-time-diff
4384			       (erc-emacs-time-to-erc-time away-time)
4385			       (erc-current-time))))
4386		   "is back")))))))))
4387    (erc-update-mode-line)))
4388
4389;;;; List of channel members handling
4390
4391(defun erc-channel-begin-receiving-names ()
4392  "Internal function.
4393
4394Used when a channel names list is about to be received.  Should
4395be called with the current buffer set to the channel buffer.
4396
4397See also `erc-channel-end-receiving-names'."
4398  (setq erc-channel-new-member-names (make-hash-table :test 'equal)))
4399
4400(defun erc-channel-end-receiving-names ()
4401  "Internal function.
4402
4403Used to fix `erc-channel-users' after a channel names list has been
4404received.  Should be called with the current buffer set to the
4405channel buffer.
4406
4407See also `erc-channel-begin-receiving-names'."
4408  (maphash (lambda (nick user)
4409	     (if (null (gethash nick erc-channel-new-member-names))
4410		 (erc-remove-channel-user nick)))
4411	   erc-channel-users)
4412  (setq erc-channel-new-member-names nil))
4413
4414(defun erc-channel-receive-names (names-string)
4415  "This function is for internal use only.
4416
4417Update `erc-channel-users' according to NAMES-STRING.
4418NAMES-STRING is a string listing some of the names on the
4419channel."
4420  (let (names name op voice)
4421      ;; We need to delete "" because in XEmacs, (split-string "a ")
4422      ;; returns ("a" "").
4423      (setq names (delete "" (split-string names-string)))
4424      (let ((erc-channel-members-changed-hook nil))
4425	(dolist (item names)
4426	  (cond ((string-match "^@\\(.*\\)$" item)
4427		 (setq name (match-string 1 item)
4428		       op 'on
4429		       voice 'off))
4430		((string-match "^+\\(.*\\)$" item)
4431		 (setq name (match-string 1 item)
4432		       op 'off
4433		       voice 'on))
4434		(t (setq name item
4435			 op 'off
4436			 voice 'off)))
4437	(puthash (erc-downcase name) t
4438		 erc-channel-new-member-names)
4439	(erc-update-current-channel-member
4440	 name name t op voice)))
4441    (run-hooks 'erc-channel-members-changed-hook)))
4442
4443(defcustom erc-channel-members-changed-hook nil
4444  "*This hook is called every time the variable `channel-members' changes.
4445The buffer where the change happened is current while this hook is called."
4446  :group 'erc-hooks
4447  :type 'hook)
4448
4449(defun erc-update-user-nick (nick &optional new-nick
4450				  host login full-name info)
4451  "Updates the stored user information for the user with nickname
4452NICK.
4453
4454See also: `erc-update-user'."
4455  (erc-update-user (erc-get-server-user nick) new-nick
4456		   host login full-name info))
4457
4458(defun erc-update-user (user &optional new-nick
4459			     host login full-name info)
4460  "Update user info for USER.  USER must be an erc-server-user
4461struct.  Any of NEW-NICK, HOST, LOGIN, FULL-NAME, INFO which are
4462non-nil and not equal to the existing values for USER are used to
4463replace the stored values in USER.
4464
4465If, and only if, a change is made,
4466`erc-channel-members-changed-hook' is run for each channel for
4467which USER is a member, and t is returned."
4468  (let (changed)
4469    (when user
4470      (when (and new-nick
4471		 (not (equal (erc-server-user-nickname user)
4472			     new-nick)))
4473	(setq changed t)
4474	(erc-change-user-nickname user new-nick))
4475      (when (and host
4476		 (not (equal (erc-server-user-host user) host)))
4477	(setq changed t)
4478	(setf (erc-server-user-host user) host))
4479      (when (and login
4480		 (not (equal (erc-server-user-login user) login)))
4481	(setq changed t)
4482	(setf (erc-server-user-login user) login))
4483      (when (and full-name
4484		 (not (equal (erc-server-user-full-name user)
4485			     full-name)))
4486	(setq changed t)
4487	(setf (erc-server-user-full-name user) full-name))
4488      (when (and info
4489		 (not (equal (erc-server-user-info user) info)))
4490	(setq changed t)
4491	(setf (erc-server-user-info user) info))
4492      (if changed
4493	  (dolist (buf (erc-server-user-buffers user))
4494	    (if (buffer-live-p buf)
4495		(with-current-buffer buf
4496		  (run-hooks 'erc-channel-members-changed-hook))))))
4497    changed))
4498
4499(defun erc-update-current-channel-member
4500  (nick new-nick &optional add op voice host login full-name info
4501	update-message-time)
4502  "Updates the stored user information for the user with nickname
4503NICK.  `erc-update-user' is called to handle changes to nickname,
4504HOST, LOGIN, FULL-NAME, and INFO.  If OP or VOICE are non-nil,
4505they must be equal to either `on' or `off', in which case the
4506operator or voice status of the user in the current channel is
4507changed accordingly.  If UPDATE-MESSAGE-TIME is non-nil, the
4508last-message-time of the user in the current channel is set
4509to (current-time).
4510
4511If ADD is non-nil, the user will be added with the specified
4512information if it is not already present in the user or channel
4513lists.
4514
4515If, and only if, changes are made, or the user is added,
4516`erc-channel-members-updated-hook' is run, and t is returned.
4517
4518See also: `erc-update-user' and `erc-update-channel-member'."
4519  (let* (changed user-changed
4520	 (channel-data (erc-get-channel-user nick))
4521	 (cuser (if channel-data (cdr channel-data)))
4522	 (user (if channel-data (car channel-data)
4523		 (erc-get-server-user nick))))
4524    (if cuser
4525	(progn
4526	  (erc-log (format "update-member: user = %S, cuser = %S" user cuser))
4527	  (when (and op
4528		     (not (eq (erc-channel-user-op cuser) op)))
4529	      (setq changed t)
4530	    (setf (erc-channel-user-op cuser)
4531		  (cond ((eq op 'on) t)
4532				   ((eq op 'off) nil)
4533				   (t op))))
4534	  (when (and voice
4535		     (not (eq (erc-channel-user-voice cuser) voice)))
4536	      (setq changed t)
4537	    (setf (erc-channel-user-voice cuser)
4538		  (cond ((eq voice 'on) t)
4539				      ((eq voice 'off) nil)
4540				      (t voice))))
4541	  (when update-message-time
4542	    (setf (erc-channel-user-last-message-time cuser) (current-time)))
4543	  (setq user-changed
4544		(erc-update-user user new-nick
4545				 host login full-name info)))
4546      (when add
4547	(if (null user)
4548	    (progn
4549	      (setq user (make-erc-server-user
4550			  :nickname nick
4551			  :host host
4552			  :full-name full-name
4553			  :login login
4554			  :info info
4555			  :buffers (list (current-buffer))))
4556	      (erc-add-server-user nick user))
4557	  (setf (erc-server-user-buffers user)
4558		(cons (current-buffer)
4559		      (erc-server-user-buffers user))))
4560	(setq cuser (make-erc-channel-user
4561		     :op (cond ((eq op 'on) t)
4562				       ((eq op 'off) nil)
4563				       (t op))
4564		     :voice (cond ((eq voice 'on) t)
4565				       ((eq voice 'off) nil)
4566				       (t voice))
4567		     :last-message-time
4568		     (if update-message-time (current-time))))
4569	(puthash (erc-downcase nick) (cons user cuser)
4570		 erc-channel-users)
4571	(setq changed t)))
4572    (when (and changed (null user-changed))
4573      (run-hooks 'erc-channel-members-changed-hook))
4574    (or changed user-changed add)))
4575
4576(defun erc-update-channel-member (channel nick new-nick
4577				  &optional add op voice host login
4578				  full-name info update-message-time)
4579  "Updates user and channel information for the user with
4580nickname NICK in channel CHANNEL.
4581
4582See also: `erc-update-current-channel-member'."
4583  (erc-with-buffer
4584   (channel)
4585   (erc-update-current-channel-member nick new-nick add op voice host
4586				      login full-name info
4587				      update-message-time)))
4588
4589(defun erc-remove-current-channel-member (nick)
4590  "Remove NICK from current channel membership list.
4591Runs `erc-channel-members-changed-hook'."
4592  (let ((channel-data (erc-get-channel-user nick)))
4593    (when channel-data
4594      (erc-remove-channel-user nick)
4595      (run-hooks 'erc-channel-members-changed-hook))))
4596
4597(defun erc-remove-channel-member (channel nick)
4598  "Remove NICK from CHANNEL's membership list.
4599
4600See also `erc-remove-current-channel-member'."
4601  (erc-with-buffer
4602   (channel)
4603   (erc-remove-current-channel-member nick)))
4604
4605(defun erc-update-channel-topic (channel topic &optional modify)
4606  "Find a buffer for CHANNEL and set the TOPIC for it.
4607
4608If optional MODIFY is 'append or 'prepend, then append or prepend the
4609TOPIC string to the current topic."
4610  (erc-with-buffer (channel)
4611    (cond ((eq modify 'append)
4612	   (setq erc-channel-topic (concat erc-channel-topic topic)))
4613	  ((eq modify 'prepend)
4614	   (setq erc-channel-topic (concat topic erc-channel-topic)))
4615	  (t (setq erc-channel-topic topic)))
4616    (erc-update-mode-line-buffer (current-buffer))))
4617
4618(defun erc-set-modes (tgt mode-string)
4619  "Set the modes for the TGT provided as MODE-STRING."
4620  (let* ((modes (erc-parse-modes mode-string))
4621	 (add-modes (nth 0 modes))
4622	 (remove-modes (nth 1 modes))
4623	 ;; list of triples: (mode-char 'on/'off argument)
4624	 (arg-modes (nth 2 modes)))
4625    (cond ((erc-channel-p tgt); channel modes
4626	   (let ((buf (and erc-server-process
4627			   (erc-get-buffer tgt erc-server-process))))
4628	     (when buf
4629	       (with-current-buffer buf
4630		 (setq erc-channel-modes add-modes)
4631		 (setq erc-channel-user-limit nil)
4632		 (setq erc-channel-key nil)
4633		 (while arg-modes
4634		   (let ((mode (nth 0 (car arg-modes)))
4635			 (onoff (nth 1 (car arg-modes)))
4636			 (arg (nth 2 (car arg-modes))))
4637		     (cond ((string-match "^[Ll]" mode)
4638			    (erc-update-channel-limit tgt onoff arg))
4639			   ((string-match "^[Kk]" mode)
4640			    (erc-update-channel-key tgt onoff arg))
4641			   (t nil)))
4642		   (setq arg-modes (cdr arg-modes)))
4643		 (erc-update-mode-line-buffer buf)))))
4644	  ;; we do not keep our nick's modes yet
4645	  ;;(t (setq erc-user-modes add-modes))
4646	  )
4647    ))
4648
4649(defun erc-sort-strings (list-of-strings)
4650  "Sort LIST-OF-STRINGS in lexicographic order.
4651
4652Side-effect free."
4653  (sort (copy-sequence list-of-strings) 'string<))
4654
4655(defun erc-parse-modes (mode-string)
4656  "Parse MODE-STRING into a list.
4657
4658Returns a list of three elements:
4659
4660  (ADD-MODES REMOVE-MODES ARG-MODES).
4661
4662The add-modes and remove-modes are lists of single-character strings
4663for modes without parameters to add and remove respectively.  The
4664arg-modes is a list of triples of the form:
4665
4666  (MODE-CHAR ON/OFF ARGUMENT)."
4667  (if (string-match "^\\s-*\\(\\S-+\\)\\(\\s-.*$\\|$\\)" mode-string)
4668      (let ((chars (mapcar 'char-to-string (match-string 1 mode-string)))
4669	    ;; arguments in channel modes
4670	    (args-str (match-string 2 mode-string))
4671	    (args nil)
4672	    (add-modes nil)
4673	    (remove-modes nil)
4674	    (arg-modes nil); list of triples: (mode-char 'on/'off argument)
4675	    (add-p t))
4676	;; make the argument list
4677	(while (string-match "^\\s-*\\(\\S-+\\)\\(\\s-+.*$\\|$\\)" args-str)
4678	  (setq args (cons (match-string 1 args-str) args))
4679	  (setq args-str (match-string 2 args-str)))
4680	(setq args (nreverse args))
4681	;; collect what modes changed, and match them with arguments
4682	(while chars
4683	  (cond ((string= (car chars) "+") (setq add-p t))
4684		((string= (car chars) "-") (setq add-p nil))
4685		((string-match "^[ovbOVB]" (car chars))
4686		 (setq arg-modes (cons (list (car chars)
4687					     (if add-p 'on 'off)
4688					     (if args (car args) nil))
4689				       arg-modes))
4690		 (if args (setq args (cdr args))))
4691		((string-match "^[LlKk]" (car chars))
4692		 (setq arg-modes (cons (list (car chars)
4693					     (if add-p 'on 'off)
4694					     (if (and add-p args)
4695						 (car args) nil))
4696				       arg-modes))
4697		 (if (and add-p args) (setq args (cdr args))))
4698		(add-p (setq add-modes (cons (car chars) add-modes)))
4699		(t (setq remove-modes (cons (car chars) remove-modes))))
4700	  (setq chars (cdr chars)))
4701	(setq add-modes (nreverse add-modes))
4702	(setq remove-modes (nreverse remove-modes))
4703	(setq arg-modes (nreverse arg-modes))
4704	(list add-modes remove-modes arg-modes))
4705    nil))
4706
4707(defun erc-update-modes (tgt mode-string &optional nick host login)
4708  "Update the mode information for TGT, provided as MODE-STRING.
4709Optional arguments: NICK, HOST and LOGIN - the attributes of the
4710person who changed the modes."
4711  (let* ((modes (erc-parse-modes mode-string))
4712	 (add-modes (nth 0 modes))
4713	 (remove-modes (nth 1 modes))
4714	 ;; list of triples: (mode-char 'on/'off argument)
4715	 (arg-modes (nth 2 modes)))
4716    ;; now parse the modes changes and do the updates
4717    (cond ((erc-channel-p tgt); channel modes
4718	   (let ((buf (and erc-server-process
4719			   (erc-get-buffer tgt erc-server-process))))
4720	     (when buf
4721	       ;; FIXME! This used to have an original buffer
4722	       ;; variable, but it never switched back to the original
4723	       ;; buffer. Is this wanted behavior?
4724	       (set-buffer buf)
4725	       (if (not (boundp 'erc-channel-modes))
4726		   (setq erc-channel-modes nil))
4727	       (while remove-modes
4728		 (setq erc-channel-modes (delete (car remove-modes)
4729						 erc-channel-modes)
4730		       remove-modes (cdr remove-modes)))
4731	       (while add-modes
4732		 (setq erc-channel-modes (cons (car add-modes)
4733					       erc-channel-modes)
4734		       add-modes (cdr add-modes)))
4735	       (setq erc-channel-modes (erc-sort-strings erc-channel-modes))
4736	       (while arg-modes
4737		 (let ((mode (nth 0 (car arg-modes)))
4738		       (onoff (nth 1 (car arg-modes)))
4739		       (arg (nth 2 (car arg-modes))))
4740		   (cond ((string-match "^[oO]" mode)
4741			  (erc-update-channel-member tgt arg arg nil onoff))
4742			 ((string-match "^[Vv]" mode)
4743			  (erc-update-channel-member tgt arg arg nil nil
4744						     onoff))
4745			 ((string-match "^[Ll]" mode)
4746			  (erc-update-channel-limit tgt onoff arg))
4747			 ((string-match "^[Kk]" mode)
4748			  (erc-update-channel-key tgt onoff arg))
4749			 (t nil)); only ops are tracked now
4750		   (setq arg-modes (cdr arg-modes))))
4751	       (erc-update-mode-line buf))))
4752	  ;; nick modes - ignored at this point
4753	  (t nil))))
4754
4755(defun erc-update-channel-limit (channel onoff n)
4756  ;; FIXME: what does ONOFF actually do?  -- Lawrence 2004-01-08
4757  "Update CHANNEL's user limit to N."
4758  (if (or (not (eq onoff 'on))
4759	  (and (stringp n) (string-match "^[0-9]+$" n)))
4760      (erc-with-buffer
4761       (channel)
4762      (cond ((eq onoff 'on) (setq erc-channel-user-limit (string-to-number n)))
4763	    (t (setq erc-channel-user-limit nil))))))
4764
4765(defun erc-update-channel-key (channel onoff key)
4766  "Update CHANNEL's key to KEY if ONOFF is 'on or to nil if it's 'off."
4767  (erc-with-buffer
4768   (channel)
4769   (cond ((eq onoff 'on) (setq erc-channel-key key))
4770	 (t (setq erc-channel-key nil)))))
4771
4772(defun erc-handle-user-status-change (type nlh &optional l)
4773  "Handle changes in any user's status.
4774
4775So far, only nick change is handled.
4776
4777Generally, the TYPE argument is a symbol describing the change type, NLH is
4778a list containing the original nickname, login name and hostname for the user,
4779and L is a list containing additional TYPE-specific arguments.
4780
4781So far the following TYPE/L pairs are supported:
4782
4783       Event			TYPE		       L
4784
4785    nickname change	       'nick		    (NEW-NICK)"
4786  (erc-log (format "user-change: type: %S  nlh: %S  l: %S" type nlh l))
4787  (cond
4788   ;; nickname change
4789   ((equal type 'nick)
4790    t)
4791   (t
4792    nil)))
4793
4794(defun erc-highlight-notice (s)
4795  "Highlight notice message S and return it.
4796See also variable `erc-notice-highlight-type'."
4797  (cond
4798   ((eq erc-notice-highlight-type 'prefix)
4799    (erc-put-text-property 0 (length erc-notice-prefix)
4800			   'face 'erc-notice-face s)
4801    s)
4802   ((eq erc-notice-highlight-type 'all)
4803    (erc-put-text-property 0 (length s) 'face 'erc-notice-face s)
4804    s)
4805   (t s)))
4806
4807(defun erc-make-notice (message)
4808  "Notify the user of MESSAGE."
4809  (when erc-minibuffer-notice
4810    (message "%s" message))
4811  (erc-highlight-notice (concat erc-notice-prefix message)))
4812
4813(defun erc-highlight-error (s)
4814  "Highlight error message S and return it."
4815  (erc-put-text-property 0 (length s) 'face 'erc-error-face s)
4816  s)
4817
4818(defun erc-put-text-property (start end property value &optional object)
4819  "Set text-property for an object (usually a string).
4820START and END define the characters covered.
4821PROPERTY is the text-property set, usually the symbol `face'.
4822VALUE is the value for the text-property, usually a face symbol such as
4823the face `bold' or `erc-pal-face'.
4824OBJECT is a string which will be modified and returned.
4825OBJECT is modified without being copied first.
4826
4827You can redefine or `defadvice' this function in order to add
4828EmacsSpeak support."
4829  (put-text-property start end property value object))
4830
4831(defun erc-list (thing)
4832  "Return THING if THING is a list, or a list with THING as its element."
4833  (if (listp thing)
4834      thing
4835    (list thing)))
4836
4837(defun erc-parse-user (string)
4838  "Parse STRING as a user specification (nick!login@host).
4839
4840Return a list of the three separate tokens."
4841  (cond
4842   ((string-match "^\\([^!\n]*\\)!\\([^@\n]*\\)@\\(.*\\)$" string)
4843    (list (match-string 1 string)
4844	  (match-string 2 string)
4845	  (match-string 3 string)))
4846   ;; Some bogus bouncers send Nick!(null), try to live with that.
4847   ((string-match "^\\([^!\n]*\\)!\\(.*\\)$" string)
4848    (list (match-string 1 string)
4849	  ""
4850	  (match-string 2 string)))
4851   (t
4852    (list string "" ""))))
4853
4854(defun erc-extract-nick (string)
4855  "Return the nick corresponding to a user specification STRING.
4856
4857See also `erc-parse-user'."
4858  (car (erc-parse-user string)))
4859
4860(defun erc-put-text-properties (start end properties
4861				&optional object value-list)
4862  "Set text-properties for OBJECT.
4863
4864START and END describe positions in OBJECT.
4865If VALUE-LIST is nil, set each property in PROPERTIES to t, else set
4866each property to the corresponding value in VALUE-LIST."
4867  (unless value-list
4868    (setq value-list (mapcar (lambda (x)
4869			       t)
4870			     properties)))
4871  (mapcar* (lambda (prop value)
4872	     (erc-put-text-property start end prop value object))
4873	   properties value-list))
4874
4875;;; Input area handling:
4876
4877(defun erc-beg-of-input-line ()
4878  "Return the value of `point' at the beginning of the input line.
4879
4880Specifically, return the position of `erc-insert-marker'."
4881  (or (and (boundp 'erc-insert-marker)
4882	   (markerp erc-insert-marker))
4883      (error "erc-insert-marker has no value, please report a bug"))
4884  (marker-position erc-insert-marker))
4885
4886(defun erc-end-of-input-line ()
4887  "Return the value of `point' at the end of the input line."
4888  (point-max))
4889
4890(defun erc-send-current-line ()
4891  "Parse current line and send it to IRC."
4892  (interactive)
4893  (save-restriction
4894    (widen)
4895    (cond
4896     ((< (point) (erc-beg-of-input-line))
4897      (message "Point is not in the input area")
4898      (beep))
4899     ((not (erc-server-buffer-live-p))
4900      (message "ERC: No process running")
4901      (beep))
4902     (t
4903      (erc-set-active-buffer (current-buffer))
4904      (let ((inhibit-read-only t)
4905	    (str (erc-user-input))
4906	    (old-buf (current-buffer)))
4907
4908	;; Kill the input and the prompt
4909	(delete-region (erc-beg-of-input-line)
4910		       (erc-end-of-input-line))
4911
4912	(unwind-protect
4913	    (erc-send-input str)
4914	  ;; Fix the buffer if the command didn't kill it
4915	  (when (buffer-live-p old-buf)
4916	    (with-current-buffer old-buf
4917	      (save-restriction
4918		(widen)
4919		(goto-char (point-max))
4920		(set-marker (process-mark erc-server-process) (point))
4921		(set-marker erc-insert-marker (point))
4922		(let ((buffer-modified (buffer-modified-p)))
4923		  (erc-display-prompt)
4924		  (set-buffer-modified-p buffer-modified))))))
4925
4926	;; Only when last hook has been run...
4927	(run-hook-with-args 'erc-send-completed-hook str))))))
4928
4929(defun erc-user-input ()
4930  "Return the input of the user in the current buffer."
4931  (buffer-substring
4932   erc-input-marker
4933   (erc-end-of-input-line)))
4934
4935(defvar erc-command-regexp "^/\\([A-Za-z]+\\)\\(\\s-+.*\\|\\s-*\\)$"
4936  "Regular expression used for matching commands in ERC.")
4937
4938(defun erc-send-input (input)
4939  "Treat INPUT as typed in by the user. It is assumed that the input
4940and the prompt is already deleted.
4941This returns non-nil only iff we actually send anything."
4942  ;; Handle different kinds of inputs
4943  (cond
4944   ;; Ignore empty input
4945   ((if erc-send-whitespace-lines
4946	(string= input "")
4947      (string-match "\\`[ \t\r\f\n]*\\'" input))
4948    (when erc-warn-about-blank-lines
4949      (message "Blank line - ignoring...")
4950      (beep))
4951    nil)
4952   (t
4953    (let ((str input)
4954	  (erc-insert-this t))
4955      (setq erc-send-this t)
4956      (run-hook-with-args 'erc-send-pre-hook input)
4957      (when erc-send-this
4958	(if (or (string-match "\n" str)
4959		(not (string-match erc-command-regexp str)))
4960	    (mapc
4961	     (lambda (line)
4962	       (mapc
4963		(lambda (line)
4964		  ;; Insert what has to be inserted for this.
4965		  (erc-display-msg line)
4966		  (erc-process-input-line (concat line "\n")
4967					  (null erc-flood-protect) t))
4968		(or (and erc-flood-protect (erc-split-line line))
4969		    (list line))))
4970	     (split-string str "\n"))
4971	  ;; Insert the prompt along with the command.
4972	  (erc-display-command str)
4973	  (erc-process-input-line (concat str "\n") t nil))
4974	t)))))
4975
4976(defun erc-display-command (line)
4977  (when erc-insert-this
4978    (let ((insert-position (point)))
4979      (unless erc-hide-prompt
4980	(erc-display-prompt nil nil (erc-command-indicator)
4981			    (and (erc-command-indicator)
4982				 'erc-command-indicator-face)))
4983      (let ((beg (point)))
4984	(insert line)
4985	(erc-put-text-property beg (point)
4986			       'face 'erc-command-indicator-face)
4987	(insert "\n"))
4988      (set-marker (process-mark erc-server-process) (point))
4989      (set-marker erc-insert-marker (point))
4990      (save-excursion
4991	(save-restriction
4992	  (narrow-to-region insert-position (point))
4993	  (run-hooks 'erc-send-modify-hook)
4994	  (run-hooks 'erc-send-post-hook))))))
4995
4996(defun erc-display-msg (line)
4997  "Display LINE as a message of the user to the current target at the
4998current position."
4999  (when erc-insert-this
5000    (let ((insert-position (point)))
5001      (insert (erc-format-my-nick))
5002      (let ((beg (point)))
5003	(insert line)
5004	(erc-put-text-property beg (point)
5005			       'face 'erc-input-face))
5006      (insert "\n")
5007      (set-marker (process-mark erc-server-process) (point))
5008      (set-marker erc-insert-marker (point))
5009      (save-excursion
5010	(save-restriction
5011	  (narrow-to-region insert-position (point))
5012	  (run-hooks 'erc-send-modify-hook)
5013	  (run-hooks 'erc-send-post-hook))))))
5014
5015(defun erc-command-symbol (command)
5016  "Return the ERC command symbol for COMMAND if it exists and is bound."
5017  (let ((cmd (intern-soft (format "erc-cmd-%s" (upcase command)))))
5018    (when (fboundp cmd) cmd)))
5019
5020(defun erc-extract-command-from-line (line)
5021  "Extract command and args from the input LINE.
5022If no command was given, return nil.  If command matches, return a
5023list of the form: (command args) where both elements are strings."
5024  (when (string-match erc-command-regexp line)
5025    (let* ((cmd (erc-command-symbol (match-string 1 line)))
5026	   ;; note: return is nil, we apply this simply for side effects
5027	   (canon-defun (while (and cmd (symbolp (symbol-function cmd)))
5028			  (setq cmd (symbol-function cmd))))
5029	   (cmd-fun (or cmd #'erc-cmd-default))
5030	   (arg (if cmd
5031		    (if (get cmd-fun 'do-not-parse-args)
5032			(format "%s" (match-string 2 line))
5033		      (delete "" (split-string (erc-trim-string
5034						(match-string 2 line)) " ")))
5035		  line)))
5036      (list cmd-fun arg))))
5037
5038(defun erc-split-multiline-safe (string)
5039  "Split STRING, containing multiple lines and return them in a list.
5040Do it only for STRING as the complete input, do not carry unfinished
5041strings over to the next call."
5042  (let ((l ())
5043	(i0 0)
5044	(doit t))
5045    (while doit
5046      (let ((i (string-match "\r?\n" string i0))
5047	    (s (substring string i0)))
5048	(cond (i (setq l (cons (substring string i0 i) l))
5049		 (setq i0 (match-end 0)))
5050	      ((> (length s) 0)
5051		 (setq l (cons s l))(setq doit nil))
5052	      (t (setq doit nil)))))
5053    (nreverse l)))
5054
5055;; nick handling
5056
5057(defun erc-set-current-nick (nick)
5058  "Set the current nickname to NICK."
5059  (with-current-buffer (if (buffer-live-p (erc-server-buffer))
5060			   (erc-server-buffer)
5061			 (current-buffer))
5062    (setq erc-server-current-nick nick)))
5063
5064(defun erc-current-nick ()
5065  "Return the current nickname."
5066  (with-current-buffer (if (buffer-live-p (erc-server-buffer))
5067			   (erc-server-buffer)
5068			 (current-buffer))
5069    erc-server-current-nick))
5070
5071(defun erc-current-nick-p (nick)
5072  "Return non-nil if NICK is the current nickname."
5073  (erc-nick-equal-p nick (erc-current-nick)))
5074
5075(defun erc-nick-equal-p (nick1 nick2)
5076  "Return non-nil if NICK1 and NICK2 are the same.
5077
5078This matches strings according to the IRC protocol's case convention.
5079
5080See also `erc-downcase'."
5081  (string= (erc-downcase nick1)
5082	   (erc-downcase nick2)))
5083
5084;; default target handling
5085
5086(defun erc-default-target ()
5087  "Return the current default target (as a character string) or nil if none."
5088  (let ((tgt (car erc-default-recipients)))
5089    (cond
5090     ((not tgt) nil)
5091     ((listp tgt) (cdr tgt))
5092     (t tgt))))
5093
5094(defun erc-add-default-channel (channel)
5095  "Add CHANNEL to the default channel list."
5096
5097  (let ((d1 (car erc-default-recipients))
5098	(d2 (cdr erc-default-recipients))
5099	(chl (downcase channel)))
5100      (setq erc-default-recipients
5101	    (cons chl erc-default-recipients))))
5102
5103(defun erc-delete-default-channel (channel &optional buffer)
5104  "Delete CHANNEL from the default channel list."
5105  (let ((ob (current-buffer)))
5106    (with-current-buffer (if (and buffer
5107				  (bufferp buffer))
5108			     buffer
5109			   (current-buffer))
5110      (setq erc-default-recipients (delete (downcase channel)
5111					   erc-default-recipients)))))
5112
5113(defun erc-add-query (nickname)
5114  "Add QUERY'd NICKNAME to the default channel list.
5115
5116The previous default target of QUERY type gets removed."
5117  (let ((d1 (car erc-default-recipients))
5118	(d2 (cdr erc-default-recipients))
5119	(qt (cons 'QUERY (downcase nickname))))
5120    (if (and (listp d1)
5121	     (eq (car d1) 'QUERY))
5122	(setq erc-default-recipients (cons qt d2))
5123      (setq erc-default-recipients (cons qt erc-default-recipients)))))
5124
5125(defun erc-delete-query ()
5126  "Delete the topmost target if it is a QUERY."
5127
5128  (let ((d1 (car erc-default-recipients))
5129	(d2 (cdr erc-default-recipients)))
5130    (if (and (listp d1)
5131	     (eq (car d1) 'QUERY))
5132	(setq erc-default-recipients d2)
5133      (error "Current target is not a QUERY"))))
5134
5135(defun erc-ignored-user-p (spec)
5136  "Return non-nil if SPEC matches something in `erc-ignore-list'.
5137
5138Takes a full SPEC of a user in the form \"nick!login@host\", and
5139matches against all the regexp's in `erc-ignore-list'.  If any
5140match, returns that regexp."
5141  (catch 'found
5142    (dolist (ignored (erc-with-server-buffer erc-ignore-list))
5143      (if (string-match ignored spec)
5144	  (throw 'found ignored)))))
5145
5146(defun erc-ignored-reply-p (msg tgt proc)
5147  ;; FIXME: this docstring needs fixing -- Lawrence 2004-01-08
5148  "Return non-nil if MSG matches something in `erc-ignore-reply-list'.
5149
5150Takes a message MSG to a channel and returns non-nil if the addressed
5151user matches any regexp in `erc-ignore-reply-list'."
5152  (let ((target-nick (erc-message-target msg)))
5153    (if (not target-nick)
5154	nil
5155      (erc-with-buffer (tgt proc)
5156	(let ((user (erc-get-server-user target-nick)))
5157	  (when user
5158	    (erc-list-match erc-ignore-reply-list
5159			    (erc-user-spec user))))))))
5160
5161(defun erc-message-target (msg)
5162  "Return the addressed target in MSG.
5163
5164The addressed target is the string before the first colon in MSG."
5165  (if (string-match "^\\([^: \n]*\\):" msg)
5166      (match-string 1 msg)
5167    nil))
5168
5169(defun erc-user-spec (user)
5170  "Create a nick!user@host spec from a user struct."
5171  (let ((nick (erc-server-user-nickname user))
5172	(host (erc-server-user-host user))
5173	(login (erc-server-user-login user)))
5174  (concat (if nick
5175	      nick
5176	    "")
5177	  "!"
5178	  (if login
5179	      login
5180	    "")
5181	  "@"
5182	  (if host
5183	      host
5184	    ""))))
5185
5186(defun erc-list-match (lst str)
5187  "Return non-nil if any regexp in LST matches STR."
5188  (memq nil (mapcar (lambda (regexp)
5189		      (not (string-match regexp str)))
5190		    lst)))
5191
5192;; other "toggles"
5193
5194(defun erc-toggle-ctcp-autoresponse (&optional arg)
5195  "Toggle automatic CTCP replies (like VERSION and PING).
5196
5197If ARG is positive, turns CTCP replies on.
5198
5199If ARG is non-nil and not positive, turns CTCP replies off."
5200  (interactive "P")
5201  (cond ((and (numberp arg) (> arg 0))
5202	 (setq erc-disable-ctcp-replies t))
5203	(arg (setq erc-disable-ctcp-replies nil))
5204	(t (setq erc-disable-ctcp-replies (not erc-disable-ctcp-replies))))
5205  (message "ERC CTCP replies are %s" (if erc-disable-ctcp-replies "OFF" "ON")))
5206
5207(defun erc-toggle-flood-control (&optional arg)
5208  "Toggle use of flood control on sent messages.
5209
5210If ARG is positive, use flood control.
5211If ARG is non-nil and not positive, do not use flood control.
5212
5213See `erc-server-flood-margin' for an explanation of the available
5214flood control parameters."
5215  (interactive "P")
5216  (cond ((and (numberp arg) (> arg 0))
5217	 (setq erc-flood-protect t))
5218	(arg (setq erc-flood-protect nil))
5219	(t (setq erc-flood-protect (not erc-flood-protect))))
5220  (message "ERC flood control is %s"
5221	   (cond (erc-flood-protect "ON")
5222		 (t "OFF"))))
5223
5224;; Some useful channel and nick commands for fast key bindings
5225
5226(defun erc-invite-only-mode (&optional arg)
5227  "Turn on the invite only mode (+i) for the current channel.
5228
5229If ARG is non-nil, turn this mode off (-i).
5230
5231This command is sent even if excess flood is detected."
5232  (interactive "P")
5233  (erc-set-active-buffer (current-buffer))
5234  (let ((tgt (erc-default-target))
5235	(erc-force-send t))
5236    (cond ((or (not tgt) (not (erc-channel-p tgt)))
5237	   (erc-display-message nil 'error (current-buffer) 'no-target))
5238	  (arg (erc-load-irc-script-lines (list (concat "/mode " tgt " -i"))
5239					  t))
5240	  (t (erc-load-irc-script-lines (list (concat "/mode " tgt " +i"))
5241					t)))))
5242
5243(defun erc-get-channel-mode-from-keypress (key)
5244  "Read a key sequence and call the corresponding channel mode function.
5245After doing C-c C-o, type in a channel mode letter.
5246
5247C-g means quit.
5248RET lets you type more than one mode at a time.
5249If \"l\" is pressed, `erc-set-channel-limit' gets called.
5250If \"k\" is pressed, `erc-set-channel-key' gets called.
5251Anything else will be sent to `erc-toggle-channel-mode'."
5252  (interactive "kChannel mode (RET to set more than one): ")
5253  (when (featurep 'xemacs)
5254    (setq key (char-to-string (event-to-character (aref key 0)))))
5255  (cond ((equal key "\C-g")
5256	 (keyboard-quit))
5257	((equal key "\C-m")
5258	 (erc-insert-mode-command))
5259	((equal key "l")
5260	 (call-interactively 'erc-set-channel-limit))
5261	((equal key "k")
5262	 (call-interactively 'erc-set-channel-key))
5263	(t (erc-toggle-channel-mode key))))
5264
5265(defun erc-toggle-channel-mode (mode &optional channel)
5266  "Toggle channel MODE.
5267
5268If CHANNEL is non-nil, toggle MODE for that channel, otherwise use
5269`erc-default-target'."
5270  (interactive "P")
5271  (erc-set-active-buffer (current-buffer))
5272  (let ((tgt (or channel (erc-default-target)))
5273	(erc-force-send t))
5274    (cond ((or (null tgt) (null (erc-channel-p tgt)))
5275	   (erc-display-message nil 'error 'active 'no-target))
5276	  ((member mode erc-channel-modes)
5277	   (erc-log (format "%s: Toggle mode %s OFF" tgt mode))
5278	   (message "Toggle channel mode %s OFF" mode)
5279	   (erc-server-send (format "MODE %s -%s" tgt mode)))
5280	  (t (erc-log (format "%s: Toggle channel mode %s ON" tgt mode))
5281	     (message "Toggle channel mode %s ON" mode)
5282	     (erc-server-send (format "MODE %s +%s" tgt mode))))))
5283
5284(defun erc-insert-mode-command ()
5285  "Insert the line \"/mode <current target> \" at `point'."
5286  (interactive)
5287  (let ((tgt (erc-default-target)))
5288    (if tgt (insert (concat "/mode " tgt " "))
5289      (erc-display-message nil 'error (current-buffer) 'no-target))))
5290
5291(defun erc-channel-names ()
5292  "Run \"/names #channel\" in the current channel."
5293  (interactive)
5294  (erc-set-active-buffer (current-buffer))
5295  (let ((tgt (erc-default-target)))
5296    (if tgt (erc-load-irc-script-lines (list (concat "/names " tgt)))
5297      (erc-display-message nil 'error (current-buffer) 'no-target))))
5298
5299(defun erc-remove-text-properties-region (start end &optional object)
5300  "Clears the region (START,END) in OBJECT from all colors, etc."
5301  (interactive "r")
5302  (save-excursion
5303    (let ((inhibit-read-only t))
5304      (set-text-properties start end nil object))))
5305
5306;; script execution and startup
5307
5308(defun erc-find-file (file &optional path)
5309  "Search for a FILE in the filesystem.
5310First the `default-directory' is searched for FILE, then any directories
5311specified in the list PATH.
5312
5313If FILE is found, return the path to it."
5314  (let ((filepath file))
5315    (if (file-readable-p filepath) filepath
5316      (progn
5317	(while (and path
5318		    (progn (setq filepath (expand-file-name file (car path)))
5319			   (not (file-readable-p filepath))))
5320	  (setq path (cdr path)))
5321	(if path filepath nil)))))
5322
5323(defun erc-select-startup-file ()
5324  "Select an ERC startup file.
5325See also `erc-startup-file-list'."
5326  (catch 'found
5327    (dolist (f erc-startup-file-list)
5328      (setq f (convert-standard-filename f))
5329      (when (file-readable-p f)
5330	(throw 'found f)))))
5331
5332(defun erc-find-script-file (file)
5333  "Search for FILE in `default-directory', and any in `erc-script-path'."
5334  (erc-find-file file erc-script-path))
5335
5336(defun erc-load-script (file)
5337  "Load a script from FILE.
5338
5339FILE must be the full name, it is not searched in the
5340`erc-script-path'.  If the filename ends with `.el', then load it
5341as an Emacs Lisp program.  Otherwise, treat it as a regular IRC
5342script."
5343  (erc-log (concat "erc-load-script: " file))
5344  (cond
5345   ((string-match "\\.el$" file)
5346    (load file))
5347   (t
5348    (erc-load-irc-script file))))
5349
5350(defun erc-process-script-line (line &optional args)
5351  "Process an IRC script LINE.
5352
5353Does script-specific substitutions (script arguments, current nick,
5354server, etc.) in LINE and returns it.
5355
5356Substitutions are: %C and %c = current target (channel or nick),
5357%S %s = current server, %N %n = my current nick, and %x is x verbatim,
5358where x is any other character;
5359$* = the entire argument string, $1 = the first argument, $2 = the second,
5360and so on."
5361  (if (not args) (setq args ""))
5362  (let* ((arg-esc-regexp "\\(\\$\\(\\*\\|[1-9][0-9]*\\)\\)\\([^0-9]\\|$\\)")
5363	 (percent-regexp "\\(%.\\)")
5364	 (esc-regexp (concat arg-esc-regexp "\\|" percent-regexp))
5365	 (tgt (erc-default-target))
5366	 (server (and (boundp 'erc-session-server) erc-session-server))
5367	 (nick (erc-current-nick))
5368	 (res "")
5369	 (tmp nil)
5370	 (arg-list nil)
5371	 (arg-num 0))
5372    (if (not tgt) (setq tgt ""))
5373    (if (not server) (setq server ""))
5374    (if (not nick) (setq nick ""))
5375    ;; First, compute the argument list
5376    (setq tmp args)
5377    (while (string-match "^\\s-*\\(\\S-+\\)\\(\\s-+.*$\\|$\\)" tmp)
5378      (setq arg-list (cons (match-string 1 tmp) arg-list))
5379      (setq tmp (match-string 2 tmp)))
5380    (setq arg-list (nreverse arg-list))
5381    (setq arg-num (length arg-list))
5382    ;; now do the substitution
5383    (setq tmp (string-match esc-regexp line))
5384    (while tmp
5385      ;;(message "beginning of while: tmp=%S" tmp)
5386      (let* ((hd (substring line 0 tmp))
5387	     (esc "")
5388	     (subst "")
5389	     (tail (substring line tmp)))
5390	(cond ((string-match (concat "^" arg-esc-regexp) tail)
5391	       (setq esc (match-string 1 tail))
5392	       (setq tail (substring tail (match-end 1))))
5393	      ((string-match (concat "^" percent-regexp) tail)
5394	       (setq esc (match-string 1 tail))
5395	       (setq tail (substring tail (match-end 1)))))
5396	;;(message "hd=%S, esc=%S, tail=%S, arg-num=%S" hd esc tail arg-num)
5397	(setq res (concat res hd))
5398	(setq subst
5399	      (cond ((string= esc "") "")
5400		    ((string-match "^\\$\\*$" esc) args)
5401		    ((string-match "^\\$\\([0-9]+\\)$" esc)
5402		     (let ((n (string-to-number (match-string 1 esc))))
5403		       (message "n = %S, integerp(n)=%S" n (integerp n))
5404		       (if (<= n arg-num) (nth (1- n) arg-list) "")))
5405		    ((string-match "^%[Cc]$" esc) tgt)
5406		    ((string-match "^%[Ss]$" esc) server)
5407		    ((string-match "^%[Nn]$" esc) nick)
5408		    ((string-match "^%\\(.\\)$" esc) (match-string 1 esc))
5409		    (t (erc-log (format "BUG in erc-process-script-line: bad escape sequence: %S\n" esc))
5410		       (message "BUG IN ERC: esc=%S" esc)
5411		       "")))
5412	(setq line tail)
5413	(setq tmp (string-match esc-regexp line))
5414	(setq res (concat res subst))
5415	;;(message "end of while: line=%S, res=%S, tmp=%S" line res tmp)
5416	))
5417    (setq res (concat res line))
5418    res))
5419
5420(defun erc-load-irc-script (file &optional force)
5421  "Load an IRC script from FILE."
5422  (erc-log (concat "erc-load-script: " file))
5423  (let ((str (with-temp-buffer
5424	       (insert-file-contents file)
5425	       (buffer-string))))
5426    (erc-load-irc-script-lines (erc-split-multiline-safe str) force)))
5427
5428(defun erc-load-irc-script-lines (lines &optional force noexpand)
5429  "Load IRC script LINES (a list of strings).
5430
5431If optional NOEXPAND is non-nil, do not expand script-specific
5432sequences, process the lines verbatim.  Use this for multiline
5433user input."
5434  (let* ((cb (current-buffer))
5435	 (pnt (point))
5436	 (s "")
5437	 (sp (or (erc-command-indicator) (erc-prompt)))
5438	 (args (and (boundp 'erc-script-args) erc-script-args)))
5439    (if (and args (string-match "^ " args))
5440	(setq args (substring args 1)))
5441    ;; prepare the prompt string for echo
5442    (erc-put-text-property 0 (length sp)
5443			   'face 'erc-command-indicator-face sp)
5444    (while lines
5445      (setq s (car lines))
5446      (erc-log (concat "erc-load-script: CMD: " s))
5447      (unless (string-match "^\\s-*$" s)
5448	(let ((line (if noexpand s (erc-process-script-line s args))))
5449	  (if (and (erc-process-input-line line force)
5450		   erc-script-echo)
5451	      (progn
5452		(erc-put-text-property 0 (length line)
5453				       'face 'erc-input-face line)
5454		(erc-display-line (concat sp line) cb)))))
5455      (setq lines (cdr lines)))))
5456
5457;; authentication
5458
5459(defun erc-login ()
5460  "Perform user authentication at the IRC server."
5461  (erc-log (format "login: nick: %s, user: %s %s %s :%s"
5462		   (erc-current-nick)
5463		   (user-login-name)
5464		   (or erc-system-name (system-name))
5465		   erc-session-server
5466		   erc-session-user-full-name))
5467  (if erc-session-password
5468      (erc-server-send (format "PASS %s" erc-session-password))
5469    (message "Logging in without password"))
5470  (erc-server-send (format "NICK %s" (erc-current-nick)))
5471  (erc-server-send
5472   (format "USER %s %s %s :%s"
5473	   ;; hacked - S.B.
5474	   (if erc-anonymous-login erc-email-userid (user-login-name))
5475	   "0" "*"
5476	   erc-session-user-full-name))
5477  (erc-update-mode-line))
5478
5479;; connection properties' heuristics
5480
5481(defun erc-determine-parameters (&optional server port nick name)
5482  "Determine the connection and authentication parameters.
5483Sets the buffer local variables:
5484
5485- `erc-session-server'
5486- `erc-session-port'
5487- `erc-session-full-name'
5488- `erc-server-current-nick'"
5489  (setq erc-session-server (erc-compute-server server)
5490	erc-session-port (or port erc-default-port)
5491	erc-session-user-full-name (erc-compute-full-name name))
5492  (erc-set-current-nick (erc-compute-nick nick)))
5493
5494(defun erc-compute-server (&optional server)
5495  "Return an IRC server name.
5496
5497This tries a number of increasingly more default methods until a
5498non-nil value is found.
5499
5500- SERVER (the argument passed to this function)
5501- The `erc-server' option
5502- The value of the IRCSERVER environment variable
5503- The `erc-default-server' variable"
5504  (or server
5505      erc-server
5506      (getenv "IRCSERVER")
5507      erc-default-server))
5508
5509(defun erc-compute-nick (&optional nick)
5510  "Return user's IRC nick.
5511
5512This tries a number of increasingly more default methods until a
5513non-nil value is found.
5514
5515- NICK (the argument passed to this function)
5516- The `erc-nick' option
5517- The value of the IRCNICK environment variable
5518- The result from the `user-login-name' function"
5519  (or nick
5520      (if (consp erc-nick) (car erc-nick) erc-nick)
5521      (getenv "IRCNICK")
5522      (user-login-name)))
5523
5524
5525(defun erc-compute-full-name (&optional full-name)
5526  "Return user's full name.
5527
5528This tries a number of increasingly more default methods until a
5529non-nil value is found.
5530
5531- FULL-NAME (the argument passed to this function)
5532- The `erc-user-full-name' option
5533- The value of the IRCNAME environment variable
5534- The result from the `user-full-name' function"
5535  (or full-name
5536      erc-user-full-name
5537      (getenv "IRCNAME")
5538      (if erc-anonymous-login "unknown" nil)
5539      (user-full-name)))
5540
5541(defun erc-compute-port (&optional port)
5542  "Return a port for an IRC server.
5543
5544This tries a number of increasingly more default methods until a
5545non-nil value is found.
5546
5547- PORT (the argument passed to this function)
5548- The `erc-port' option
5549- The `erc-default-port' variable"
5550  (or port erc-port erc-default-port))
5551
5552;; time routines
5553
5554(defun erc-string-to-emacs-time (string)
5555  "Convert the long number represented by STRING into an Emacs format.
5556Returns a list of the form (HIGH LOW), compatible with Emacs time format."
5557  (let* ((n (string-to-number (concat string ".0"))))
5558    (list (truncate (/ n 65536))
5559	  (truncate (mod n 65536)))))
5560
5561(defun erc-emacs-time-to-erc-time (time)
5562  "Convert Emacs TIME to a number of seconds since the epoch."
5563  (when time
5564    (+ (* (nth 0 time) 65536.0) (nth 1 time))))
5565;  (round (+ (* (nth 0 tm) 65536.0) (nth 1 tm))))
5566
5567(defun erc-current-time ()
5568  "Return the `current-time' as a number of seconds since the epoch.
5569
5570See also `erc-emacs-time-to-erc-time'."
5571  (erc-emacs-time-to-erc-time (current-time)))
5572
5573(defun erc-time-diff (t1 t2)
5574  "Return the time difference in seconds between T1 and T2."
5575  (abs (- t2 t1)))
5576
5577(defun erc-time-gt (t1 t2)
5578  "Check whether T1 > T2."
5579  (> t1 t2))
5580
5581(defun erc-sec-to-time (ns)
5582  "Convert NS to a time string HH:MM.SS."
5583  (setq ns (truncate ns))
5584  (format "%02d:%02d.%02d"
5585	  (/ ns 3600)
5586	  (/ (% ns 3600) 60)
5587	  (% ns 60)))
5588
5589(defun erc-seconds-to-string (seconds)
5590  "Convert a number of SECONDS into an English phrase."
5591  (let (days hours minutes format-args output)
5592    (setq days		(/ seconds 86400)
5593	  seconds	(% seconds 86400)
5594	  hours		(/ seconds 3600)
5595	  seconds	(% seconds 3600)
5596	  minutes	(/ seconds 60)
5597	  seconds	(% seconds 60)
5598	  format-args	(if (> days 0)
5599			    `("%d days, %d hours, %d minutes, %d seconds"
5600			      ,days ,hours ,minutes ,seconds)
5601			  (if (> hours 0)
5602			      `("%d hours, %d minutes, %d seconds"
5603				,hours ,minutes ,seconds)
5604			    (if (> minutes 0)
5605				`("%d minutes, %d seconds" ,minutes ,seconds)
5606			      `("%d seconds" ,seconds))))
5607	  output	(apply 'format format-args))
5608    ;; Change all "1 units" to "1 unit".
5609    (while (string-match "\\([^0-9]\\|^\\)1 \\S-+\\(s\\)" output)
5610      (setq output (erc-replace-match-subexpression-in-string
5611		    "" output (match-string 2 output) 2 (match-beginning 2))))
5612    output))
5613
5614
5615;; info
5616
5617(defconst erc-clientinfo-alist
5618  '(("ACTION" . "is used to inform about one's current activity")
5619    ("CLIENTINFO" . "gives help on CTCP commands supported by client")
5620    ("ECHO" . "echoes its arguments back")
5621    ("FINGER" . "shows user's name, location, and idle time")
5622    ("PING" . "measures delay between peers")
5623    ("TIME" . "shows client-side time")
5624    ("USERINFO" . "shows information provided by a user")
5625    ("VERSION" . "shows client type and version"))
5626  "Alist of CTCP CLIENTINFO for ERC commands.")
5627
5628(defun erc-client-info (s)
5629  "Return CTCP CLIENTINFO on command S.
5630If S is nil or an empty string then return general CLIENTINFO."
5631  (if (or (not s) (string= s ""))
5632      (concat
5633       (apply #'concat
5634	      (mapcar (lambda (e)
5635			(concat (car e) " "))
5636		      erc-clientinfo-alist))
5637       ": use CLIENTINFO <COMMAND> to get more specific information")
5638    (let ((h (assoc (upcase s) erc-clientinfo-alist)))
5639      (if h
5640	  (concat s " " (cdr h))
5641	(concat s ": unknown command")))))
5642
5643;; Hook functions
5644
5645(defun erc-directory-writable-p (dir)
5646  "Determine whether DIR is a writable directory.
5647If it doesn't exist, create it."
5648  (unless (file-attributes dir) (make-directory dir))
5649  (or (file-accessible-directory-p dir) (error "Cannot access %s" dir)))
5650
5651(defun erc-kill-query-buffers (process)
5652  "Kill all buffers of PROCESS."
5653  ;; here, we only want to match the channel buffers, to avoid
5654  ;; "selecting killed buffers" b0rkage.
5655  (erc-with-all-buffers-of-server process
5656				  (lambda ()
5657				    (not (erc-server-buffer-p)))
5658				  (kill-buffer (current-buffer))))
5659
5660(defun erc-nick-at-point ()
5661  "Give information about the nickname at `point'.
5662
5663If called interactively, give a human readable message in the
5664minibuffer.  If called programatically, return the corresponding
5665entry of `channel-members'."
5666  (interactive)
5667  (require 'thingatpt)
5668  (let* ((word (word-at-point))
5669	 (channel-data (erc-get-channel-user word))
5670	 (cuser (cdr channel-data))
5671	 (user (if channel-data
5672		   (car channel-data)
5673		 (erc-get-server-user word)))
5674	 host login full-name info nick op voice)
5675    (when user
5676      (setq nick (erc-server-user-nickname user)
5677	    host (erc-server-user-host user)
5678	    login (erc-server-user-login user)
5679	    full-name (erc-server-user-full-name user)
5680	    info (erc-server-user-info user))
5681      (if cuser
5682	  (setq op (erc-channel-user-op cuser)
5683		voice (erc-channel-user-voice cuser)))
5684      (if (interactive-p)
5685	  (message "%s is %s@%s%s%s"
5686		   nick login host
5687		   (if full-name (format " (%s)" full-name) "")
5688		   (if (or op voice)
5689			       (format " and is +%s%s on %s"
5690			       (if op "o" "")
5691			       (if voice "v" "")
5692				       (erc-default-target))
5693			     ""))
5694	user))))
5695
5696(defun erc-away-time ()
5697  "Return non-nil if the current ERC process is set away.
5698
5699In particular, the time that we were set away is returned.
5700See `current-time' for details on the time format."
5701  (erc-with-server-buffer erc-away))
5702
5703;; Mode line handling
5704
5705(defcustom erc-mode-line-format "%s %a"
5706  "A string to be formatted and shown in the mode-line in `erc-mode'.
5707
5708The string is formatted using `format-spec' and the result is set as the value
5709of `mode-line-buffer-identification'.
5710
5711The following characters are replaced:
5712%a: String indicating away status or \"\" if you are not away
5713%l: The estimated lag time to the server
5714%m: The modes of the channel
5715%n: The current nick name
5716%o: The topic of the channel
5717%p: The session port
5718%t: The name of the target (channel, nickname, or servername:port)
5719%s: In the server-buffer, this gets filled with the value of
5720    `erc-server-announced-name', in a channel, the value of
5721    (erc-default-target) also get concatenated."
5722  :group 'erc-mode-line-and-header
5723  :type 'string)
5724
5725(defcustom erc-header-line-format "%n on %t (%m,%l) %o"
5726  "A string to be formatted and shown in the header-line in `erc-mode'.
5727Only used starting in Emacs 21.
5728
5729Set this to nil if you do not want the header line to be
5730displayed.
5731
5732See `erc-mode-line-format' for which characters are can be used."
5733  :group 'erc-mode-line-and-header
5734  :set (lambda (sym val)
5735	 (set sym val)
5736	 (when (fboundp 'erc-update-mode-line)
5737	   (erc-update-mode-line nil)))
5738  :type '(choice (const :tag "Disabled" nil)
5739		 string))
5740
5741(defcustom erc-header-line-uses-help-echo-p t
5742  "Show the contents of the header line in the echo area or as a tooltip
5743when you move point into the header line."
5744  :group 'erc-mode-line-and-header
5745  :type 'boolean)
5746
5747(defcustom erc-header-line-face-method nil
5748  "Determine what method to use when colorizing the header line text.
5749
5750If nil, don't colorize the header text.
5751If given a function, call it and use the resulting face name.
5752Otherwise, use the `erc-header-line' face."
5753  :group 'erc-mode-line-and-header
5754  :type '(choice (const :tag "Don't colorize" nil)
5755		 (const :tag "Use the erc-header-line face" t)
5756		 (function :tag "Call a function")))
5757
5758(defcustom erc-show-channel-key-p t
5759  "Show the the channel key in the header line."
5760  :group 'erc-paranoia
5761  :type 'boolean)
5762
5763(defcustom erc-common-server-suffixes
5764  '(("openprojects.net$" . "OPN")
5765    ("freenode.net$" . "freenode")
5766    ("oftc.net$" . "OFTC"))
5767  "Alist of common server name suffixes.
5768This variable is used in mode-line display to save screen
5769real estate.  Set it to nil if you want to avoid changing
5770displayed hostnames."
5771  :group 'erc-mode-line-and-header
5772  :type 'alist)
5773
5774(defcustom erc-mode-line-away-status-format
5775  "(AWAY since %a %b %d %H:%M) "
5776  "When you're away on a server, this is shown in the mode line.
5777This should be a string with substitution variables recognized by
5778`format-time-string'."
5779  :group 'erc-mode-line-and-header
5780  :type 'string)
5781
5782(defun erc-shorten-server-name (server-name)
5783  "Shorten SERVER-NAME according to `erc-common-server-suffixes'."
5784  (if (stringp server-name)
5785      (with-temp-buffer
5786	(insert server-name)
5787	(let ((alist erc-common-server-suffixes))
5788	  (while alist
5789	    (goto-char (point-min))
5790	(if (re-search-forward (caar alist) nil t)
5791	    (replace-match (cdar alist)))
5792	(setq alist (cdr alist))))
5793	(buffer-string))))
5794
5795(defun erc-format-target ()
5796  "Return the name of the target (channel or nickname or servername:port)."
5797  (let ((target (erc-default-target)))
5798    (or target
5799	(concat (erc-shorten-server-name
5800		 (or erc-server-announced-name
5801		     erc-session-server))
5802		":" (erc-port-to-string erc-session-port)))))
5803
5804(defun erc-format-target-and/or-server ()
5805  "Return the server name or the current target and server name combined."
5806  (let ((server-name (erc-shorten-server-name
5807		      (or erc-server-announced-name
5808			  erc-session-server))))
5809    (cond ((erc-default-target)
5810	   (concat (erc-string-no-properties (erc-default-target))
5811		   "@" server-name))
5812	  (server-name server-name)
5813	  (t (buffer-name (current-buffer))))))
5814
5815(defun erc-format-away-status ()
5816  "Return a formatted `erc-mode-line-away-status-format'
5817if `erc-away' is non-nil."
5818  (let ((a (erc-away-time)))
5819    (if a
5820	(format-time-string erc-mode-line-away-status-format a)
5821      "")))
5822
5823(defun erc-format-channel-modes ()
5824  "Return the current channel's modes."
5825  (concat (apply 'concat
5826		 "+" erc-channel-modes)
5827	  (cond ((and erc-channel-user-limit erc-channel-key)
5828		 (if erc-show-channel-key-p
5829		     (format "lk %.0f %s" erc-channel-user-limit
5830			     erc-channel-key)
5831		   (format "kl %.0f" erc-channel-user-limit)))
5832		(erc-channel-user-limit
5833		 ;; Emacs has no bignums
5834		 (format "l %.0f" erc-channel-user-limit))
5835		(erc-channel-key
5836		 (if erc-show-channel-key-p
5837		     (format "k %s" erc-channel-key)
5838		   "k"))
5839		(t nil))))
5840
5841(defun erc-format-lag-time ()
5842  "Return the estimated lag time to server, `erc-server-lag'."
5843  (let ((lag (erc-with-server-buffer erc-server-lag)))
5844    (cond (lag (format "lag:%.0f" lag))
5845	  (t ""))))
5846
5847(defun erc-update-mode-line-buffer (buffer)
5848  "Update the mode line in a single ERC buffer BUFFER."
5849  (with-current-buffer buffer
5850    (let ((spec (format-spec-make
5851		 ?a (erc-format-away-status)
5852		 ?l (erc-format-lag-time)
5853		 ?m (erc-format-channel-modes)
5854		 ?n (or (erc-current-nick) "")
5855		 ?o (erc-controls-strip erc-channel-topic)
5856		 ?p (erc-port-to-string erc-session-port)
5857		 ?s (erc-format-target-and/or-server)
5858		 ?t (erc-format-target)))
5859	  (process-status (cond ((and (erc-server-process-alive)
5860				      (not erc-server-connected))
5861				 ":connecting")
5862				((erc-server-process-alive)
5863				 "")
5864				(t
5865				 ": CLOSED")))
5866	  (face (cond ((eq erc-header-line-face-method nil)
5867		       nil)
5868		      ((functionp erc-header-line-face-method)
5869		       (funcall erc-header-line-face-method))
5870		      (t
5871		       'erc-header-line))))
5872      (cond ((featurep 'xemacs)
5873	     (setq modeline-buffer-identification
5874		   (list (format-spec erc-mode-line-format spec)))
5875	     (setq modeline-process (list process-status)))
5876	    (t
5877	     (setq mode-line-buffer-identification
5878		   (list (format-spec erc-mode-line-format spec)))
5879	     (setq mode-line-process (list process-status))))
5880      (when (boundp 'header-line-format)
5881	(let ((header (if erc-header-line-format
5882			  (format-spec erc-header-line-format spec)
5883			nil)))
5884	  (cond ((null header)
5885		 (setq header-line-format nil))
5886		(erc-header-line-uses-help-echo-p
5887		 (let ((help-echo (with-temp-buffer
5888				    (insert header)
5889				    (fill-region (point-min) (point-max))
5890				    (buffer-string))))
5891		   (setq header-line-format
5892			 (erc-replace-regexp-in-string
5893			  "%"
5894			  "%%"
5895			  (if face
5896			      (erc-propertize header 'help-echo help-echo
5897					      'face face)
5898			    (erc-propertize header 'help-echo help-echo))))))
5899		(t (setq header-line-format
5900			 (if face
5901			     (erc-propertize header 'face face)
5902			   header)))))))
5903    (if (featurep 'xemacs)
5904	(redraw-modeline)
5905      (force-mode-line-update))))
5906
5907(defun erc-update-mode-line (&optional buffer)
5908  "Update the mode line in BUFFER.
5909
5910If BUFFER is nil, update the mode line in all ERC buffers."
5911  (if (and buffer (bufferp buffer))
5912      (erc-update-mode-line-buffer buffer)
5913    (dolist (buf (erc-buffer-list))
5914      (when (buffer-live-p buf)
5915	(erc-update-mode-line-buffer buf)))))
5916
5917;; Miscellaneous
5918
5919(defun erc-port-to-string (p)
5920  "Convert port P to a string.
5921P may be an integer or a service name."
5922  (if (integerp p)
5923      (int-to-string p)
5924    p))
5925
5926(defun erc-string-to-port (s)
5927  "Convert string S to either an integer port number or a service name."
5928  (if (numberp s)
5929      s
5930    (let ((n (string-to-number s)))
5931      (if (= n 0)
5932	  s
5933	n))))
5934
5935(defun erc-version (&optional here)
5936  "Show the version number of ERC in the minibuffer.
5937If optional argument HERE is non-nil, insert version number at point."
5938  (interactive "P")
5939  (let ((version-string
5940	 (format "ERC %s (GNU Emacs %s)" erc-version-string emacs-version)))
5941    (if here
5942	(insert version-string)
5943      (if (interactive-p)
5944	  (message "%s" version-string)
5945	version-string))))
5946
5947(defun erc-modes (&optional here)
5948  "Show the active ERC modes in the minibuffer.
5949If optional argument HERE is non-nil, insert version number at point."
5950  (interactive "P")
5951  (let ((string
5952	 (mapconcat 'identity
5953		    (let (modes (case-fold-search nil))
5954		      (dolist (var (apropos-internal "^erc-.*mode$"))
5955			(when (and (boundp var)
5956				   (symbol-value var))
5957			  (setq modes (cons (symbol-name var)
5958					    modes))))
5959		      modes)
5960		    ", ")))
5961    (if here
5962	(insert string)
5963      (if (interactive-p)
5964	  (message "%s" string)
5965	string))))
5966
5967(defun erc-trim-string (s)
5968  "Trim leading and trailing spaces off S."
5969  (cond
5970   ((not (stringp s)) nil)
5971   ((string-match "^\\s-*$" s)
5972    "")
5973   ((string-match "^\\s-*\\(.*\\S-\\)\\s-*$" s)
5974    (match-string 1 s))
5975   (t
5976    s)))
5977
5978(defun erc-arrange-session-in-multiple-windows ()
5979  "Open a window for every non-server buffer related to `erc-session-server'.
5980
5981All windows are opened in the current frame."
5982  (interactive)
5983  (unless erc-server-process
5984    (error "No erc-server-process found in current buffer"))
5985  (let ((bufs (erc-buffer-list nil erc-server-process)))
5986    (when bufs
5987      (delete-other-windows)
5988      (switch-to-buffer (car bufs))
5989      (setq bufs (cdr bufs))
5990      (while bufs
5991	(split-window)
5992	(other-window 1)
5993	(switch-to-buffer (car bufs))
5994	(setq bufs (cdr bufs))
5995	(balance-windows)))))
5996
5997(defun erc-popup-input-buffer ()
5998  "Provide an input buffer."
5999   (interactive)
6000   (let ((buffer-name (generate-new-buffer-name "*ERC input*"))
6001	 (mode (intern
6002		(completing-read
6003		 "Mode: "
6004		 (mapcar (lambda (e)
6005			   (list (symbol-name e)))
6006			 (apropos-internal "-mode$" 'commandp))
6007		 nil t))))
6008     (pop-to-buffer (make-indirect-buffer (current-buffer) buffer-name))
6009     (funcall mode)
6010     (narrow-to-region (point) (point))
6011     (shrink-window-if-larger-than-buffer)))
6012
6013;;; Message catalog
6014
6015(defun erc-make-message-variable-name (catalog entry)
6016  "Create a variable name corresponding to CATALOG's ENTRY."
6017  (intern (concat "erc-message-"
6018		  (symbol-name catalog) "-" (symbol-name entry))))
6019
6020(defun erc-define-catalog-entry (catalog entry format-spec)
6021  "Set CATALOG's ENTRY to FORMAT-SPEC."
6022  (set (erc-make-message-variable-name catalog entry)
6023       format-spec))
6024
6025(defun erc-define-catalog (catalog entries)
6026  "Define a CATALOG according to ENTRIES."
6027  (dolist (entry entries)
6028    (erc-define-catalog-entry catalog (car entry) (cdr entry))))
6029
6030(erc-define-catalog
6031 'english
6032 '((bad-ping-response . "Unexpected PING response from %n (time %t)")
6033   (bad-syntax . "Error occurred - incorrect usage?\n%c %u\n%d")
6034   (incorrect-args . "Incorrect arguments. Usage:\n%c %u\n%d")
6035   (cannot-find-file . "Cannot find file %f")
6036   (cannot-read-file . "Cannot read file %f")
6037   (connect . "Connecting to %S:%p... ")
6038   (country . "%c")
6039   (country-unknown . "%d: No such domain")
6040   (ctcp-empty . "Illegal empty CTCP query received from %n. Ignoring.")
6041   (ctcp-request . "==> CTCP request from %n (%u@%h): %r")
6042   (ctcp-request-to . "==> CTCP request from %n (%u@%h) to %t: %r")
6043   (ctcp-too-many . "Too many CTCP queries in single message. Ignoring")
6044   (flood-ctcp-off . "FLOOD PROTECTION: Automatic CTCP responses turned off.")
6045   (flood-strict-mode
6046    . "FLOOD PROTECTION: Switched to Strict Flood Control mode.")
6047   (disconnected . "\n\nConnection failed!  Re-establishing connection...\n")
6048   (disconnected-noreconnect
6049    . "\n\nConnection failed!  Not re-establishing connection.\n")
6050   (finished . "\n\n*** ERC finished ***\n")
6051   (terminated . "\n\n*** ERC terminated: %e\n")
6052   (login . "Logging in as \'%n\'...")
6053   (nick-in-use . "%n is in use. Choose new nickname: ")
6054   (nick-too-long
6055    . "WARNING: Nick length (%i) exceeds max NICKLEN(%l) defined by server")
6056   (no-default-channel . "No default channel")
6057   (no-invitation . "You've got no invitation")
6058   (no-target . "No target")
6059   (ops . "%i operator%s: %o")
6060   (ops-none . "No operators in this channel.")
6061   (undefined-ctcp . "Undefined CTCP query received. Silently ignored")
6062   (variable-not-bound . "Variable not bound!")
6063   (ACTION . "* %n %a")
6064   (CTCP-CLIENTINFO . "Client info for %n: %m")
6065   (CTCP-ECHO . "Echo %n: %m")
6066   (CTCP-FINGER . "Finger info for %n: %m")
6067   (CTCP-PING . "Ping time to %n is %t")
6068   (CTCP-TIME . "Time by %n is %m")
6069   (CTCP-UNKNOWN . "Unknown CTCP message from %n (%u@%h): %m")
6070   (CTCP-VERSION . "Version for %n is %m")
6071   (ERROR  . "==> ERROR from %s: %c\n")
6072   (INVITE . "%n (%u@%h) invites you to channel %c")
6073   (JOIN   . "%n (%u@%h) has joined channel %c")
6074   (JOIN-you . "You have joined channel %c")
6075   (KICK . "%n (%u@%h) has kicked %k off channel %c: %r")
6076   (KICK-you . "You have been kicked off channel %c by %n (%u@%h): %r")
6077   (KICK-by-you . "You have kicked %k off channel %c: %r")
6078   (MODE   . "%n (%u@%h) has changed mode for %t to %m")
6079   (MODE-nick . "%n has changed mode for %t to %m")
6080   (NICK   . "%n (%u@%h) is now known as %N")
6081   (NICK-you . "Your new nickname is %N")
6082   (PART   . erc-message-english-PART)
6083   (PING   . "PING from server (last: %s sec. ago)")
6084   (PONG   . "PONG from %h (%i second%s)")
6085   (QUIT   . "%n (%u@%h) has quit: %r")
6086   (TOPIC  . "%n (%u@%h) has set the topic for %c: \"%T\"")
6087   (WALLOPS . "Wallops from %n: %m")
6088   (s004   . "%s %v %U %C")
6089   (s221   . "User modes for %n: %m")
6090   (s252   . "%i operator(s) online")
6091   (s253   . "%i unknown connection(s)")
6092   (s254   . "%i channels formed")
6093   (s301   . "%n is AWAY: %r")
6094   (s303   . "Is online: %n")
6095   (s305   . "%m")
6096   (s306   . "%m")
6097   (s311   . "%n is %f (%u@%h)")
6098   (s312   . "%n is/was on server %s (%c)")
6099   (s313   . "%n is an IRC operator")
6100   (s314   . "%n was %f (%u@%h)")
6101   (s317   . "%n has been idle for %i")
6102   (s317-on-since . "%n has been idle for %i, on since %t")
6103   (s319   . "%n is on channel(s): %c")
6104   (s320   . "%n is an identified user")
6105   (s321   . "Channel  Users  Topic")
6106   (s322   . "%c [%u] %t")
6107   (s324   . "%c modes: %m")
6108   (s329   . "%c was created on %t")
6109   (s330   . "%n %a %i")
6110   (s331   . "No topic is set for %c")
6111   (s332   . "Topic for %c: %T")
6112   (s333   . "%c: topic set by %n, %t")
6113   (s341   . "Inviting %n to channel %c")
6114   (s352   . "%-11c %-10n %-4a %u@%h (%f)")
6115   (s353   . "Users on %c: %u")
6116   (s367   . "Ban for %b on %c")
6117   (s367-set-by . "Ban for %b on %c set by %s on %t")
6118   (s368   . "Banlist of %c ends.")
6119   (s379   . "%c: Forwarded to %f")
6120   (s391   . "The time at %s is %t")
6121   (s401   . "%n: No such nick/channel")
6122   (s403   . "%c: No such channel")
6123   (s404   . "%c: Cannot send to channel")
6124   (s405   . "%c: You have joined too many channels")
6125   (s406   . "%n: There was no such nickname")
6126   (s412   . "No text to send")
6127   (s421   . "%c: Unknown command")
6128   (s431   . "No nickname given")
6129   (s432   . "%n is an erroneous nickname")
6130   (s442   . "%c: You're not on that channel")
6131   (s445   . "SUMMON has been disabled")
6132   (s446   . "USERS has been disabled")
6133   (s451   . "You have not registered")
6134   (s461   . "%c: not enough parameters")
6135   (s462   . "Unauthorized command (already registered)")
6136   (s463   . "Your host isn't among the privileged")
6137   (s464   . "Password incorrect")
6138   (s465   . "You are banned from this server")
6139   (s474   . "You can't join %c because you're banned (+b)")
6140   (s475   . "You must specify the correct channel key (+k) to join %c")
6141   (s481   . "Permission Denied - You're not an IRC operator")
6142   (s482   . "You need to be a channel operator of %c to do that")
6143   (s483   . "You can't kill a server!")
6144   (s484   . "Your connection is restricted!")
6145   (s485   . "You're not the original channel operator")
6146   (s491   . "No O-lines for your host")
6147   (s501   . "Unknown MODE flag")
6148   (s502   . "You can't change modes for other users")))
6149
6150(defun erc-message-english-PART (&rest args)
6151  "Format a proper PART message.
6152
6153This function is an example on what could be done with formatting
6154functions."
6155  (let ((nick (cadr (memq ?n args)))
6156	(user (cadr (memq ?u args)))
6157	(host (cadr (memq ?h args)))
6158	(channel (cadr (memq ?c args)))
6159	(reason (cadr (memq ?r args))))
6160    (if (string= nick (erc-current-nick))
6161	(format "You have left channel %s" channel)
6162      (format "%s (%s@%s) has left channel %s%s"
6163	      nick user host channel
6164	      (if (not (string= reason ""))
6165		  (format ": %s"
6166			  (erc-replace-regexp-in-string "%" "%%" reason))
6167		"")))))
6168
6169
6170(defvar erc-current-message-catalog 'english)
6171(make-variable-buffer-local 'erc-current-message-catalog)
6172
6173(defun erc-retrieve-catalog-entry (entry &optional catalog)
6174  "Retrieve ENTRY from CATALOG.
6175
6176If CATALOG is nil, `erc-current-message-catalog' is used.
6177
6178If ENTRY is nil in CATALOG, it is retrieved from the fallback,
6179english, catalog."
6180  (unless catalog (setq catalog erc-current-message-catalog))
6181  (let ((var (erc-make-message-variable-name catalog entry)))
6182    (if (boundp var)
6183	(symbol-value var)
6184      (when (boundp (erc-make-message-variable-name 'english entry))
6185	(symbol-value (erc-make-message-variable-name 'english entry))))))
6186
6187(defun erc-format-message (msg &rest args)
6188  "Format MSG according to ARGS.
6189
6190See also `format-spec'."
6191  (when (eq (logand (length args) 1) 1)	; oddp
6192    (error "Obscure usage of this function appeared"))
6193  (let ((entry (erc-retrieve-catalog-entry msg)))
6194    (when (not entry)
6195      (error "No format spec for message %s" msg))
6196    (when (functionp entry)
6197      (setq entry (apply entry args)))
6198    (format-spec entry (apply 'format-spec-make args))))
6199
6200;;; Various hook functions
6201
6202(add-hook 'kill-buffer-hook 'erc-kill-buffer-function)
6203
6204(defcustom erc-kill-server-hook '(erc-kill-server)
6205  "*Invoked whenever a server-buffer is killed via `kill-buffer'."
6206  :group 'erc-hooks
6207  :type 'hook)
6208
6209(defcustom erc-kill-channel-hook '(erc-kill-channel)
6210  "*Invoked whenever a channel-buffer is killed via `kill-buffer'."
6211  :group 'erc-hooks
6212  :type 'hook)
6213
6214(defcustom erc-kill-buffer-hook nil
6215  "*Hook run whenever a non-server or channel buffer is killed.
6216
6217See also `kill-buffer'."
6218  :group 'erc-hooks
6219  :type 'hook)
6220
6221(defun erc-kill-buffer-function ()
6222  "Function to call when an ERC buffer is killed.
6223This function should be on `kill-buffer-hook'.
6224When the current buffer is in `erc-mode', this function will run
6225one of the following hooks:
6226`erc-kill-server-hook' if the server buffer was killed,
6227`erc-kill-channel-hook' if a channel buffer was killed,
6228or `erc-kill-buffer-hook' if any other buffer."
6229  (when (eq major-mode 'erc-mode)
6230    (erc-remove-channel-users)
6231    (cond
6232     ((eq (erc-server-buffer) (current-buffer))
6233      (run-hooks 'erc-kill-server-hook))
6234     ((erc-channel-p (erc-default-target))
6235      (run-hooks 'erc-kill-channel-hook))
6236     (t
6237      (run-hooks 'erc-kill-buffer-hook)))))
6238
6239(defun erc-kill-server ()
6240  "Sends a QUIT command to the server when the server buffer is killed.
6241This function should be on `erc-kill-server-hook'."
6242  (when (erc-server-process-alive)
6243    (setq erc-server-quitting t)
6244    (erc-server-send (format "QUIT :%s" (funcall erc-quit-reason nil)))))
6245
6246(defun erc-kill-channel ()
6247  "Sends a PART command to the server when the channel buffer is killed.
6248This function should be on `erc-kill-channel-hook'."
6249  (when (erc-server-process-alive)
6250    (let ((tgt (erc-default-target)))
6251      (erc-server-send (format "PART %s :%s" tgt
6252			       (funcall erc-part-reason nil))
6253		       nil tgt))))
6254
6255;;; Dealing with `erc-parsed'
6256
6257(defun erc-find-parsed-property ()
6258  "Find the next occurrence of the `erc-parsed' text property."
6259  (text-property-not-all (point-min) (point-max) 'erc-parsed nil))
6260
6261(defun erc-restore-text-properties ()
6262  "Restore the property 'erc-parsed for the region."
6263  (let ((parsed-posn (erc-find-parsed-property)))
6264    (put-text-property
6265     (point-min) (point-max)
6266     'erc-parsed (when parsed-posn (erc-get-parsed-vector parsed-posn)))))
6267
6268(defun erc-get-parsed-vector (point)
6269  "Return the whole parsed vector on POINT."
6270  (get-text-property point 'erc-parsed))
6271
6272(defun erc-get-parsed-vector-nick (vect)
6273  "Return nickname in the parsed vector VECT."
6274  (let* ((untreated-nick (and vect (erc-response.sender vect)))
6275	 (maybe-nick (when untreated-nick
6276		       (car (split-string untreated-nick "!")))))
6277    (when (and (not (null maybe-nick))
6278	       (erc-is-valid-nick-p maybe-nick))
6279      untreated-nick)))
6280
6281(defun erc-get-parsed-vector-type (vect)
6282  "Return message type in the parsed vector VECT."
6283  (and vect
6284       (erc-response.command vect)))
6285
6286;; Teach url.el how to open irc:// URLs with ERC.
6287;; To activate, customize `url-irc-function' to `url-irc-erc'.
6288
6289;;;###autoload
6290(defun erc-handle-irc-url (host port channel user password)
6291  "Use ERC to IRC on HOST:PORT in CHANNEL as USER with PASSWORD.
6292If ERC is already connected to HOST:PORT, simply /join CHANNEL.
6293Otherwise, connect to HOST:PORT as USER and /join CHANNEL."
6294  (let ((server-buffer
6295	 (car (erc-buffer-filter
6296	       (lambda ()
6297		 (and (string-equal erc-session-server host)
6298		      (= erc-session-port port)
6299		      (erc-open-server-buffer-p)))))))
6300    (with-current-buffer (or server-buffer (current-buffer))
6301      (if (and server-buffer channel)
6302	  (erc-cmd-JOIN channel)
6303	(erc-open host port (or user (erc-compute-nick)) (erc-compute-full-name)
6304		  (not server-buffer) password nil channel
6305		  (when server-buffer
6306		    (get-buffer-process server-buffer)))))))
6307
6308(provide 'erc)
6309
6310;;; Deprecated. We might eventually stop requiring the goodies automatically.
6311;;; IMPORTANT: This require must appear _after_ the above (provide 'erc) to
6312;;; avoid a recursive require error when byte-compiling the entire package.
6313(require 'erc-goodies)
6314
6315;;; erc.el ends here
6316;;
6317;; Local Variables:
6318;; outline-regexp: ";;+"
6319;; indent-tabs-mode: t
6320;; tab-width: 8
6321;; End:
6322
6323;; arch-tag: d19587f6-627e-48c1-8d86-58595fa3eca3
6324