gnus-util.el 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995
  1. ;;; gnus-util.el --- utility functions for Gnus
  2. ;; Copyright (C) 1996-2015 Free Software Foundation, Inc.
  3. ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
  4. ;; Keywords: news
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; Nothing in this file depends on any other parts of Gnus -- all
  18. ;; functions and macros in this file are utility functions that are
  19. ;; used by Gnus and may be used by any other package without loading
  20. ;; Gnus first.
  21. ;; [Unfortunately, it does depend on other parts of Gnus, e.g. the
  22. ;; autoloads and defvars below...]
  23. ;;; Code:
  24. (eval-when-compile
  25. (require 'cl))
  26. (require 'time-date)
  27. (defcustom gnus-completing-read-function 'gnus-emacs-completing-read
  28. "Function use to do completing read."
  29. :version "24.1"
  30. :group 'gnus-meta
  31. :type `(radio (function-item
  32. :doc "Use Emacs standard `completing-read' function."
  33. gnus-emacs-completing-read)
  34. ;; iswitchb.el is very old and ido.el is unavailable
  35. ;; in XEmacs, so we exclude those function items.
  36. ,@(unless (featurep 'xemacs)
  37. '((function-item
  38. :doc "Use `ido-completing-read' function."
  39. gnus-ido-completing-read)
  40. (function-item
  41. :doc "Use iswitchb based completing-read function."
  42. gnus-iswitchb-completing-read)))))
  43. (defcustom gnus-completion-styles
  44. (if (and (boundp 'completion-styles-alist)
  45. (boundp 'completion-styles))
  46. (append (when (and (assq 'substring completion-styles-alist)
  47. (not (memq 'substring completion-styles)))
  48. (list 'substring))
  49. completion-styles)
  50. nil)
  51. "Value of `completion-styles' to use when completing."
  52. :version "24.1"
  53. :group 'gnus-meta
  54. :type '(repeat symbol))
  55. ;; Fixme: this should be a gnus variable, not nnmail-.
  56. (defvar nnmail-pathname-coding-system)
  57. (defvar nnmail-active-file-coding-system)
  58. ;; Inappropriate references to other parts of Gnus.
  59. (defvar gnus-emphasize-whitespace-regexp)
  60. (defvar gnus-original-article-buffer)
  61. (defvar gnus-user-agent)
  62. (autoload 'gnus-get-buffer-window "gnus-win")
  63. (autoload 'nnheader-narrow-to-headers "nnheader")
  64. (autoload 'nnheader-replace-chars-in-string "nnheader")
  65. (autoload 'mail-header-remove-comments "mail-parse")
  66. (eval-and-compile
  67. (cond
  68. ;; Prefer `replace-regexp-in-string' (present in Emacs, XEmacs 21.5,
  69. ;; SXEmacs 22.1.4) over `replace-in-string'. The latter leads to inf-loops
  70. ;; on empty matches:
  71. ;; (replace-in-string "foo" "/*$" "/")
  72. ;; (replace-in-string "xe" "\\(x\\)?" "")
  73. ((fboundp 'replace-regexp-in-string)
  74. (defun gnus-replace-in-string (string regexp newtext &optional literal)
  75. "Replace all matches for REGEXP with NEWTEXT in STRING.
  76. If LITERAL is non-nil, insert NEWTEXT literally. Return a new
  77. string containing the replacements.
  78. This is a compatibility function for different Emacsen."
  79. (replace-regexp-in-string regexp newtext string nil literal)))
  80. ((fboundp 'replace-in-string)
  81. (defalias 'gnus-replace-in-string 'replace-in-string))))
  82. (defun gnus-boundp (variable)
  83. "Return non-nil if VARIABLE is bound and non-nil."
  84. (and (boundp variable)
  85. (symbol-value variable)))
  86. (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
  87. "Pop to BUFFER, evaluate FORMS, and then return to the original window."
  88. (let ((tempvar (make-symbol "GnusStartBufferWindow"))
  89. (w (make-symbol "w"))
  90. (buf (make-symbol "buf")))
  91. `(let* ((,tempvar (selected-window))
  92. (,buf ,buffer)
  93. (,w (gnus-get-buffer-window ,buf 'visible)))
  94. (unwind-protect
  95. (progn
  96. (if ,w
  97. (progn
  98. (select-window ,w)
  99. (set-buffer (window-buffer ,w)))
  100. (pop-to-buffer ,buf))
  101. ,@forms)
  102. (select-window ,tempvar)))))
  103. (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
  104. (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
  105. (defmacro gnus-intern-safe (string hashtable)
  106. "Get hash value. Arguments are STRING and HASHTABLE."
  107. `(let ((symbol (intern ,string ,hashtable)))
  108. (or (boundp symbol)
  109. (set symbol nil))
  110. symbol))
  111. (defsubst gnus-goto-char (point)
  112. (and point (goto-char point)))
  113. (defmacro gnus-buffer-exists-p (buffer)
  114. `(let ((buffer ,buffer))
  115. (when buffer
  116. (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
  117. buffer))))
  118. ;; The LOCAL arg to `add-hook' is interpreted differently in Emacs and
  119. ;; XEmacs. In Emacs we don't need to call `make-local-hook' first.
  120. ;; It's harmless, though, so the main purpose of this alias is to shut
  121. ;; up the byte compiler.
  122. (defalias 'gnus-make-local-hook (if (featurep 'xemacs)
  123. 'make-local-hook
  124. 'ignore))
  125. (defun gnus-delete-first (elt list)
  126. "Delete by side effect the first occurrence of ELT as a member of LIST."
  127. (if (equal (car list) elt)
  128. (cdr list)
  129. (let ((total list))
  130. (while (and (cdr list)
  131. (not (equal (cadr list) elt)))
  132. (setq list (cdr list)))
  133. (when (cdr list)
  134. (setcdr list (cddr list)))
  135. total)))
  136. ;; Delete the current line (and the next N lines).
  137. (defmacro gnus-delete-line (&optional n)
  138. `(delete-region (point-at-bol)
  139. (progn (forward-line ,(or n 1)) (point))))
  140. (defun gnus-extract-address-components (from)
  141. "Extract address components from a From header.
  142. Given an RFC-822 address FROM, extract full name and canonical address.
  143. Returns a list of the form (FULL-NAME CANONICAL-ADDRESS). Much more simple
  144. solution than `mail-extract-address-components', which works much better, but
  145. is slower."
  146. (let (name address)
  147. ;; First find the address - the thing with the @ in it. This may
  148. ;; not be accurate in mail addresses, but does the trick most of
  149. ;; the time in news messages.
  150. (cond (;; Check ``<foo@bar>'' first in order to handle the quite common
  151. ;; form ``"abc@xyz" <foo@bar>'' (i.e. ``@'' as part of a comment)
  152. ;; correctly.
  153. (string-match "<\\([^@ \t<>]+[!@][^@ \t<>]+\\)>" from)
  154. (setq address (substring from (match-beginning 1) (match-end 1))))
  155. ((string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
  156. (setq address (substring from (match-beginning 0) (match-end 0)))))
  157. ;; Then we check whether the "name <address>" format is used.
  158. (and address
  159. ;; Linear white space is not required.
  160. (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
  161. (and (setq name (substring from 0 (match-beginning 0)))
  162. ;; Strip any quotes from the name.
  163. (string-match "^\".*\"$" name)
  164. (setq name (substring name 1 (1- (match-end 0))))))
  165. ;; If not, then "address (name)" is used.
  166. (or name
  167. (and (string-match "(.+)" from)
  168. (setq name (substring from (1+ (match-beginning 0))
  169. (1- (match-end 0)))))
  170. (and (string-match "()" from)
  171. (setq name address))
  172. ;; XOVER might not support folded From headers.
  173. (and (string-match "(.*" from)
  174. (setq name (substring from (1+ (match-beginning 0))
  175. (match-end 0)))))
  176. (list (if (string= name "") nil name) (or address from))))
  177. (declare-function message-fetch-field "message" (header &optional not-all))
  178. (defun gnus-fetch-field (field)
  179. "Return the value of the header FIELD of current article."
  180. (require 'message)
  181. (save-excursion
  182. (save-restriction
  183. (let ((inhibit-point-motion-hooks t))
  184. (nnheader-narrow-to-headers)
  185. (message-fetch-field field)))))
  186. (defun gnus-fetch-original-field (field)
  187. "Fetch FIELD from the original version of the current article."
  188. (with-current-buffer gnus-original-article-buffer
  189. (gnus-fetch-field field)))
  190. (defun gnus-goto-colon ()
  191. (move-beginning-of-line 1)
  192. (let ((eol (point-at-eol)))
  193. (goto-char (or (text-property-any (point) eol 'gnus-position t)
  194. (search-forward ":" eol t)
  195. (point)))))
  196. (declare-function gnus-find-method-for-group "gnus" (group &optional info))
  197. (declare-function gnus-group-name-decode "gnus-group" (string charset))
  198. (declare-function gnus-group-name-charset "gnus-group" (method group))
  199. ;; gnus-group requires gnus-int which requires message.
  200. (declare-function message-tokenize-header "message"
  201. (header &optional separator))
  202. (defun gnus-decode-newsgroups (newsgroups group &optional method)
  203. (require 'gnus-group)
  204. (let ((method (or method (gnus-find-method-for-group group))))
  205. (mapconcat (lambda (group)
  206. (gnus-group-name-decode group (gnus-group-name-charset
  207. method group)))
  208. (message-tokenize-header newsgroups)
  209. ",")))
  210. (defun gnus-remove-text-with-property (prop)
  211. "Delete all text in the current buffer with text property PROP."
  212. (let ((start (point-min))
  213. end)
  214. (unless (get-text-property start prop)
  215. (setq start (next-single-property-change start prop)))
  216. (while start
  217. (setq end (text-property-any start (point-max) prop nil))
  218. (delete-region start (or end (point-max)))
  219. (setq start (when end
  220. (next-single-property-change start prop))))))
  221. (defun gnus-find-text-property-region (start end prop)
  222. "Return a list of text property regions that has property PROP."
  223. (let (regions value)
  224. (unless (get-text-property start prop)
  225. (setq start (next-single-property-change start prop)))
  226. (while start
  227. (setq value (get-text-property start prop)
  228. end (text-property-not-all start (point-max) prop value))
  229. (if (not end)
  230. (setq start nil)
  231. (when value
  232. (push (list (set-marker (make-marker) start)
  233. (set-marker (make-marker) end)
  234. value)
  235. regions))
  236. (setq start (next-single-property-change start prop))))
  237. (nreverse regions)))
  238. (defun gnus-newsgroup-directory-form (newsgroup)
  239. "Make hierarchical directory name from NEWSGROUP name."
  240. (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
  241. (idx (string-match ":" newsgroup)))
  242. (concat
  243. (if idx (substring newsgroup 0 idx))
  244. (if idx "/")
  245. (nnheader-replace-chars-in-string
  246. (if idx (substring newsgroup (1+ idx)) newsgroup)
  247. ?. ?/))))
  248. (defun gnus-newsgroup-savable-name (group)
  249. ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
  250. ;; with dots.
  251. (nnheader-replace-chars-in-string group ?/ ?.))
  252. (defun gnus-string> (s1 s2)
  253. (not (or (string< s1 s2)
  254. (string= s1 s2))))
  255. (defun gnus-string< (s1 s2)
  256. "Return t if first arg string is less than second in lexicographic order.
  257. Case is significant if and only if `case-fold-search' is nil.
  258. Symbols are also allowed; their print names are used instead."
  259. (if case-fold-search
  260. (string-lessp (downcase (if (symbolp s1) (symbol-name s1) s1))
  261. (downcase (if (symbolp s2) (symbol-name s2) s2)))
  262. (string-lessp s1 s2)))
  263. ;;; Time functions.
  264. (defun gnus-file-newer-than (file date)
  265. (let ((fdate (nth 5 (file-attributes file))))
  266. (or (> (car fdate) (car date))
  267. (and (= (car fdate) (car date))
  268. (> (nth 1 fdate) (nth 1 date))))))
  269. ;; Every version of Emacs Gnus supports has built-in float-time.
  270. ;; The featurep test silences an irritating compiler warning.
  271. (defalias 'gnus-float-time
  272. (if (or (featurep 'emacs)
  273. (fboundp 'float-time))
  274. 'float-time 'time-to-seconds))
  275. ;;; Keymap macros.
  276. (defmacro gnus-local-set-keys (&rest plist)
  277. "Set the keys in PLIST in the current keymap."
  278. `(gnus-define-keys-1 (current-local-map) ',plist))
  279. (defmacro gnus-define-keys (keymap &rest plist)
  280. "Define all keys in PLIST in KEYMAP."
  281. ;; Convert the key [?\S-\ ] to [(shift space)] for XEmacs.
  282. (when (featurep 'xemacs)
  283. (let ((bindings plist))
  284. (while bindings
  285. (when (equal (car bindings) [?\S-\ ])
  286. (setcar bindings [(shift space)]))
  287. (setq bindings (cddr bindings)))))
  288. `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
  289. (defmacro gnus-define-keys-safe (keymap &rest plist)
  290. "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
  291. `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
  292. (put 'gnus-define-keys 'lisp-indent-function 1)
  293. (put 'gnus-define-keys-safe 'lisp-indent-function 1)
  294. (put 'gnus-local-set-keys 'lisp-indent-function 1)
  295. (defmacro gnus-define-keymap (keymap &rest plist)
  296. "Define all keys in PLIST in KEYMAP."
  297. `(gnus-define-keys-1 ,keymap (quote ,plist)))
  298. (put 'gnus-define-keymap 'lisp-indent-function 1)
  299. (defun gnus-define-keys-1 (keymap plist &optional safe)
  300. (when (null keymap)
  301. (error "Can't set keys in a null keymap"))
  302. (cond ((symbolp keymap)
  303. (setq keymap (symbol-value keymap)))
  304. ((keymapp keymap))
  305. ((listp keymap)
  306. (set (car keymap) nil)
  307. (define-prefix-command (car keymap))
  308. (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
  309. (setq keymap (symbol-value (car keymap)))))
  310. (let (key)
  311. (while plist
  312. (when (symbolp (setq key (pop plist)))
  313. (setq key (symbol-value key)))
  314. (if (or (not safe)
  315. (eq (lookup-key keymap key) 'undefined))
  316. (define-key keymap key (pop plist))
  317. (pop plist)))))
  318. (defun gnus-y-or-n-p (prompt)
  319. (prog1
  320. (y-or-n-p prompt)
  321. (message "")))
  322. (defun gnus-yes-or-no-p (prompt)
  323. (prog1
  324. (yes-or-no-p prompt)
  325. (message "")))
  326. ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
  327. ;; age-depending date representations. (e.g. just the time if it's
  328. ;; from today, the day of the week if it's within the last 7 days and
  329. ;; the full date if it's older)
  330. (defun gnus-seconds-today ()
  331. "Return the number of seconds passed today."
  332. (let ((now (decode-time)))
  333. (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
  334. (defun gnus-seconds-month ()
  335. "Return the number of seconds passed this month."
  336. (let ((now (decode-time)))
  337. (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
  338. (* (- (car (nthcdr 3 now)) 1) 3600 24))))
  339. (defun gnus-seconds-year ()
  340. "Return the number of seconds passed this year."
  341. (let* ((current (current-time))
  342. (now (decode-time current))
  343. (days (format-time-string "%j" current)))
  344. (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
  345. (* (- (string-to-number days) 1) 3600 24))))
  346. (defmacro gnus-date-get-time (date)
  347. "Convert DATE string to Emacs time.
  348. Cache the result as a text property stored in DATE."
  349. ;; Either return the cached value...
  350. `(let ((d ,date))
  351. (if (equal "" d)
  352. '(0 0)
  353. (or (get-text-property 0 'gnus-time d)
  354. ;; or compute the value...
  355. (let ((time (safe-date-to-time d)))
  356. ;; and store it back in the string.
  357. (put-text-property 0 1 'gnus-time time d)
  358. time)))))
  359. (defun gnus-dd-mmm (messy-date)
  360. "Return a string like DD-MMM from a big messy string."
  361. (condition-case ()
  362. (format-time-string "%d-%b" (gnus-date-get-time messy-date))
  363. (error " - ")))
  364. (defsubst gnus-time-iso8601 (time)
  365. "Return a string of TIME in YYYYMMDDTHHMMSS format."
  366. (format-time-string "%Y%m%dT%H%M%S" time))
  367. (defun gnus-date-iso8601 (date)
  368. "Convert the DATE to YYYYMMDDTHHMMSS."
  369. (condition-case ()
  370. (gnus-time-iso8601 (gnus-date-get-time date))
  371. (error "")))
  372. (defun gnus-mode-string-quote (string)
  373. "Quote all \"%\"'s in STRING."
  374. (gnus-replace-in-string string "%" "%%"))
  375. ;; Make a hash table (default and minimum size is 256).
  376. ;; Optional argument HASHSIZE specifies the table size.
  377. (defun gnus-make-hashtable (&optional hashsize)
  378. (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
  379. ;; Make a number that is suitable for hashing; bigger than MIN and
  380. ;; equal to some 2^x. Many machines (such as sparcs) do not have a
  381. ;; hardware modulo operation, so they implement it in software. On
  382. ;; many sparcs over 50% of the time to intern is spent in the modulo.
  383. ;; Yes, it's slower than actually computing the hash from the string!
  384. ;; So we use powers of 2 so people can optimize the modulo to a mask.
  385. (defun gnus-create-hash-size (min)
  386. (let ((i 1))
  387. (while (< i min)
  388. (setq i (* 2 i)))
  389. i))
  390. (defcustom gnus-verbose 6
  391. "*Integer that says how verbose Gnus should be.
  392. The higher the number, the more messages Gnus will flash to say what
  393. it's doing. At zero, Gnus will be totally mute; at five, Gnus will
  394. display most important messages; and at ten, Gnus will keep on
  395. jabbering all the time."
  396. :version "24.1"
  397. :group 'gnus-start
  398. :type 'integer)
  399. (defcustom gnus-add-timestamp-to-message nil
  400. "Non-nil means add timestamps to messages that Gnus issues.
  401. If it is `log', add timestamps to only the messages that go into the
  402. \"*Messages*\" buffer (in XEmacs, it is the \" *Message-Log*\" buffer).
  403. If it is neither nil nor `log', add timestamps not only to log messages
  404. but also to the ones displayed in the echo area."
  405. :version "23.1" ;; No Gnus
  406. :group 'gnus-various
  407. :type '(choice :format "%{%t%}:\n %[Value Menu%] %v"
  408. (const :tag "Logged messages only" log)
  409. (sexp :tag "All messages"
  410. :match (lambda (widget value) value)
  411. :value t)
  412. (const :tag "No timestamp" nil)))
  413. (eval-when-compile
  414. (defmacro gnus-message-with-timestamp-1 (format-string args)
  415. (let ((timestamp '(format-time-string "%Y%m%dT%H%M%S.%3N> " time)))
  416. (if (featurep 'xemacs)
  417. `(let (str time)
  418. (if (or (and (null ,format-string) (null ,args))
  419. (progn
  420. (setq str (apply 'format ,format-string ,args))
  421. (zerop (length str))))
  422. (prog1
  423. (and ,format-string str)
  424. (clear-message nil))
  425. (cond ((eq gnus-add-timestamp-to-message 'log)
  426. (setq time (current-time))
  427. (display-message 'no-log str)
  428. (log-message 'message (concat ,timestamp str)))
  429. (gnus-add-timestamp-to-message
  430. (setq time (current-time))
  431. (display-message 'message (concat ,timestamp str)))
  432. (t
  433. (display-message 'message str))))
  434. str)
  435. `(let (str time)
  436. (cond ((eq gnus-add-timestamp-to-message 'log)
  437. (setq str (let (message-log-max)
  438. (apply 'message ,format-string ,args)))
  439. (when (and message-log-max
  440. (> message-log-max 0)
  441. (/= (length str) 0))
  442. (setq time (current-time))
  443. (with-current-buffer (if (fboundp 'messages-buffer)
  444. (messages-buffer)
  445. (get-buffer-create "*Messages*"))
  446. (goto-char (point-max))
  447. (let ((inhibit-read-only t))
  448. (insert ,timestamp str "\n")
  449. (forward-line (- message-log-max))
  450. (delete-region (point-min) (point)))
  451. (goto-char (point-max))))
  452. str)
  453. (gnus-add-timestamp-to-message
  454. (if (or (and (null ,format-string) (null ,args))
  455. (progn
  456. (setq str (apply 'format ,format-string ,args))
  457. (zerop (length str))))
  458. (prog1
  459. (and ,format-string str)
  460. (message nil))
  461. (setq time (current-time))
  462. (message "%s" (concat ,timestamp str))
  463. str))
  464. (t
  465. (apply 'message ,format-string ,args))))))))
  466. (defvar gnus-action-message-log nil)
  467. (defun gnus-message-with-timestamp (format-string &rest args)
  468. "Display message with timestamp. Arguments are the same as `message'.
  469. The `gnus-add-timestamp-to-message' variable controls how to add
  470. timestamp to message."
  471. (gnus-message-with-timestamp-1 format-string args))
  472. (defun gnus-message (level &rest args)
  473. "If LEVEL is lower than `gnus-verbose' print ARGS using `message'.
  474. Guideline for numbers:
  475. 1 - error messages, 3 - non-serious error messages, 5 - messages for things
  476. that take a long time, 7 - not very important messages on stuff, 9 - messages
  477. inside loops."
  478. (if (<= level gnus-verbose)
  479. (let ((message
  480. (if gnus-add-timestamp-to-message
  481. (apply 'gnus-message-with-timestamp args)
  482. (apply 'message args))))
  483. (when (and (consp gnus-action-message-log)
  484. (<= level 3))
  485. (push message gnus-action-message-log))
  486. message)
  487. ;; We have to do this format thingy here even if the result isn't
  488. ;; shown - the return value has to be the same as the return value
  489. ;; from `message'.
  490. (apply 'format args)))
  491. (defun gnus-final-warning ()
  492. (when (and (consp gnus-action-message-log)
  493. (setq gnus-action-message-log
  494. (delete nil gnus-action-message-log)))
  495. (message "Warning: %s"
  496. (mapconcat #'identity gnus-action-message-log "; "))))
  497. (defun gnus-error (level &rest args)
  498. "Beep an error if LEVEL is equal to or less than `gnus-verbose'.
  499. ARGS are passed to `message'."
  500. (when (<= (floor level) gnus-verbose)
  501. (apply 'message args)
  502. (ding)
  503. (let (duration)
  504. (when (and (floatp level)
  505. (not (zerop (setq duration (* 10 (- level (floor level)))))))
  506. (sit-for duration))))
  507. nil)
  508. (defun gnus-split-references (references)
  509. "Return a list of Message-IDs in REFERENCES."
  510. (let ((beg 0)
  511. (references (mail-header-remove-comments (or references "")))
  512. ids)
  513. (while (string-match "<[^<]+[^< \t]" references beg)
  514. (push (substring references (match-beginning 0) (setq beg (match-end 0)))
  515. ids))
  516. (nreverse ids)))
  517. (defun gnus-extract-references (references)
  518. "Return a list of Message-IDs in REFERENCES (in In-Reply-To
  519. format), trimmed to only contain the Message-IDs."
  520. (let ((ids (gnus-split-references references))
  521. refs)
  522. (dolist (id ids)
  523. (when (string-match "<[^<>]+>" id)
  524. (push (match-string 0 id) refs)))
  525. refs))
  526. (defsubst gnus-parent-id (references &optional n)
  527. "Return the last Message-ID in REFERENCES.
  528. If N, return the Nth ancestor instead."
  529. (when (and references
  530. (not (zerop (length references))))
  531. (if n
  532. (let ((ids (inline (gnus-split-references references))))
  533. (while (nthcdr n ids)
  534. (setq ids (cdr ids)))
  535. (car ids))
  536. (let ((references (mail-header-remove-comments references)))
  537. (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
  538. (match-string 1 references))))))
  539. (defsubst gnus-buffer-live-p (buffer)
  540. "Say whether BUFFER is alive or not."
  541. (and buffer (buffer-live-p (get-buffer buffer))))
  542. (defun gnus-horizontal-recenter ()
  543. "Recenter the current buffer horizontally."
  544. (if (< (current-column) (/ (window-width) 2))
  545. (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
  546. (let* ((orig (point))
  547. (end (window-end (gnus-get-buffer-window (current-buffer) t)))
  548. (max 0))
  549. (when end
  550. ;; Find the longest line currently displayed in the window.
  551. (goto-char (window-start))
  552. (while (and (not (eobp))
  553. (< (point) end))
  554. (end-of-line)
  555. (setq max (max max (current-column)))
  556. (forward-line 1))
  557. (goto-char orig)
  558. ;; Scroll horizontally to center (sort of) the point.
  559. (if (> max (window-width))
  560. (set-window-hscroll
  561. (gnus-get-buffer-window (current-buffer) t)
  562. (min (- (current-column) (/ (window-width) 3))
  563. (+ 2 (- max (window-width)))))
  564. (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
  565. max))))
  566. (defun gnus-read-event-char (&optional prompt)
  567. "Get the next event."
  568. (let ((event (read-event prompt)))
  569. ;; should be gnus-characterp, but this can't be called in XEmacs anyway
  570. (cons (and (numberp event) event) event)))
  571. (defun gnus-copy-file (file &optional to)
  572. "Copy FILE to TO."
  573. (interactive
  574. (list (read-file-name "Copy file: " default-directory)
  575. (read-file-name "Copy file to: " default-directory)))
  576. (unless to
  577. (setq to (read-file-name "Copy file to: " default-directory)))
  578. (when (file-directory-p to)
  579. (setq to (concat (file-name-as-directory to)
  580. (file-name-nondirectory file))))
  581. (copy-file file to))
  582. (defvar gnus-work-buffer " *gnus work*")
  583. (declare-function gnus-get-buffer-create "gnus" (name))
  584. ;; gnus.el requires mm-util.
  585. (declare-function mm-enable-multibyte "mm-util")
  586. (defun gnus-set-work-buffer ()
  587. "Put point in the empty Gnus work buffer."
  588. (if (get-buffer gnus-work-buffer)
  589. (progn
  590. (set-buffer gnus-work-buffer)
  591. (erase-buffer))
  592. (set-buffer (gnus-get-buffer-create gnus-work-buffer))
  593. (kill-all-local-variables)
  594. (mm-enable-multibyte)))
  595. (defmacro gnus-group-real-name (group)
  596. "Find the real name of a foreign newsgroup."
  597. `(let ((gname ,group))
  598. (if (string-match "^[^:]+:" gname)
  599. (substring gname (match-end 0))
  600. gname)))
  601. (defmacro gnus-group-server (group)
  602. "Find the server name of a foreign newsgroup.
  603. For example, (gnus-group-server \"nnimap+yxa:INBOX.foo\") would
  604. yield \"nnimap:yxa\"."
  605. `(let ((gname ,group))
  606. (if (string-match "^\\([^:+]+\\)\\(?:\\+\\([^:]*\\)\\)?:" gname)
  607. (format "%s:%s" (match-string 1 gname) (or
  608. (match-string 2 gname)
  609. ""))
  610. (format "%s:%s" (car gnus-select-method) (cadr gnus-select-method)))))
  611. (defun gnus-make-sort-function (funs)
  612. "Return a composite sort condition based on the functions in FUNS."
  613. (cond
  614. ;; Just a simple function.
  615. ((functionp funs) funs)
  616. ;; No functions at all.
  617. ((null funs) funs)
  618. ;; A list of functions.
  619. ((or (cdr funs)
  620. (listp (car funs)))
  621. (gnus-byte-compile
  622. `(lambda (t1 t2)
  623. ,(gnus-make-sort-function-1 (reverse funs)))))
  624. ;; A list containing just one function.
  625. (t
  626. (car funs))))
  627. (defun gnus-make-sort-function-1 (funs)
  628. "Return a composite sort condition based on the functions in FUNS."
  629. (let ((function (car funs))
  630. (first 't1)
  631. (last 't2))
  632. (when (consp function)
  633. (cond
  634. ;; Reversed spec.
  635. ((eq (car function) 'not)
  636. (setq function (cadr function)
  637. first 't2
  638. last 't1))
  639. ((functionp function)
  640. ;; Do nothing.
  641. )
  642. (t
  643. (error "Invalid sort spec: %s" function))))
  644. (if (cdr funs)
  645. `(or (,function ,first ,last)
  646. (and (not (,function ,last ,first))
  647. ,(gnus-make-sort-function-1 (cdr funs))))
  648. `(,function ,first ,last))))
  649. (defun gnus-turn-off-edit-menu (type)
  650. "Turn off edit menu in `gnus-TYPE-mode-map'."
  651. (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
  652. [menu-bar edit] 'undefined))
  653. (defmacro gnus-bind-print-variables (&rest forms)
  654. "Bind print-* variables and evaluate FORMS.
  655. This macro is used with `prin1', `pp', etc. in order to ensure printed
  656. Lisp objects are loadable. Bind `print-quoted' and `print-readably'
  657. to t, and `print-escape-multibyte', `print-escape-newlines',
  658. `print-escape-nonascii', `print-length', `print-level' and
  659. `print-string-length' to nil."
  660. `(let ((print-quoted t)
  661. (print-readably t)
  662. ;;print-circle
  663. ;;print-continuous-numbering
  664. print-escape-multibyte
  665. print-escape-newlines
  666. print-escape-nonascii
  667. ;;print-gensym
  668. print-length
  669. print-level
  670. print-string-length)
  671. ,@forms))
  672. (defun gnus-prin1 (form)
  673. "Use `prin1' on FORM in the current buffer.
  674. Bind `print-quoted' and `print-readably' to t, and `print-length' and
  675. `print-level' to nil. See also `gnus-bind-print-variables'."
  676. (gnus-bind-print-variables (prin1 form (current-buffer))))
  677. (defun gnus-prin1-to-string (form)
  678. "The same as `prin1'.
  679. Bind `print-quoted' and `print-readably' to t, and `print-length' and
  680. `print-level' to nil. See also `gnus-bind-print-variables'."
  681. (gnus-bind-print-variables (prin1-to-string form)))
  682. (defun gnus-pp (form &optional stream)
  683. "Use `pp' on FORM in the current buffer.
  684. Bind `print-quoted' and `print-readably' to t, and `print-length' and
  685. `print-level' to nil. See also `gnus-bind-print-variables'."
  686. (gnus-bind-print-variables (pp form (or stream (current-buffer)))))
  687. (defun gnus-pp-to-string (form)
  688. "The same as `pp-to-string'.
  689. Bind `print-quoted' and `print-readably' to t, and `print-length' and
  690. `print-level' to nil. See also `gnus-bind-print-variables'."
  691. (gnus-bind-print-variables (pp-to-string form)))
  692. (defun gnus-make-directory (directory)
  693. "Make DIRECTORY (and all its parents) if it doesn't exist."
  694. (require 'nnmail)
  695. (let ((file-name-coding-system nnmail-pathname-coding-system))
  696. (when (and directory
  697. (not (file-exists-p directory)))
  698. (make-directory directory t)))
  699. t)
  700. (defun gnus-write-buffer (file)
  701. "Write the current buffer's contents to FILE."
  702. (require 'nnmail)
  703. (let ((file-name-coding-system nnmail-pathname-coding-system))
  704. ;; Make sure the directory exists.
  705. (gnus-make-directory (file-name-directory file))
  706. ;; Write the buffer.
  707. (write-region (point-min) (point-max) file nil 'quietly)))
  708. (defun gnus-delete-file (file)
  709. "Delete FILE if it exists."
  710. (when (file-exists-p file)
  711. (delete-file file)))
  712. (defun gnus-delete-duplicates (list)
  713. "Remove duplicate entries from LIST."
  714. (let ((result nil))
  715. (while list
  716. (unless (member (car list) result)
  717. (push (car list) result))
  718. (pop list))
  719. (nreverse result)))
  720. (defun gnus-delete-directory (directory)
  721. "Delete files in DIRECTORY. Subdirectories remain.
  722. If there's no subdirectory, delete DIRECTORY as well."
  723. (when (file-directory-p directory)
  724. (let ((files (directory-files
  725. directory t "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
  726. file dir)
  727. (while files
  728. (setq file (pop files))
  729. (if (eq t (car (file-attributes file)))
  730. ;; `file' is a subdirectory.
  731. (setq dir t)
  732. ;; `file' is a file or a symlink.
  733. (delete-file file)))
  734. (unless dir
  735. (delete-directory directory)))))
  736. (defun gnus-strip-whitespace (string)
  737. "Return STRING stripped of all whitespace."
  738. (while (string-match "[\r\n\t ]+" string)
  739. (setq string (replace-match "" t t string)))
  740. string)
  741. (declare-function gnus-put-text-property "gnus"
  742. (start end property value &optional object))
  743. (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
  744. "The same as `put-text-property', but don't put this prop on any newlines in the region."
  745. (save-match-data
  746. (save-excursion
  747. (save-restriction
  748. (goto-char beg)
  749. (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
  750. (gnus-put-text-property beg (match-beginning 0) prop val)
  751. (setq beg (point)))
  752. (gnus-put-text-property beg (point) prop val)))))
  753. (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
  754. "The same as `put-text-property', but don't put this prop on any newlines in the region."
  755. (save-match-data
  756. (save-excursion
  757. (save-restriction
  758. (goto-char beg)
  759. (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
  760. (overlay-put (make-overlay beg (match-beginning 0)) prop val)
  761. (setq beg (point)))
  762. (overlay-put (make-overlay beg (point)) prop val)))))
  763. (defun gnus-put-text-property-excluding-characters-with-faces (beg end prop val)
  764. "The same as `put-text-property', except where `gnus-face' is set.
  765. If so, and PROP is `face', set the second element of its value to VAL.
  766. Otherwise, do nothing."
  767. (while (< beg end)
  768. ;; Property values are compared with `eq'.
  769. (let ((stop (next-single-property-change beg 'face nil end)))
  770. (if (get-text-property beg 'gnus-face)
  771. (when (eq prop 'face)
  772. (setcar (cdr (get-text-property beg 'face)) (or val 'default)))
  773. (inline
  774. (gnus-put-text-property beg stop prop val)))
  775. (setq beg stop))))
  776. (defun gnus-get-text-property-excluding-characters-with-faces (pos prop)
  777. "The same as `get-text-property', except where `gnus-face' is set.
  778. If so, and PROP is `face', return the second element of its value.
  779. Otherwise, return the value."
  780. (let ((val (get-text-property pos prop)))
  781. (if (and (get-text-property pos 'gnus-face)
  782. (eq prop 'face))
  783. (cadr val)
  784. (get-text-property pos prop))))
  785. (defmacro gnus-faces-at (position)
  786. "Return a list of faces at POSITION."
  787. (if (featurep 'xemacs)
  788. `(let ((pos ,position))
  789. (mapcar-extents 'extent-face
  790. nil (current-buffer) pos pos nil 'face))
  791. `(let ((pos ,position))
  792. (delq nil (cons (get-text-property pos 'face)
  793. (mapcar
  794. (lambda (overlay)
  795. (overlay-get overlay 'face))
  796. (overlays-at pos)))))))
  797. (if (fboundp 'invisible-p)
  798. (defalias 'gnus-invisible-p 'invisible-p)
  799. ;; for Emacs < 22.2, and XEmacs.
  800. (defun gnus-invisible-p (pos)
  801. "Return non-nil if the character after POS is currently invisible."
  802. (let ((prop (get-char-property pos 'invisible)))
  803. (if (eq buffer-invisibility-spec t)
  804. prop
  805. (or (memq prop buffer-invisibility-spec)
  806. (assq prop buffer-invisibility-spec))))))
  807. ;; Note: the optional 2nd argument has a different meaning between
  808. ;; Emacs and XEmacs.
  809. ;; (next-char-property-change POSITION &optional LIMIT)
  810. ;; (next-extent-change POS &optional OBJECT)
  811. (defalias 'gnus-next-char-property-change
  812. (if (fboundp 'next-extent-change)
  813. 'next-extent-change 'next-char-property-change))
  814. (defalias 'gnus-previous-char-property-change
  815. (if (fboundp 'previous-extent-change)
  816. 'previous-extent-change 'previous-char-property-change))
  817. ;;; Protected and atomic operations. dmoore@ucsd.edu 21.11.1996
  818. ;; The primary idea here is to try to protect internal data structures
  819. ;; from becoming corrupted when the user hits C-g, or if a hook or
  820. ;; similar blows up. Often in Gnus multiple tables/lists need to be
  821. ;; updated at the same time, or information can be lost.
  822. (defvar gnus-atomic-be-safe t
  823. "If t, certain operations will be protected from interruption by C-g.")
  824. (defmacro gnus-atomic-progn (&rest forms)
  825. "Evaluate FORMS atomically, which means to protect the evaluation
  826. from being interrupted by the user. An error from the forms themselves
  827. will return without finishing the operation. Since interrupts from
  828. the user are disabled, it is recommended that only the most minimal
  829. operations are performed by FORMS. If you wish to assign many
  830. complicated values atomically, compute the results into temporary
  831. variables and then do only the assignment atomically."
  832. `(let ((inhibit-quit gnus-atomic-be-safe))
  833. ,@forms))
  834. (put 'gnus-atomic-progn 'lisp-indent-function 0)
  835. (defmacro gnus-atomic-progn-assign (protect &rest forms)
  836. "Evaluate FORMS, but ensure that the variables listed in PROTECT
  837. are not changed if anything in FORMS signals an error or otherwise
  838. non-locally exits. The variables listed in PROTECT are updated atomically.
  839. It is safe to use gnus-atomic-progn-assign with long computations.
  840. Note that if any of the symbols in PROTECT were unbound, they will be
  841. set to nil on a successful assignment. In case of an error or other
  842. non-local exit, it will still be unbound."
  843. (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
  844. (concat (symbol-name x)
  845. "-tmp"))
  846. x))
  847. protect))
  848. (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
  849. temp-sym-map))
  850. (temp-sym-let (mapcar (lambda (x) (list (car x)
  851. `(and (boundp ',(cadr x))
  852. ,(cadr x))))
  853. temp-sym-map))
  854. (sym-temp-let sym-temp-map)
  855. (temp-sym-assign (apply 'append temp-sym-map))
  856. (sym-temp-assign (apply 'append sym-temp-map))
  857. (result (make-symbol "result-tmp")))
  858. `(let (,@temp-sym-let
  859. ,result)
  860. (let ,sym-temp-let
  861. (setq ,result (progn ,@forms))
  862. (setq ,@temp-sym-assign))
  863. (let ((inhibit-quit gnus-atomic-be-safe))
  864. (setq ,@sym-temp-assign))
  865. ,result)))
  866. (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
  867. ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
  868. (defmacro gnus-atomic-setq (&rest pairs)
  869. "Similar to setq, except that the real symbols are only assigned when
  870. there are no errors. And when the real symbols are assigned, they are
  871. done so atomically. If other variables might be changed via side-effect,
  872. see gnus-atomic-progn-assign. It is safe to use gnus-atomic-setq
  873. with potentially long computations."
  874. (let ((tpairs pairs)
  875. syms)
  876. (while tpairs
  877. (push (car tpairs) syms)
  878. (setq tpairs (cddr tpairs)))
  879. `(gnus-atomic-progn-assign ,syms
  880. (setq ,@pairs))))
  881. ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
  882. ;;; Functions for saving to babyl/mail files.
  883. (eval-when-compile
  884. (if (featurep 'xemacs)
  885. ;; Don't load tm and apel XEmacs packages that provide some
  886. ;; Emacs emulating functions and variables.
  887. (let ((features features))
  888. (provide 'tm-view)
  889. (unless (fboundp 'set-alist) (defalias 'set-alist 'ignore))
  890. (require 'rmail)) ;; It requires tm-view that loads apel.
  891. (require 'rmail))
  892. (autoload 'rmail-update-summary "rmailsum"))
  893. (defvar mm-text-coding-system)
  894. (declare-function mm-append-to-file "mm-util"
  895. (start end filename &optional codesys inhibit))
  896. (declare-function rmail-swap-buffers-maybe "rmail" ())
  897. (declare-function rmail-maybe-set-message-counters "rmail" ())
  898. (declare-function rmail-count-new-messages "rmail" (&optional nomsg))
  899. (declare-function rmail-summary-exists "rmail" ())
  900. (declare-function rmail-show-message "rmail" (&optional n no-summary))
  901. ;; Macroexpansion of rmail-select-summary:
  902. (declare-function rmail-summary-displayed "rmail" ())
  903. (declare-function rmail-pop-to-buffer "rmail" (&rest args))
  904. (declare-function rmail-maybe-display-summary "rmail" ())
  905. (defun gnus-output-to-rmail (filename &optional ask)
  906. "Append the current article to an Rmail file named FILENAME.
  907. In Emacs 22 this writes Babyl format; in Emacs 23 it writes mbox unless
  908. FILENAME exists and is Babyl format."
  909. (require 'rmail)
  910. (require 'mm-util)
  911. (require 'nnmail)
  912. ;; Some of this codes is borrowed from rmailout.el.
  913. (setq filename (expand-file-name filename))
  914. ;; FIXME should we really be messing with this defcustom?
  915. ;; It is not needed for the operation of this function.
  916. (if (boundp 'rmail-default-rmail-file)
  917. (setq rmail-default-rmail-file filename) ; 22
  918. (setq rmail-default-file filename)) ; 23
  919. (let ((artbuf (current-buffer))
  920. (tmpbuf (get-buffer-create " *Gnus-output*"))
  921. ;; Babyl rmail.el defines this, mbox does not.
  922. (babyl (fboundp 'rmail-insert-rmail-file-header)))
  923. (save-excursion
  924. ;; Note that we ignore the possibility of visiting a Babyl
  925. ;; format buffer in Emacs 23, since Rmail no longer supports that.
  926. (or (get-file-buffer filename)
  927. (progn
  928. ;; In case someone wants to write to a Babyl file from Emacs 23.
  929. (when (file-exists-p filename)
  930. (setq babyl (mail-file-babyl-p filename))
  931. t))
  932. (if (or (not ask)
  933. (gnus-yes-or-no-p
  934. (concat "\"" filename "\" does not exist, create it? ")))
  935. (let ((file-buffer (create-file-buffer filename)))
  936. (with-current-buffer file-buffer
  937. (if (fboundp 'rmail-insert-rmail-file-header)
  938. (rmail-insert-rmail-file-header))
  939. (let ((require-final-newline nil)
  940. (coding-system-for-write mm-text-coding-system))
  941. (gnus-write-buffer filename)))
  942. (kill-buffer file-buffer))
  943. (error "Output file does not exist")))
  944. (set-buffer tmpbuf)
  945. (erase-buffer)
  946. (insert-buffer-substring artbuf)
  947. (if babyl
  948. (gnus-convert-article-to-rmail)
  949. ;; Non-Babyl case copied from gnus-output-to-mail.
  950. (goto-char (point-min))
  951. (if (looking-at "From ")
  952. (forward-line 1)
  953. (insert "From nobody " (current-time-string) "\n"))
  954. (let (case-fold-search)
  955. (while (re-search-forward "^From " nil t)
  956. (beginning-of-line)
  957. (insert ">"))))
  958. ;; Decide whether to append to a file or to an Emacs buffer.
  959. (let ((outbuf (get-file-buffer filename)))
  960. (if (not outbuf)
  961. (progn
  962. (unless babyl ; from gnus-output-to-mail
  963. (let ((buffer-read-only nil))
  964. (goto-char (point-max))
  965. (forward-char -2)
  966. (unless (looking-at "\n\n")
  967. (goto-char (point-max))
  968. (unless (bolp)
  969. (insert "\n"))
  970. (insert "\n"))))
  971. (let ((file-name-coding-system nnmail-pathname-coding-system))
  972. (mm-append-to-file (point-min) (point-max) filename)))
  973. ;; File has been visited, in buffer OUTBUF.
  974. (set-buffer outbuf)
  975. (let ((buffer-read-only nil)
  976. (msg (and (boundp 'rmail-current-message)
  977. (symbol-value 'rmail-current-message))))
  978. ;; If MSG is non-nil, buffer is in RMAIL mode.
  979. ;; Compare this with rmail-output-to-rmail-buffer in Emacs 23.
  980. (when msg
  981. (unless babyl
  982. (rmail-swap-buffers-maybe)
  983. (rmail-maybe-set-message-counters))
  984. (widen)
  985. (narrow-to-region (point-max) (point-max)))
  986. (insert-buffer-substring tmpbuf)
  987. (when msg
  988. (when babyl
  989. (goto-char (point-min))
  990. (widen)
  991. (search-backward "\n\^_")
  992. (narrow-to-region (point) (point-max)))
  993. (rmail-count-new-messages t)
  994. (when (rmail-summary-exists)
  995. (rmail-select-summary
  996. (rmail-update-summary)))
  997. (rmail-show-message msg))
  998. (save-buffer)))))
  999. (kill-buffer tmpbuf)))
  1000. (defun gnus-output-to-mail (filename &optional ask)
  1001. "Append the current article to a mail file named FILENAME."
  1002. (require 'nnmail)
  1003. (setq filename (expand-file-name filename))
  1004. (let ((artbuf (current-buffer))
  1005. (tmpbuf (get-buffer-create " *Gnus-output*")))
  1006. (save-excursion
  1007. ;; Create the file, if it doesn't exist.
  1008. (when (and (not (get-file-buffer filename))
  1009. (not (file-exists-p filename)))
  1010. (if (or (not ask)
  1011. (gnus-y-or-n-p
  1012. (concat "\"" filename "\" does not exist, create it? ")))
  1013. (let ((file-buffer (create-file-buffer filename)))
  1014. (with-current-buffer file-buffer
  1015. (let ((require-final-newline nil)
  1016. (coding-system-for-write mm-text-coding-system))
  1017. (gnus-write-buffer filename)))
  1018. (kill-buffer file-buffer))
  1019. (error "Output file does not exist")))
  1020. (set-buffer tmpbuf)
  1021. (erase-buffer)
  1022. (insert-buffer-substring artbuf)
  1023. (goto-char (point-min))
  1024. (if (looking-at "From ")
  1025. (forward-line 1)
  1026. (insert "From nobody " (current-time-string) "\n"))
  1027. (let (case-fold-search)
  1028. (while (re-search-forward "^From " nil t)
  1029. (beginning-of-line)
  1030. (insert ">")))
  1031. ;; Decide whether to append to a file or to an Emacs buffer.
  1032. (let ((outbuf (get-file-buffer filename)))
  1033. (if (not outbuf)
  1034. (let ((buffer-read-only nil))
  1035. (save-excursion
  1036. (goto-char (point-max))
  1037. (forward-char -2)
  1038. (unless (looking-at "\n\n")
  1039. (goto-char (point-max))
  1040. (unless (bolp)
  1041. (insert "\n"))
  1042. (insert "\n"))
  1043. (goto-char (point-max))
  1044. (let ((file-name-coding-system nnmail-pathname-coding-system))
  1045. (mm-append-to-file (point-min) (point-max) filename))))
  1046. ;; File has been visited, in buffer OUTBUF.
  1047. (set-buffer outbuf)
  1048. (let ((buffer-read-only nil))
  1049. (goto-char (point-max))
  1050. (unless (eobp)
  1051. (insert "\n"))
  1052. (insert "\n")
  1053. (insert-buffer-substring tmpbuf)))))
  1054. (kill-buffer tmpbuf)))
  1055. (defun gnus-convert-article-to-rmail ()
  1056. "Convert article in current buffer to Rmail message format."
  1057. (let ((buffer-read-only nil))
  1058. ;; Convert article directly into Babyl format.
  1059. (goto-char (point-min))
  1060. (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
  1061. (while (search-forward "\n\^_" nil t) ;single char
  1062. (replace-match "\n^_" t t)) ;2 chars: "^" and "_"
  1063. (goto-char (point-max))
  1064. (insert "\^_")))
  1065. (defun gnus-map-function (funs arg)
  1066. "Apply the result of the first function in FUNS to the second, and so on.
  1067. ARG is passed to the first function."
  1068. (while funs
  1069. (setq arg (funcall (pop funs) arg)))
  1070. arg)
  1071. (defun gnus-run-hooks (&rest funcs)
  1072. "Does the same as `run-hooks', but saves the current buffer."
  1073. (save-current-buffer
  1074. (apply 'run-hooks funcs)))
  1075. (defun gnus-run-hook-with-args (hook &rest args)
  1076. "Does the same as `run-hook-with-args', but saves the current buffer."
  1077. (save-current-buffer
  1078. (apply 'run-hook-with-args hook args)))
  1079. (defun gnus-run-mode-hooks (&rest funcs)
  1080. "Run `run-mode-hooks' if it is available, otherwise `run-hooks'.
  1081. This function saves the current buffer."
  1082. (if (fboundp 'run-mode-hooks)
  1083. (save-current-buffer (apply 'run-mode-hooks funcs))
  1084. (save-current-buffer (apply 'run-hooks funcs))))
  1085. ;;; Various
  1086. (defvar gnus-group-buffer) ; Compiler directive
  1087. (defun gnus-alive-p ()
  1088. "Say whether Gnus is running or not."
  1089. (and (boundp 'gnus-group-buffer)
  1090. (get-buffer gnus-group-buffer)
  1091. (with-current-buffer gnus-group-buffer
  1092. (eq major-mode 'gnus-group-mode))))
  1093. (defun gnus-remove-if (predicate sequence &optional hash-table-p)
  1094. "Return a copy of SEQUENCE with all items satisfying PREDICATE removed.
  1095. SEQUENCE should be a list, a vector, or a string. Returns always a list.
  1096. If HASH-TABLE-P is non-nil, regards SEQUENCE as a hash table."
  1097. (let (out)
  1098. (if hash-table-p
  1099. (mapatoms (lambda (symbol)
  1100. (unless (funcall predicate symbol)
  1101. (push symbol out)))
  1102. sequence)
  1103. (unless (listp sequence)
  1104. (setq sequence (append sequence nil)))
  1105. (while sequence
  1106. (unless (funcall predicate (car sequence))
  1107. (push (car sequence) out))
  1108. (setq sequence (cdr sequence))))
  1109. (nreverse out)))
  1110. (defun gnus-remove-if-not (predicate sequence &optional hash-table-p)
  1111. "Return a copy of SEQUENCE with all items not satisfying PREDICATE removed.
  1112. SEQUENCE should be a list, a vector, or a string. Returns always a list.
  1113. If HASH-TABLE-P is non-nil, regards SEQUENCE as a hash table."
  1114. (let (out)
  1115. (if hash-table-p
  1116. (mapatoms (lambda (symbol)
  1117. (when (funcall predicate symbol)
  1118. (push symbol out)))
  1119. sequence)
  1120. (unless (listp sequence)
  1121. (setq sequence (append sequence nil)))
  1122. (while sequence
  1123. (when (funcall predicate (car sequence))
  1124. (push (car sequence) out))
  1125. (setq sequence (cdr sequence))))
  1126. (nreverse out)))
  1127. (if (fboundp 'assq-delete-all)
  1128. (defalias 'gnus-delete-alist 'assq-delete-all)
  1129. (defun gnus-delete-alist (key alist)
  1130. "Delete from ALIST all elements whose car is KEY.
  1131. Return the modified alist."
  1132. (let (entry)
  1133. (while (setq entry (assq key alist))
  1134. (setq alist (delq entry alist)))
  1135. alist)))
  1136. (defun gnus-grep-in-list (word list)
  1137. "Find if a WORD matches any regular expression in the given LIST."
  1138. (when (and word list)
  1139. (catch 'found
  1140. (dolist (r list)
  1141. (when (string-match r word)
  1142. (throw 'found r))))))
  1143. (defmacro gnus-alist-pull (key alist &optional assoc-p)
  1144. "Modify ALIST to be without KEY."
  1145. (unless (symbolp alist)
  1146. (error "Not a symbol: %s" alist))
  1147. (let ((fun (if assoc-p 'assoc 'assq)))
  1148. `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
  1149. (defun gnus-globalify-regexp (re)
  1150. "Return a regexp that matches a whole line, if RE matches a part of it."
  1151. (concat (unless (string-match "^\\^" re) "^.*")
  1152. re
  1153. (unless (string-match "\\$$" re) ".*$")))
  1154. (defun gnus-set-window-start (&optional point)
  1155. "Set the window start to POINT, or (point) if nil."
  1156. (let ((win (gnus-get-buffer-window (current-buffer) t)))
  1157. (when win
  1158. (set-window-start win (or point (point))))))
  1159. (defun gnus-annotation-in-region-p (b e)
  1160. (if (= b e)
  1161. (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
  1162. (text-property-any b e 'gnus-undeletable t)))
  1163. (defun gnus-or (&rest elems)
  1164. "Return non-nil if any of the elements are non-nil."
  1165. (catch 'found
  1166. (while elems
  1167. (when (pop elems)
  1168. (throw 'found t)))))
  1169. (defun gnus-and (&rest elems)
  1170. "Return non-nil if all of the elements are non-nil."
  1171. (catch 'found
  1172. (while elems
  1173. (unless (pop elems)
  1174. (throw 'found nil)))
  1175. t))
  1176. ;; gnus.el requires mm-util.
  1177. (declare-function mm-disable-multibyte "mm-util")
  1178. (defun gnus-write-active-file (file hashtb &optional full-names)
  1179. ;; `coding-system-for-write' should be `raw-text' or equivalent.
  1180. (let ((coding-system-for-write nnmail-active-file-coding-system))
  1181. (with-temp-file file
  1182. ;; The buffer should be in the unibyte mode because group names
  1183. ;; are ASCII text or encoded non-ASCII text (i.e., unibyte).
  1184. (mm-disable-multibyte)
  1185. (mapatoms
  1186. (lambda (sym)
  1187. (when (and sym
  1188. (boundp sym)
  1189. (symbol-value sym))
  1190. (insert (format "%S %d %d y\n"
  1191. (if full-names
  1192. sym
  1193. (intern (gnus-group-real-name (symbol-name sym))))
  1194. (or (cdr (symbol-value sym))
  1195. (car (symbol-value sym)))
  1196. (car (symbol-value sym))))))
  1197. hashtb)
  1198. (goto-char (point-max))
  1199. (while (search-backward "\\." nil t)
  1200. (delete-char 1)))))
  1201. ;; Fixme: Why not use `with-output-to-temp-buffer'?
  1202. (defmacro gnus-with-output-to-file (file &rest body)
  1203. (let ((buffer (make-symbol "output-buffer"))
  1204. (size (make-symbol "output-buffer-size"))
  1205. (leng (make-symbol "output-buffer-length"))
  1206. (append (make-symbol "output-buffer-append")))
  1207. `(let* ((,size 131072)
  1208. (,buffer (make-string ,size 0))
  1209. (,leng 0)
  1210. (,append nil)
  1211. (standard-output
  1212. (lambda (c)
  1213. (aset ,buffer ,leng c)
  1214. (if (= ,size (setq ,leng (1+ ,leng)))
  1215. (progn (write-region ,buffer nil ,file ,append 'no-msg)
  1216. (setq ,leng 0
  1217. ,append t))))))
  1218. ,@body
  1219. (when (> ,leng 0)
  1220. (let ((coding-system-for-write 'no-conversion))
  1221. (write-region (substring ,buffer 0 ,leng) nil ,file
  1222. ,append 'no-msg))))))
  1223. (put 'gnus-with-output-to-file 'lisp-indent-function 1)
  1224. (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
  1225. (if (fboundp 'union)
  1226. (defalias 'gnus-union 'union)
  1227. (defun gnus-union (l1 l2)
  1228. "Set union of lists L1 and L2."
  1229. (cond ((null l1) l2)
  1230. ((null l2) l1)
  1231. ((equal l1 l2) l1)
  1232. (t
  1233. (or (>= (length l1) (length l2))
  1234. (setq l1 (prog1 l2 (setq l2 l1))))
  1235. (while l2
  1236. (or (member (car l2) l1)
  1237. (push (car l2) l1))
  1238. (pop l2))
  1239. l1))))
  1240. (declare-function gnus-add-text-properties "gnus"
  1241. (start end properties &optional object))
  1242. (defun gnus-add-text-properties-when
  1243. (property value start end properties &optional object)
  1244. "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
  1245. (let (point)
  1246. (while (and start
  1247. (< start end) ;; XEmacs will loop for every when start=end.
  1248. (setq point (text-property-not-all start end property value)))
  1249. (gnus-add-text-properties start point properties object)
  1250. (setq start (text-property-any point end property value)))
  1251. (if start
  1252. (gnus-add-text-properties start end properties object))))
  1253. (defun gnus-remove-text-properties-when
  1254. (property value start end properties &optional object)
  1255. "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
  1256. (let (point)
  1257. (while (and start
  1258. (< start end)
  1259. (setq point (text-property-not-all start end property value)))
  1260. (remove-text-properties start point properties object)
  1261. (setq start (text-property-any point end property value)))
  1262. (if start
  1263. (remove-text-properties start end properties object))
  1264. t))
  1265. (defun gnus-string-remove-all-properties (string)
  1266. (condition-case ()
  1267. (let ((s string))
  1268. (set-text-properties 0 (length string) nil string)
  1269. s)
  1270. (error string)))
  1271. ;; This might use `compare-strings' to reduce consing in the
  1272. ;; case-insensitive case, but it has to cope with null args.
  1273. ;; (`string-equal' uses symbol print names.)
  1274. (defun gnus-string-equal (x y)
  1275. "Like `string-equal', except it compares case-insensitively."
  1276. (and (= (length x) (length y))
  1277. (or (string-equal x y)
  1278. (string-equal (downcase x) (downcase y)))))
  1279. (defcustom gnus-use-byte-compile t
  1280. "If non-nil, byte-compile crucial run-time code.
  1281. Setting it to nil has no effect after the first time `gnus-byte-compile'
  1282. is run."
  1283. :type 'boolean
  1284. :version "22.1"
  1285. :group 'gnus-various)
  1286. (defun gnus-byte-compile (form)
  1287. "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
  1288. (if gnus-use-byte-compile
  1289. (progn
  1290. (condition-case nil
  1291. ;; Work around a bug in XEmacs 21.4
  1292. (require 'byte-optimize)
  1293. (error))
  1294. (require 'bytecomp)
  1295. (defalias 'gnus-byte-compile
  1296. (lambda (form)
  1297. (let ((byte-compile-warnings '(unresolved callargs redefine)))
  1298. (byte-compile form))))
  1299. (gnus-byte-compile form))
  1300. form))
  1301. (defun gnus-remassoc (key alist)
  1302. "Delete by side effect any elements of LIST whose car is `equal' to KEY.
  1303. The modified LIST is returned. If the first member
  1304. of LIST has a car that is `equal' to KEY, there is no way to remove it
  1305. by side effect; therefore, write `(setq foo (gnus-remassoc key foo))' to be
  1306. sure of changing the value of `foo'."
  1307. (when alist
  1308. (if (equal key (caar alist))
  1309. (cdr alist)
  1310. (setcdr alist (gnus-remassoc key (cdr alist)))
  1311. alist)))
  1312. (defun gnus-update-alist-soft (key value alist)
  1313. (if value
  1314. (cons (cons key value) (gnus-remassoc key alist))
  1315. (gnus-remassoc key alist)))
  1316. (defun gnus-create-info-command (node)
  1317. "Create a command that will go to info NODE."
  1318. `(lambda ()
  1319. (interactive)
  1320. ,(concat "Enter the info system at node " node)
  1321. (Info-goto-node ,node)
  1322. (setq gnus-info-buffer (current-buffer))
  1323. (gnus-configure-windows 'info)))
  1324. (defun gnus-not-ignore (&rest args)
  1325. t)
  1326. (defvar gnus-directory-sep-char-regexp "/"
  1327. "The regexp of directory separator character.
  1328. If you find some problem with the directory separator character, try
  1329. \"[/\\\\\]\" for some systems.")
  1330. (defun gnus-url-unhex (x)
  1331. (if (> x ?9)
  1332. (if (>= x ?a)
  1333. (+ 10 (- x ?a))
  1334. (+ 10 (- x ?A)))
  1335. (- x ?0)))
  1336. ;; Fixme: Do it like QP.
  1337. (defun gnus-url-unhex-string (str &optional allow-newlines)
  1338. "Remove %XX, embedded spaces, etc in a url.
  1339. If optional second argument ALLOW-NEWLINES is non-nil, then allow the
  1340. decoding of carriage returns and line feeds in the string, which is normally
  1341. forbidden in URL encoding."
  1342. (let ((tmp "")
  1343. (case-fold-search t))
  1344. (while (string-match "%[0-9a-f][0-9a-f]" str)
  1345. (let* ((start (match-beginning 0))
  1346. (ch1 (gnus-url-unhex (elt str (+ start 1))))
  1347. (code (+ (* 16 ch1)
  1348. (gnus-url-unhex (elt str (+ start 2))))))
  1349. (setq tmp (concat
  1350. tmp (substring str 0 start)
  1351. (cond
  1352. (allow-newlines
  1353. (char-to-string code))
  1354. ((or (= code ?\n) (= code ?\r))
  1355. " ")
  1356. (t (char-to-string code))))
  1357. str (substring str (match-end 0)))))
  1358. (setq tmp (concat tmp str))
  1359. tmp))
  1360. (defun gnus-make-predicate (spec)
  1361. "Transform SPEC into a function that can be called.
  1362. SPEC is a predicate specifier that contains stuff like `or', `and',
  1363. `not', lists and functions. The functions all take one parameter."
  1364. `(lambda (elem) ,(gnus-make-predicate-1 spec)))
  1365. (defun gnus-make-predicate-1 (spec)
  1366. (cond
  1367. ((symbolp spec)
  1368. `(,spec elem))
  1369. ((listp spec)
  1370. (if (memq (car spec) '(or and not))
  1371. `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
  1372. (error "Invalid predicate specifier: %s" spec)))))
  1373. (defun gnus-completing-read (prompt collection &optional require-match
  1374. initial-input history def)
  1375. "Call `gnus-completing-read-function'."
  1376. (funcall gnus-completing-read-function
  1377. (concat prompt (when def
  1378. (concat " (default " def ")"))
  1379. ": ")
  1380. collection require-match initial-input history def))
  1381. (defun gnus-emacs-completing-read (prompt collection &optional require-match
  1382. initial-input history def)
  1383. "Call standard `completing-read-function'."
  1384. (let ((completion-styles gnus-completion-styles))
  1385. (completing-read prompt
  1386. (if (featurep 'xemacs)
  1387. ;; Old XEmacs (at least 21.4) expect an alist,
  1388. ;; in which the car of each element is a string,
  1389. ;; for collection.
  1390. (mapcar
  1391. (lambda (elem)
  1392. (list (format "%s" (or (car-safe elem) elem))))
  1393. collection)
  1394. collection)
  1395. nil require-match initial-input history def)))
  1396. (autoload 'ido-completing-read "ido")
  1397. (defun gnus-ido-completing-read (prompt collection &optional require-match
  1398. initial-input history def)
  1399. "Call `ido-completing-read-function'."
  1400. (ido-completing-read prompt collection nil require-match
  1401. initial-input history def))
  1402. (declare-function iswitchb-read-buffer "iswitchb"
  1403. (prompt &optional default require-match
  1404. _predicate start matches-set))
  1405. (defvar iswitchb-temp-buflist)
  1406. (defvar iswitchb-mode)
  1407. (defun gnus-iswitchb-completing-read (prompt collection &optional require-match
  1408. initial-input history def)
  1409. "`iswitchb' based completing-read function."
  1410. ;; Make sure iswitchb is loaded before we let-bind its variables.
  1411. ;; If it is loaded inside the let, variables can become unbound afterwards.
  1412. (require 'iswitchb)
  1413. (let ((iswitchb-make-buflist-hook
  1414. (lambda ()
  1415. (setq iswitchb-temp-buflist
  1416. (let ((choices (append
  1417. (when initial-input (list initial-input))
  1418. (symbol-value history) collection))
  1419. filtered-choices)
  1420. (dolist (x choices)
  1421. (setq filtered-choices (adjoin x filtered-choices)))
  1422. (nreverse filtered-choices))))))
  1423. (unwind-protect
  1424. (progn
  1425. (or iswitchb-mode
  1426. (add-hook 'minibuffer-setup-hook 'iswitchb-minibuffer-setup))
  1427. (iswitchb-read-buffer prompt def require-match))
  1428. (or iswitchb-mode
  1429. (remove-hook 'minibuffer-setup-hook 'iswitchb-minibuffer-setup)))))
  1430. (defun gnus-graphic-display-p ()
  1431. (if (featurep 'xemacs)
  1432. (device-on-window-system-p)
  1433. (display-graphic-p)))
  1434. (put 'gnus-parse-without-error 'lisp-indent-function 0)
  1435. (put 'gnus-parse-without-error 'edebug-form-spec '(body))
  1436. (defmacro gnus-parse-without-error (&rest body)
  1437. "Allow continuing onto the next line even if an error occurs."
  1438. `(while (not (eobp))
  1439. (condition-case ()
  1440. (progn
  1441. ,@body
  1442. (goto-char (point-max)))
  1443. (error
  1444. (gnus-error 4 "Invalid data on line %d"
  1445. (count-lines (point-min) (point)))
  1446. (forward-line 1)))))
  1447. (defun gnus-cache-file-contents (file variable function)
  1448. "Cache the contents of FILE in VARIABLE. The contents come from FUNCTION."
  1449. (let ((time (nth 5 (file-attributes file)))
  1450. contents value)
  1451. (if (or (null (setq value (symbol-value variable)))
  1452. (not (equal (car value) file))
  1453. (not (equal (nth 1 value) time)))
  1454. (progn
  1455. (setq contents (funcall function file))
  1456. (set variable (list file time contents))
  1457. contents)
  1458. (nth 2 value))))
  1459. (defun gnus-multiple-choice (prompt choice &optional idx)
  1460. "Ask user a multiple choice question.
  1461. CHOICE is a list of the choice char and help message at IDX."
  1462. (let (tchar buf)
  1463. (save-window-excursion
  1464. (save-excursion
  1465. (while (not tchar)
  1466. (message "%s (%s): "
  1467. prompt
  1468. (concat
  1469. (mapconcat (lambda (s) (char-to-string (car s)))
  1470. choice ", ") ", ?"))
  1471. (setq tchar (read-char))
  1472. (when (not (assq tchar choice))
  1473. (setq tchar nil)
  1474. (setq buf (get-buffer-create "*Gnus Help*"))
  1475. (pop-to-buffer buf)
  1476. (fundamental-mode) ; for Emacs 20.4+
  1477. (buffer-disable-undo)
  1478. (erase-buffer)
  1479. (insert prompt ":\n\n")
  1480. (let ((max -1)
  1481. (list choice)
  1482. (alist choice)
  1483. (idx (or idx 1))
  1484. (i 0)
  1485. n width pad format)
  1486. ;; find the longest string to display
  1487. (while list
  1488. (setq n (length (nth idx (car list))))
  1489. (unless (> max n)
  1490. (setq max n))
  1491. (setq list (cdr list)))
  1492. (setq max (+ max 4)) ; %c, `:', SPACE, a SPACE at end
  1493. (setq n (/ (1- (window-width)) max)) ; items per line
  1494. (setq width (/ (1- (window-width)) n)) ; width of each item
  1495. ;; insert `n' items, each in a field of width `width'
  1496. (while alist
  1497. (if (< i n)
  1498. ()
  1499. (setq i 0)
  1500. (delete-char -1) ; the `\n' takes a char
  1501. (insert "\n"))
  1502. (setq pad (- width 3))
  1503. (setq format (concat "%c: %-" (int-to-string pad) "s"))
  1504. (insert (format format (caar alist) (nth idx (car alist))))
  1505. (setq alist (cdr alist))
  1506. (setq i (1+ i))))))))
  1507. (if (buffer-live-p buf)
  1508. (kill-buffer buf))
  1509. tchar))
  1510. (if (featurep 'emacs)
  1511. (defalias 'gnus-select-frame-set-input-focus 'select-frame-set-input-focus)
  1512. (if (fboundp 'select-frame-set-input-focus)
  1513. (defalias 'gnus-select-frame-set-input-focus 'select-frame-set-input-focus)
  1514. ;; XEmacs 21.4, SXEmacs
  1515. (defun gnus-select-frame-set-input-focus (frame)
  1516. "Select FRAME, raise it, and set input focus, if possible."
  1517. (raise-frame frame)
  1518. (select-frame frame)
  1519. (focus-frame frame))))
  1520. (defun gnus-frame-or-window-display-name (object)
  1521. "Given a frame or window, return the associated display name.
  1522. Return nil otherwise."
  1523. (if (featurep 'xemacs)
  1524. (device-connection (dfw-device object))
  1525. (if (or (framep object)
  1526. (and (windowp object)
  1527. (setq object (window-frame object))))
  1528. (let ((display (frame-parameter object 'display)))
  1529. (if (and (stringp display)
  1530. ;; Exclude invalid display names.
  1531. (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
  1532. display))
  1533. display)))))
  1534. (defvar tool-bar-mode)
  1535. (defun gnus-tool-bar-update (&rest ignore)
  1536. "Update the tool bar."
  1537. (when (and (boundp 'tool-bar-mode)
  1538. tool-bar-mode)
  1539. (let* ((args nil)
  1540. (func (cond ((featurep 'xemacs)
  1541. 'ignore)
  1542. ((fboundp 'tool-bar-update)
  1543. 'tool-bar-update)
  1544. ((fboundp 'force-window-update)
  1545. 'force-window-update)
  1546. ((fboundp 'redraw-frame)
  1547. (setq args (list (selected-frame)))
  1548. 'redraw-frame)
  1549. (t 'ignore))))
  1550. (apply func args))))
  1551. ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
  1552. (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
  1553. "Apply FUNCTION to each element of the sequences, and make a list of the results.
  1554. If there are several sequences, FUNCTION is called with that many arguments,
  1555. and mapping stops as soon as the shortest sequence runs out. With just one
  1556. sequence, this is like `mapcar'. With several, it is like the Common Lisp
  1557. `mapcar' function extended to arbitrary sequence types."
  1558. (if seqs2_n
  1559. (let* ((seqs (cons seq1 seqs2_n))
  1560. (cnt 0)
  1561. (heads (mapcar (lambda (seq)
  1562. (make-symbol (concat "head"
  1563. (int-to-string
  1564. (setq cnt (1+ cnt))))))
  1565. seqs))
  1566. (result (make-symbol "result"))
  1567. (result-tail (make-symbol "result-tail")))
  1568. `(let* ,(let* ((bindings (cons nil nil))
  1569. (heads heads))
  1570. (nconc bindings (list (list result '(cons nil nil))))
  1571. (nconc bindings (list (list result-tail result)))
  1572. (while heads
  1573. (nconc bindings (list (list (pop heads) (pop seqs)))))
  1574. (cdr bindings))
  1575. (while (and ,@heads)
  1576. (setcdr ,result-tail (cons (funcall ,function
  1577. ,@(mapcar (lambda (h) (list 'car h))
  1578. heads))
  1579. nil))
  1580. (setq ,result-tail (cdr ,result-tail)
  1581. ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
  1582. (cdr ,result)))
  1583. `(mapcar ,function ,seq1)))
  1584. (if (fboundp 'merge)
  1585. (defalias 'gnus-merge 'merge)
  1586. ;; Adapted from cl-seq.el
  1587. (defun gnus-merge (type list1 list2 pred)
  1588. "Destructively merge lists LIST1 and LIST2 to produce a new list.
  1589. Argument TYPE is for compatibility and ignored.
  1590. Ordering of the elements is preserved according to PRED, a `less-than'
  1591. predicate on the elements."
  1592. (let ((res nil))
  1593. (while (and list1 list2)
  1594. (if (funcall pred (car list2) (car list1))
  1595. (push (pop list2) res)
  1596. (push (pop list1) res)))
  1597. (nconc (nreverse res) list1 list2))))
  1598. (defvar xemacs-codename)
  1599. (defvar sxemacs-codename)
  1600. (defvar emacs-program-version)
  1601. (defun gnus-emacs-version ()
  1602. "Stringified Emacs version."
  1603. (let* ((lst (if (listp gnus-user-agent)
  1604. gnus-user-agent
  1605. '(gnus emacs type)))
  1606. (system-v (cond ((memq 'config lst)
  1607. system-configuration)
  1608. ((memq 'type lst)
  1609. (symbol-name system-type))
  1610. (t nil)))
  1611. codename emacsname)
  1612. (cond ((featurep 'sxemacs)
  1613. (setq emacsname "SXEmacs"
  1614. codename sxemacs-codename))
  1615. ((featurep 'xemacs)
  1616. (setq emacsname "XEmacs"
  1617. codename xemacs-codename))
  1618. (t
  1619. (setq emacsname "Emacs")))
  1620. (cond
  1621. ((not (memq 'emacs lst))
  1622. nil)
  1623. ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
  1624. ;; Emacs:
  1625. (concat "Emacs/" (match-string 1 emacs-version)
  1626. (if system-v
  1627. (concat " (" system-v ")")
  1628. "")))
  1629. ((or (featurep 'sxemacs) (featurep 'xemacs))
  1630. ;; XEmacs or SXEmacs:
  1631. (concat emacsname "/" emacs-program-version
  1632. (let (plst)
  1633. (when (memq 'codename lst)
  1634. (push codename plst))
  1635. (when system-v
  1636. (push system-v plst))
  1637. (unless (featurep 'mule)
  1638. (push "no MULE" plst))
  1639. (when (> (length plst) 0)
  1640. (concat
  1641. " (" (mapconcat 'identity (reverse plst) ", ") ")")))))
  1642. (t emacs-version))))
  1643. (defun gnus-rename-file (old-path new-path &optional trim)
  1644. "Rename OLD-PATH as NEW-PATH. If TRIM, recursively delete
  1645. empty directories from OLD-PATH."
  1646. (when (file-exists-p old-path)
  1647. (let* ((old-dir (file-name-directory old-path))
  1648. (old-name (file-name-nondirectory old-path))
  1649. (new-dir (file-name-directory new-path))
  1650. (new-name (file-name-nondirectory new-path))
  1651. temp)
  1652. (gnus-make-directory new-dir)
  1653. (rename-file old-path new-path t)
  1654. (when trim
  1655. (while (progn (setq temp (directory-files old-dir))
  1656. (while (member (car temp) '("." ".."))
  1657. (setq temp (cdr temp)))
  1658. (= (length temp) 0))
  1659. (delete-directory old-dir)
  1660. (setq old-dir (file-name-as-directory
  1661. (file-truename
  1662. (concat old-dir "..")))))))))
  1663. (defun gnus-set-file-modes (filename mode)
  1664. "Wrapper for set-file-modes."
  1665. (ignore-errors
  1666. (set-file-modes filename mode)))
  1667. (if (fboundp 'set-process-query-on-exit-flag)
  1668. (defalias 'gnus-set-process-query-on-exit-flag
  1669. 'set-process-query-on-exit-flag)
  1670. (defalias 'gnus-set-process-query-on-exit-flag
  1671. 'process-kill-without-query))
  1672. (defalias 'gnus-read-shell-command
  1673. (if (fboundp 'read-shell-command) 'read-shell-command 'read-string))
  1674. (defmacro gnus-put-display-table (range value display-table)
  1675. "Set the value for char RANGE to VALUE in DISPLAY-TABLE. "
  1676. (if (featurep 'xemacs)
  1677. (progn
  1678. `(if (fboundp 'put-display-table)
  1679. (put-display-table ,range ,value ,display-table)
  1680. (if (sequencep ,display-table)
  1681. (aset ,display-table ,range ,value)
  1682. (put-char-table ,range ,value ,display-table))))
  1683. `(aset ,display-table ,range ,value)))
  1684. (defmacro gnus-get-display-table (character display-table)
  1685. "Find value for CHARACTER in DISPLAY-TABLE. "
  1686. (if (featurep 'xemacs)
  1687. `(if (fboundp 'get-display-table)
  1688. (get-display-table ,character ,display-table)
  1689. (if (sequencep ,display-table)
  1690. (aref ,display-table ,character)
  1691. (get-char-table ,character ,display-table)))
  1692. `(aref ,display-table ,character)))
  1693. (declare-function image-size "image.c" (spec &optional pixels frame))
  1694. (defun gnus-rescale-image (image size)
  1695. "Rescale IMAGE to SIZE if possible.
  1696. SIZE is in format (WIDTH . HEIGHT). Return a new image.
  1697. Sizes are in pixels."
  1698. (if (or (not (fboundp 'imagemagick-types))
  1699. (not (get-buffer-window (current-buffer))))
  1700. image
  1701. (let ((new-width (car size))
  1702. (new-height (cdr size)))
  1703. (when (> (cdr (image-size image t)) new-height)
  1704. (setq image (or (create-image (plist-get (cdr image) :data) 'imagemagick t
  1705. :height new-height)
  1706. image)))
  1707. (when (> (car (image-size image t)) new-width)
  1708. (setq image (or
  1709. (create-image (plist-get (cdr image) :data) 'imagemagick t
  1710. :width new-width)
  1711. image)))
  1712. image)))
  1713. (eval-when-compile (require 'gmm-utils))
  1714. (defun gnus-recursive-directory-files (dir)
  1715. "Return all regular files below DIR.
  1716. The first found will be returned if a file has hard or symbolic links."
  1717. (let (files attr attrs)
  1718. (gmm-labels
  1719. ((fn (directory)
  1720. (dolist (file (directory-files directory t))
  1721. (setq attr (file-attributes (file-truename file)))
  1722. (when (and (not (member attr attrs))
  1723. (not (member (file-name-nondirectory file)
  1724. '("." "..")))
  1725. (file-readable-p file))
  1726. (push attr attrs)
  1727. (cond ((file-regular-p file)
  1728. (push file files))
  1729. ((file-directory-p file)
  1730. (fn file)))))))
  1731. (fn dir))
  1732. files))
  1733. (defun gnus-list-memq-of-list (elements list)
  1734. "Return non-nil if any of the members of ELEMENTS are in LIST."
  1735. (let ((found nil))
  1736. (dolist (elem elements)
  1737. (setq found (or found
  1738. (memq elem list))))
  1739. found))
  1740. (eval-and-compile
  1741. (cond
  1742. ((fboundp 'match-substitute-replacement)
  1743. (defalias 'gnus-match-substitute-replacement 'match-substitute-replacement))
  1744. (t
  1745. (defun gnus-match-substitute-replacement (replacement &optional fixedcase literal string subexp)
  1746. "Return REPLACEMENT as it will be inserted by `replace-match'.
  1747. In other words, all back-references in the form `\\&' and `\\N'
  1748. are substituted with actual strings matched by the last search.
  1749. Optional FIXEDCASE, LITERAL, STRING and SUBEXP have the same
  1750. meaning as for `replace-match'.
  1751. This is the definition of match-substitute-replacement in subr.el from GNU Emacs."
  1752. (let ((match (match-string 0 string)))
  1753. (save-match-data
  1754. (set-match-data (mapcar (lambda (x)
  1755. (if (numberp x)
  1756. (- x (match-beginning 0))
  1757. x))
  1758. (match-data t)))
  1759. (replace-match replacement fixedcase literal match subexp)))))))
  1760. (if (fboundp 'string-match-p)
  1761. (defalias 'gnus-string-match-p 'string-match-p)
  1762. (defsubst gnus-string-match-p (regexp string &optional start)
  1763. "\
  1764. Same as `string-match' except this function does not change the match data."
  1765. (save-match-data
  1766. (string-match regexp string start))))
  1767. (if (fboundp 'string-prefix-p)
  1768. (defalias 'gnus-string-prefix-p 'string-prefix-p)
  1769. (defun gnus-string-prefix-p (str1 str2 &optional ignore-case)
  1770. "Return non-nil if STR1 is a prefix of STR2.
  1771. If IGNORE-CASE is non-nil, the comparison is done without paying attention
  1772. to case differences."
  1773. (and (<= (length str1) (length str2))
  1774. (let ((prefix (substring str2 0 (length str1))))
  1775. (if ignore-case
  1776. (string-equal (downcase str1) (downcase prefix))
  1777. (string-equal str1 prefix))))))
  1778. (if (fboundp 'format-message)
  1779. (defalias 'gnus-format-message 'format-message)
  1780. ;; for Emacs < 25, and XEmacs, don't worry about quote translation.
  1781. (defalias 'gnus-format-message 'format))
  1782. ;; Simple check: can be a macro but this way, although slow, it's really clear.
  1783. ;; We don't use `bound-and-true-p' because it's not in XEmacs.
  1784. (defun gnus-bound-and-true-p (sym)
  1785. (and (boundp sym) (symbol-value sym)))
  1786. (if (fboundp 'timer--function)
  1787. (defalias 'gnus-timer--function 'timer--function)
  1788. (defun gnus-timer--function (timer)
  1789. (elt timer 5)))
  1790. (provide 'gnus-util)
  1791. ;;; gnus-util.el ends here