OSDN Git Service

0207e88d0f80c13f1eb1a9ed1bb9e4ccc745113e
[howm/howm.git] / howm-mode.el
1 ;;; howm-mode.el --- Wiki-like note-taking tool
2 ;;; Copyright (C) 2002, 2003, 2004, 2005-2022
3 ;;;   HIRAOKA Kazuyuki <khi@users.osdn.me>
4 ;;;
5 ;;; This program is free software; you can redistribute it and/or modify
6 ;;; it under the terms of the GNU General Public License as published by
7 ;;; the Free Software Foundation; either version 1, or (at your option)
8 ;;; any later version.
9 ;;;
10 ;;; This program 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 ;;;
15 ;;; The GNU General Public License is available by anonymouse ftp from
16 ;;; prep.ai.mit.edu in pub/gnu/COPYING.  Alternately, you can write to
17 ;;; the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,
18 ;;; USA.
19 ;;;--------------------------------------------------------------------
20
21 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
22 ;; Backward compatibility
23
24 ;; (require 'howm-mode) in .emacs is obsolete. Use (require 'howm) instead.
25
26 ;; This must be earlier than (require 'howm-common), because
27 ;; howm-common needs cl, and (require 'cl) should be written in howm.el.
28 (when (not (featurep 'howm))
29   (message "Warning: Requiring howm-mode is obsolete. Require howm instead.")
30 ;;   (beep)
31 ;;   (sit-for 1)
32   (require 'howm))
33
34 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
35 ;; Require
36
37 (provide 'howm-mode)
38 (require 'howm)
39
40 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
41 ;; Customize
42
43 ;;; --- level 1 ---
44
45 ;; You can easily modify them.
46
47 (howm-defvar-risky howm-template
48   (concat howm-view-title-header " %title%cursor\n%date %file\n\n")
49   "Contents of new file. %xxx are replaced with specified items.
50 If it is a list, <n>-th one is used when you type C-u <n> M-x howm-create.
51 If it is a function, it is called to get template string with the argument <n>.")
52 (defvar howm-keyword-header "<<<"
53   "Header string for declaration of keyword (implicit link).")
54 (defvar howm-ref-header ">>>"
55   "Header string for explicit link.")
56 (defvar howm-lighter " howm"
57   "Mode line for howm-mode")
58
59 (defvar howm-inhibit-title-file-match t
60   "If non-nil, inhibit howm-list-title when search string matches file name")
61 (defvar howm-list-all-title nil) ;; obsolete [2003-11-30]
62 (defvar howm-list-recent-title nil) ;; obsolete [2003-11-30]
63
64 (defvar howm-default-key-table
65   '(
66     ;; ("key" func list-mode-p global-p)
67     ("r" howm-refresh)
68     ("l" howm-list-recent t t)
69     ("a" howm-list-all t t)
70     ("g" howm-list-grep t t)
71     ("s" howm-list-grep-fixed t t)
72     ("m" howm-list-migemo t t)
73     ("t" howm-list-todo t t)
74     ("y" howm-list-schedule t t)
75     ("b" howm-list-buffers t t)
76     ("x" howm-list-mark-ring t t)
77     ("o" howm-occur t t)
78     ("c" howm-create t t)
79     ("e" howm-remember t t)
80     ("," howm-menu t t)
81     ("." howm-find-today nil t)
82     (":" howm-find-yesterday nil t)
83     ("A" howm-list-around)
84     ("h" howm-history nil t)
85     ("D" howm-dup)
86     ("i" howm-insert-keyword nil t)
87     ("d" howm-insert-date nil t)
88     ("T" howm-insert-dtime nil t)
89     ("K" howm-keyword-to-kill-ring t t)
90     ("n" action-lock-goto-next-link)
91     ("p" action-lock-goto-previous-link)
92     ("Q" howm-kill-all t t)
93     (" " howm-toggle-buffer nil t)
94     ("N" howm-next-memo)
95     ("P" howm-previous-memo)
96     ("H" howm-first-memo)
97     ("L" howm-last-memo)
98     ("C" howm-create-here nil t)
99     ("I" howm-create-interactively nil t)
100     ("w" howm-random-walk nil t)
101     ("M" howm-open-named-file t t)
102     )
103   "List of (key function list-mode-p global-p).
104 `howm-prefix' + this key is real stroke.
105 If optional argument list-mode-p is non-nil,
106 same key is also available in view mode.
107 It is further registered globally if global-p is non-nil."
108   )
109
110 (howm-defvar-risky howm-migemo-client nil
111   "Command name of migemo-client.
112 Example of cmigemo:
113   (setq howm-migemo-client '((type . cmigemo) (command . \"cmigemo\")))
114 Example of migemo-client (obsolete):
115   (setq howm-migemo-client \"migemo-client\")
116 See also `howm-migemo-client-option`")
117 (howm-defvar-risky howm-migemo-client-option nil
118   "List of option for migemo-client.
119 Example of cmigemo:
120   (setq howm-migemo-client-option
121         '(\"-q\" \"-d\" \"/usr/share/cmigemo/utf-8/migemo-dict\"))
122 Example of migemo-client (obsolete):
123   (setq howm-migemo-client-option '(\"-H\" \"::1\")
124 See also `howm-migemo-client`")
125
126 ;;; --- level 2 ---
127
128 ;; Be careful to keep consistency.
129
130 (howm-defvar-risky howm-keyword/ref-regexp-format
131   "\\(%s\\)[ \t]*\\([^ \t\r\n].*\\)")
132 (howm-defvar-risky howm-keyword-format
133   (format "%s %%s" howm-keyword-header)
134   "Format for declaration of keyword. See `format'.")
135 (howm-defvar-risky howm-keyword-regexp
136   (format howm-keyword/ref-regexp-format (regexp-quote howm-keyword-header)))
137 (howm-defvar-risky howm-keyword-regexp-hilit-pos 1)
138 (howm-defvar-risky howm-keyword-regexp-pos 2)
139 (howm-defvar-risky howm-ref-regexp
140   (format howm-keyword/ref-regexp-format (regexp-quote howm-ref-header))
141   "Regexp for explicit link.")
142 (howm-defvar-risky howm-ref-regexp-hilit-pos 0
143   "Position of search string in `howm-ref-regexp'")
144 (howm-defvar-risky howm-ref-regexp-pos 2
145   "Position of search string in `howm-ref-regexp'")
146 (howm-defvar-risky howm-wiki-regexp "\\[\\[\\([^]\r\n]+\\)\\]\\]"
147   "Regexp for explicit link.")
148 (howm-defvar-risky howm-wiki-regexp-hilit-pos 1
149   "Position of hilight in `howm-wiki-regexp'")
150 (howm-defvar-risky howm-wiki-regexp-pos 1
151   "Position of search string in `howm-wiki-regexp'")
152 (howm-defvar-risky howm-wiki-format "[[%s]]"
153   "Format for declaration of wiki word. See `format'.")
154
155 (howm-defvar-risky howm-template-rules
156   '(("%title" . howm-template-title)
157     ("%date" . howm-template-date)
158     ("%file" . howm-template-previous-file)
159     ("%cursor" . howm-template-cursor))) ;; Cursor must be the last rule.
160 (defvar howm-template-date-format howm-dtime-format
161   "%date is replaced with `howm-template-date-format'
162 in `howm-template'. See `format-time-string'")
163 (defvar howm-template-file-format (concat howm-ref-header " %s")
164   "%file is replaced with `homw-template-file-format'
165 in `howm-template'. %s is replaced with name of last file. See `format'.")
166
167 ;;; --- level 3 ---
168
169 ;; As you like.
170
171 (defun howm-action-lock-general (command regexp pos
172                                          &optional hilit-pos
173                                          &rest options)
174   (list regexp
175         `(lambda (&optional dummy)
176            (let ((s (match-string-no-properties ,pos)))
177 ;;             (when howm-keyword-case-fold-search
178 ;;               (setq s (downcase s)))
179              (,command s ,@options)))
180         (or hilit-pos 0)
181         t))
182
183 (defun howm-action-lock-search (regexp
184                                 pos
185                                 &optional hilit-pos create-p open-unique-p)
186   (howm-action-lock-general 'howm-keyword-search
187                             regexp pos hilit-pos create-p open-unique-p))
188 (defun howm-action-lock-related (regexp pos hilit-pos)
189   (howm-action-lock-general 'howm-list-related regexp pos hilit-pos))
190
191 (defun howm-action-lock-date-rule ()
192   (action-lock-general 'howm-action-lock-date howm-date-regexp 0 0))
193
194 (defun howm-action-lock-quote-keyword (keyword)
195   (let ((q (regexp-quote keyword)))
196     ;; when a regexp is specified, leave unmatched keywords.
197     (if (and (stringp howm-check-word-break)
198              (not (string-match howm-check-word-break keyword)))
199         q
200       ;; add word break checks
201       (concat "\\b" q "\\b"))))
202
203 (defun howm-action-lock-setup ()
204   (setq action-lock-case-fold-search howm-keyword-case-fold-search)
205   (action-lock-mode t)
206   (let* ((date-al (action-lock-date "{_}" howm-dtime-format)))
207     ;; override the rule in action-lock.el
208     (action-lock-add-rules (list date-al) t))
209   (let* ((ks (howm-keyword-for-goto))
210          (r (mapconcat (if howm-check-word-break
211                            #'howm-action-lock-quote-keyword
212                          #'regexp-quote)
213                        ks "\\|"))
214          ;; The following optimization causes an error
215          ;; "Variable binding depth exceeds max-specpdl-size".
216          ;; (r (cond ((stringp howm-check-word-break)
217          ;;           (mapconcat #'howm-action-lock-quote-keyword ks "\\|"))
218          ;;          (t
219          ;;           (regexp-opt ks (and howm-check-word-break 'word)))))
220          (wiki (howm-action-lock-search howm-wiki-regexp
221                                         howm-wiki-regexp-pos
222                                         howm-wiki-regexp-hilit-pos
223                                         t))
224          (explicit (howm-action-lock-search howm-ref-regexp
225                                             howm-ref-regexp-pos
226                                             howm-ref-regexp-hilit-pos))
227          (implicit (howm-action-lock-search r 0))
228          (rev (howm-action-lock-related howm-keyword-regexp
229                                         howm-keyword-regexp-pos
230                                         howm-keyword-regexp-hilit-pos))
231          (date (howm-action-lock-date-rule))
232          (done (howm-action-lock-reminder-done-rule))
233          (all `(
234                 ,explicit
235                 ,rev
236                 ,@(if ks (list implicit) nil)
237                 ,wiki
238                 ,@(if (howm-menu-p) nil (list date done))
239                 ))
240          )
241     ;; don't override the rule in action-lock.el
242     ;; esp. http://xxx should call browser even if "<<< http" exists
243     (action-lock-add-rules all)))
244
245 (defun howm-file-name (&optional time)
246   (format-time-string howm-file-name-format
247                       (or time (current-time))))
248
249 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
250 ;; Definitions
251
252 (define-minor-mode howm-mode
253   "With no argument, this command toggles the mode. 
254 Non-null prefix argument turns on the mode.
255 Null prefix argument turns off the mode.
256
257 When the mode is enabled, underlines are drawn on texts which match
258 to titles of other files. Typing \\[action-lock-magic-return] there,
259 you can jump to the corresponding file.
260
261 key     binding
262 ---     -------
263 \\[action-lock-magic-return]    Follow link
264 \\[howm-refresh]        Refresh buffer
265 \\[howm-list-all]       List all files
266 \\[howm-list-grep]      Search (grep)
267 \\[howm-create] Create new file
268 \\[howm-dup]    Duplicate current file
269 \\[howm-insert-keyword] Insert keyword
270 \\[howm-insert-date]    Insert date
271 \\[howm-insert-dtime]   Insert date with time
272 \\[howm-keyword-to-kill-ring]   Copy current keyword to kill ring
273 \\[action-lock-goto-next-link]  Go to next link
274 \\[action-lock-goto-previous-link]      Go to previous link
275 \\[howm-next-memo]      Go to next entry in current buffer
276 \\[howm-previous-memo]  Go to previous entry in current buffer
277 \\[howm-first-memo]     Go to first entry in current buffer
278 \\[howm-last-memo]      Go to last entry in current buffer
279 \\[howm-create-here]    Add new entry to current buffer
280 \\[howm-create-interactively]   Create new file interactively (not recommended)
281 \\[howm-random-walk]    Browse random entries automtically
282 "
283   :init-value nil ;; default = off
284   :lighter howm-lighter ;; mode-line
285   :keymap (mapcar (lambda (entry)
286                     (let ((k (car entry))
287                           (f (cadr entry)))
288                       (cons (concat howm-prefix k) f)))
289                   howm-default-key-table)
290   (if howm-mode
291       (howm-initialize-buffer)
292     (howm-restore-buffer)))
293
294 (defun howm-set-keymap ()
295   (mapc (lambda (entry)
296           (let* ((k (car entry))
297                  (f (cadr entry))
298                  (list-mode-p (cl-caddr entry))
299                  (global-p (cl-cadddr entry))
300                  (pk (concat howm-prefix k)))
301             (define-key howm-mode-map pk f)
302             (when list-mode-p
303               (mapc (lambda (m)
304                       (define-key m k f)
305                       (define-key m pk f))
306                     (list howm-view-summary-mode-map
307                           howm-view-contents-mode-map)))
308             (when global-p
309               (define-key global-map pk f))))
310         howm-default-key-table)
311   (define-key howm-mode-map "\C-x\C-s" 'howm-save-buffer))
312 (howm-set-keymap)
313
314 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
315 ;; Main functions
316
317 (defun howm-refresh ()
318   (interactive)
319   (if (howm-menu-p)
320       (howm-menu-refresh)
321     (howm-initialize-buffer)))
322
323 (defun howm-initialize-buffer ()
324   (interactive)
325   (when (not howm-mode)
326     (error "Not howm-mode"))
327   (howm-message-time "init-buf"
328     (save-restriction
329       (widen)
330       (howm-set-configuration-for-major-mode major-mode)
331       (howm-action-lock-setup)
332       (howm-mode-add-font-lock)
333       (howm-reminder-add-font-lock)
334       (cheat-font-lock-fontify)
335       ;; make-local-hook is obsolete for emacs >= 21.1.
336       (howm-funcall-if-defined (make-local-hook 'after-save-hook))
337       (add-hook 'after-save-hook 'howm-after-save t t))))
338
339 (defun howm-after-save ()
340   (when howm-mode
341     (howm-keyword-add-current-buffer)
342     (when howm-refresh-after-save
343       (howm-initialize-buffer))
344     (when (and howm-menu-refresh-after-save
345                (> howm-menu-expiry-hours 0))
346       (howm-menu-refresh-background))
347     (run-hooks 'howm-after-save-hook)))
348
349 (defun howm-restore-buffer ()
350   (action-lock-mode 0))
351
352 (defun howm-list-all ()
353   (interactive)
354   (howm-set-command 'howm-list-all)
355   (howm-normalize-show "" (howm-all-items))
356   ;; for backward compatibility
357   (cond ((howm-list-title-p) t)  ;; already done in howm-normalize-show
358         (howm-list-all-title (howm-list-title-internal))))
359
360 (defun howm-all-items ()
361   "Returns list of all items in the first search path."
362   (howm-folder-items (car (howm-search-path)) t))
363
364 (defun howm-list-recent (&optional days)
365   (interactive "P")
366   (howm-set-command 'howm-list-recent)
367   (let* ((d (or days howm-list-recent-days))
368          (now (current-time))
369          (from (howm-days-before now d))
370          (item-list (howm-folder-items howm-directory t)))
371     (howm-normalize-show "" (howm-filter-items-by-mtime item-list from now))
372     ;; clean me [2003-11-30]
373     (cond ((howm-list-title-p) t)  ;; already done in howm-normalize-show
374           (howm-list-recent-title (howm-list-title-internal))
375           ((not days) (howm-view-summary-to-contents)))))
376
377 ;; clean me: direct access to howm-view-* is undesirable.
378
379 (defvar howm-list-title-previous nil
380   "For internal use")
381 (make-variable-buffer-local 'howm-list-title-previous)
382 (defun howm-list-title-put-previous (&optional item-list)
383   (when howm-list-title-undo
384     (setq howm-list-title-previous (or item-list (howm-view-item-list)))))
385 (defun howm-list-title-clear-previous ()
386   (setq howm-list-title-previous nil))
387 (defun howm-list-title-get-previous ()
388   (if howm-list-title-undo
389       (let ((prev howm-list-title-previous))
390         (setq howm-list-title-previous nil)
391         (howm-view-summary-rebuild prev))
392     (error "Undo is not enabled.")))
393 (defun howm-list-title-regexp ()
394   (or howm-list-title-regexp (howm-view-title-regexp-grep)))
395 (defalias 'howm-list-title 'howm-list-toggle-title) ;; backward compatibility
396 (defun howm-list-toggle-title (&optional undo)
397   (interactive "P")
398   (if (or undo howm-list-title-previous)
399       (howm-list-title-get-previous)
400     (howm-list-title-internal)))
401 (defun howm-list-title-internal ()
402   (let ((b (current-buffer)))
403     (howm-list-title-put-previous)
404     (howm-view-list-title (howm-list-title-regexp))
405     ;;       (howm-view-filter-by-contents (howm-list-title-regexp))
406     (let ((c (current-buffer)))
407       (when (not (eq b c))
408         (set-buffer b)
409         (howm-view-kill-buffer)
410         (switch-to-buffer c)
411         (howm-view-summary-check t)))))
412
413 (defun howm-list-title-p ()
414   (let ((a (howm-get-value howm-list-title)))
415     (cond ((null a) nil) ;; I know this is redundant.
416           ((listp a) (member (howm-command) a))
417           (t a))))
418
419 (defun howm-days-after (ti days &optional hours)
420   (let* ((ne (howm-decode-time ti))
421          (hour-pos 2)
422          (day-pos 3)
423          (nh (nth hour-pos ne))
424          (nd (nth day-pos ne)))
425     (setf (nth hour-pos ne) (+ nh (or hours 0)))
426     (setf (nth day-pos ne) (+ nd days))
427     (apply #'encode-time ne)))
428
429 (defun howm-days-before (ti days)
430   (howm-days-after ti (- days)))
431
432 (defun howm-list-grep (&optional completion-p)
433   (interactive "P")
434   (howm-set-command 'howm-list-grep)
435   (howm-list-grep-general completion-p))
436
437 (defun howm-list-grep-fixed ()
438   (interactive)
439   (howm-set-command 'howm-list-grep-fixed)
440   (howm-list-grep-general t))
441
442 (defun howm-list-grep-general (&optional completion-p)
443   (let ((regexp (howm-iigrep completion-p)))
444     (when completion-p  ;; Goto link works only for fixed string at now.
445       (howm-write-history regexp))
446     (howm-search regexp completion-p)))
447
448 (defun howm-iigrep (completion-p)
449   (iigrep-with-grep (howm-iigrep-command-for-pattern completion-p)
450       howm-iigrep-show-what
451     (if completion-p
452         (howm-completing-read-keyword)
453       (read-from-minibuffer "Search all (grep): "))))
454
455 (defmacro howm-iigrep-command-for-pattern (&optional fixed-p converter)
456   ;; use macro due to dynamic binding. Sigh...
457   `(and howm-view-use-grep
458         (lambda (str)
459           (let* ((pattern (funcall (or ,converter #'identity) str))
460                  (trio (howm-real-grep-single-command
461                         pattern (list howm-directory) ,fixed-p))
462                  (com (car trio))
463                  (args (cl-second trio))
464                  (fs (cl-third trio)))
465             (append (list com) (cons "-I" args) fs)))))
466
467 (defun howm-search (regexp fixed-p &optional emacs-regexp filter bufname)
468   (if (string= regexp "")
469       (howm-list-all)
470     (howm-message-time "search"
471       (let* ((trio (howm-call-view-search-internal regexp fixed-p emacs-regexp))
472              (kw (car trio))
473              (name (or bufname (cadr trio)))
474              (items (cl-caddr trio)))
475         (when filter
476           (setq items (funcall filter items)))
477         (howm-normalize-show name items (or emacs-regexp regexp) nil nil kw)
478         (howm-record-view-window-configuration)))))
479
480 (defvar *howm-view-window-configuration* nil
481   "For internal use")
482 (defun howm-view-window-configuration ()
483   *howm-view-window-configuration*)
484 (defun howm-set-view-window-configuration (conf)
485   (setq *howm-view-window-configuration* conf))
486 (defun howm-record-view-window-configuration ()
487   (howm-set-view-window-configuration (current-window-configuration)))
488 (defun howm-restore-view-window-configuration ()
489   (set-window-configuration (howm-view-window-configuration)))
490 (defun howm-return-to-list ()
491   (interactive)
492   (howm-restore-view-window-configuration))
493
494 (defun howm-call-view-search-internal (regexp fixed-p &optional emacs-regexp)
495   (let ((hilit (if emacs-regexp
496                    `((,emacs-regexp . howm-view-hilit-face))
497                  nil)))
498     (howm-view-search-folder-internal regexp (howm-search-path-folder)
499                                       nil nil fixed-p hilit)))
500
501 (defun howm-list-migemo (&optional completion-p)
502   (interactive "P")
503   (howm-set-command 'howm-list-migemo)
504   (if completion-p
505       (howm-list-grep t)
506     (let* ((roma (howm-iigrep-migemo))
507            (e-reg (howm-migemo-get-pattern roma "emacs"))
508            (g-reg (if howm-view-use-grep
509                       (howm-migemo-get-pattern roma "egrep")
510                     e-reg)))
511       (if (and e-reg g-reg)
512           (howm-search g-reg nil e-reg nil roma)
513         (message "No response from migemo-client.")))))
514
515 (defun howm-iigrep-migemo ()
516   (let* ((converter (lambda (yomi) (howm-migemo-get-pattern yomi "egrep")))
517          (command-for-pattern (howm-iigrep-command-for-pattern nil converter))
518          (show-what (if (eq howm-iigrep-migemo-show-what 'inherit)
519                         howm-iigrep-show-what
520                       howm-iigrep-migemo-show-what)))
521     (iigrep-with-grep command-for-pattern show-what
522       (read-from-minibuffer "Search all (migemo): "))))
523
524 (defun howm-migemo-get-pattern (roma type)
525   (when (and (null howm-migemo-client) (not howm-view-use-grep))
526     (require 'migemo))
527   (cl-labels ((ref (key) (cdr (assoc key howm-migemo-client))))
528     (cond ((and (featurep 'migemo) (string= type "emacs"))
529            (howm-funcall-if-defined (migemo-get-pattern roma)))
530           ((or (null howm-migemo-client) (stringp howm-migemo-client))
531            (car (howm-call-process (or howm-migemo-client "migemo-client")
532                                    `(,@howm-migemo-client-option "-t" ,type ,roma)
533                                    0)))
534           ((eq (ref 'type) 'cmigemo)
535            (car (howm-call-process (ref 'command)
536                                    `(,@howm-migemo-client-option
537                                      ,@(and (string= type "emacs") '("-e"))
538                                      "-w" ,roma))))
539           (t (error "Invalid howm-migemo-client: %s" howm-migemo-client)))))
540
541 (defun howm-normalize-oldp ()
542   howm-list-normalizer)
543
544 ;; ;; generate conv in howm-normalizer-pair
545 ;; (let ((methods '("random" "name" "numerical-name" "date" "reverse-date"
546 ;;                  "summary" "reminder" "mtime" "reverse")))
547 ;;   (mapcar (lambda (m)
548 ;;             (let ((command
549 ;;                    (howm-get-symbol nil "howm-view-sort-by-" m))
550 ;;                   (internal
551 ;;                    (howm-get-symbol nil "howm-sort-items-by-" m)))
552 ;;               (cons command internal)))
553 ;;           methods))
554
555 (defun howm-normalizer-pair ()
556   (let* ((old howm-list-normalizer)
557          (new howm-normalizer)
558          (conv '((howm-view-sort-by-random . howm-sort-items-by-random)
559                  (howm-view-sort-by-name . howm-sort-items-by-name)
560                  (howm-view-sort-by-numerical-name
561                   . howm-sort-items-by-numerical-name)
562                  (howm-view-sort-by-date . howm-sort-items-by-date)
563                  (howm-view-sort-by-reverse-date
564                   . howm-sort-items-by-reverse-date)
565                  (howm-view-sort-by-summary . howm-sort-items-by-summary)
566                  (howm-view-sort-by-reminder . howm-sort-items-by-reminder)
567                  (howm-view-sort-by-mtime . howm-sort-items-by-mtime)
568                  (howm-view-sort-by-reverse . howm-sort-items-by-reverse)))
569          (p (assoc old conv))
570          (q (assoc new conv)))
571     (when q
572       (message "Warning: %s is wrong for howm-normalizer. Use %s." (car q) (cdr q))
573       (setq new (cdr q)))
574     (cond ((null old) (cons old new))
575           (p (cons nil (cdr p)))
576           (t (cons old #'identity)))))
577
578 (defmacro howm-with-normalizer (&rest body)
579   (declare (indent 0))
580   (let ((g (cl-gensym)))
581     `(progn
582        (when (howm-normalize-oldp)
583          (message
584           "Warning: howm-list-normalizer is obsolete. Use howm-normalizer."))
585        (let* ((,g (howm-normalizer-pair))
586               (howm-list-normalizer (car ,g))
587               (howm-normalizer (cdr ,g)))
588          ,@body))))
589
590 (defun howm-normalize-show (name item-list
591                                  &optional keyword comefrom-regexp no-list-title
592                                  fl-keywords)
593   ;; comefrom-regexp and no-list-title are never used now. [2009-07-23]
594   (howm-with-normalizer
595     (if (howm-normalize-oldp)
596         ;; for backward compatibility.
597         (progn
598           (howm-view-summary name item-list fl-keywords)
599           (howm-list-normalize-old keyword comefrom-regexp no-list-title))
600       (let* ((r (howm-normalize item-list keyword
601                                 comefrom-regexp no-list-title)))
602         (howm-call-view-summary name (cdr r) fl-keywords)
603         (car r)))))
604
605 (defun howm-call-view-summary (name item-list-pair fl-keywords)
606   (let ((orig (car item-list-pair))
607         (entitled (cdr item-list-pair)))
608     (howm-view-summary name (or entitled orig) fl-keywords)
609     ;; side effect
610     (if entitled
611         (howm-list-title-put-previous orig)
612       (howm-list-title-clear-previous))))
613
614 (defun howm-normalize (item-list
615                        &optional keyword comefrom-regexp no-list-title)
616   ;; no-list-title is never used now. [2009-07-23]
617   "Sort ITEM-LIST in the standard order."
618   (let ((matched nil)
619         (entitled-item-list nil))
620     (setq item-list (funcall howm-normalizer item-list))
621     (when keyword
622       (let ((key-reg (or comefrom-regexp
623                          (howm-make-keyword-regexp1 keyword)))
624             (word-reg (format "\\<%s\\>"
625                               (if (stringp keyword)
626                                   (regexp-quote keyword)
627                                 (regexp-opt keyword t))))
628             (wiki-reg (regexp-quote (howm-make-wiki-string keyword)))
629             (file-reg (and
630                        (stringp keyword)
631                        (format "^%s$"
632                                (regexp-quote (expand-file-name keyword)))))
633             (case-fold-search howm-keyword-case-fold-search))
634         (cl-labels ((check (tag flag reg &optional tag-when-multi-hits)
635                         (when flag
636                           (let ((r (howm-normalize-check item-list tag reg
637                                                          tag-when-multi-hits)))
638                             (setq matched (append (car r) matched))
639                             (setq item-list (cdr r))))))
640           ;; not efficient. should I do them at once?
641           (check 'word            howm-list-prefer-word word-reg)
642           (check 'wiki            howm-list-prefer-wiki wiki-reg)
643           (check 'related-keyword t howm-keyword-regexp)
644           (check 'keyword         t key-reg 'keyword-multi-hits)
645           (check 'file            file-reg file-reg))))
646     (when (and (howm-list-title-p)
647                (not no-list-title)
648                (not (and (member 'file matched)
649                          howm-inhibit-title-file-match)))
650       (setq entitled-item-list
651             (howm-entitle-items (howm-list-title-regexp) item-list)))
652     (cons matched (cons item-list entitled-item-list))))
653
654 (defun howm-normalize-check (item-list tag reg tag-when-multi-hits)
655   (let* ((r (if (eq tag 'file)
656                 (howm-view-lift-by-path-internal item-list reg)
657               (howm-view-lift-by-summary-internal item-list reg)))
658          (m (car r))
659          (item-list (cdr r))
660          (matched (cond ((and tag-when-multi-hits (eq m 'multi))
661                          (list tag-when-multi-hits tag))
662                         (m (list tag))
663                         (t nil))))
664     (cons matched item-list)))
665
666 (defun howm-list-normalize-old (&optional keyword comefrom-regexp no-list-title)
667   "Sort displayed items in the standard order.
668 This function is obsolete. Use `howm-normalize' insteadly.
669 --- Sorry, below documentation is incomplete. ---
670 When KEYWORD is given, matched items are placed on the top.
671 KEYWORD can be a string or a list of strings.
672 "
673   (prog1
674       (howm-view-in-background
675         (howm-list-normalize-subr keyword comefrom-regexp no-list-title))
676     (howm-view-summary)))
677
678 (defun howm-list-normalize-subr (keyword comefrom-regexp no-list-title)
679   "Obsolete. Do not use this any more."
680   (let ((matched nil))
681     (funcall howm-list-normalizer)
682     (when keyword
683       (let ((key-reg (or comefrom-regexp
684                          (howm-make-keyword-regexp1 keyword)))
685             (word-reg (format "\\<%s\\>"
686                               (if (stringp keyword)
687                                   (regexp-quote keyword)
688                                 (regexp-opt keyword t))))
689             (wiki-reg (regexp-quote (howm-make-wiki-string keyword)))
690             (file-reg (and
691                        (stringp keyword)
692                        (format "^%s$"
693                                (regexp-quote (expand-file-name keyword)))))
694             (case-fold-search howm-keyword-case-fold-search))
695         ;; clean me.
696         (let ((check (lambda (tag flag reg &optional tag-when-multi-hits)
697                        (when flag
698                          (let ((m (if (eq tag 'file)
699                                       (howm-view-lift-by-name nil reg t)
700                                     (howm-view-lift-by-summary nil reg))))
701                            (when m
702                              (setq matched (cons tag matched)))
703                            (when (and tag-when-multi-hits (eq m 'multi))
704                              (setq matched
705                                    (cons tag-when-multi-hits matched))))))))
706           (funcall check 'word            howm-list-prefer-word word-reg)
707           (funcall check 'wiki            howm-list-prefer-wiki wiki-reg)
708           (funcall check 'related-keyword t howm-keyword-regexp)
709           (funcall check 'keyword         t key-reg 'keyword-multi-hits)
710           (funcall check 'file            file-reg file-reg))))
711     (when (and (howm-list-title-p)
712                (not no-list-title)
713                (not (and (member 'file matched)
714                          howm-inhibit-title-file-match)))
715       (howm-list-title-internal))
716     matched))
717
718 (defun howm-make-keyword-string (keyword)
719   (format howm-keyword-format keyword))
720 (defun howm-make-wiki-string (keyword)
721   (format howm-wiki-format keyword))
722
723 ;; clean me
724 (defvar howm-keyword-regexp-format "%s$"
725   "Format to make entire-match regexp from keyword string.
726 Default is \"%s$\" because we want to make regexp \"<<< foo$\"
727 from keyword string \"<<< foo\",
728 so that we can accept \"<<< foo\" and reject \"<<< foobar\".
729 We need entire-match in order to
730 (1) place \"<<< foo\" on the top when \"foo\" is searched, and
731 (2) judge existence of \"<<< foo\" when [[foo]] is hit.")
732 (defun howm-make-keyword-regexp1 (keyword)
733   (howm-make-keyword-regexp-general keyword #'howm-make-keyword-regexp1-sub))
734 (defun howm-make-keyword-regexp2 (keyword)
735   (howm-make-keyword-regexp-general keyword #'howm-make-keyword-regexp2-sub))
736 (defun howm-make-keyword-regexp1-sub (keyword)
737   (format howm-keyword-regexp-format
738           (regexp-quote (howm-make-keyword-string keyword))))
739 (defun howm-make-keyword-regexp2-sub (keyword)
740   (format howm-keyword-regexp-format
741           (howm-make-keyword-string (regexp-quote keyword))))
742 (defun howm-make-keyword-regexp-general (keyword regexp-generator)
743   (cond ((stringp keyword)
744          (funcall regexp-generator keyword))
745         ((listp keyword)
746          (mapconcat (lambda (s)
747                       (concat "\\("
748                               (funcall regexp-generator s)
749                               "\\)"))
750                     keyword
751                     "\\|"))
752         (t (error "Wrong type: %s" keyword))))
753
754 (defun howm-list-related (str)
755   (howm-set-command 'howm-list-related)
756   (let* ((keys (mapcar (lambda (k)
757                          (if howm-keyword-case-fold-search
758                              (downcase k)
759                            k))
760                        (howm-subkeyword str)))
761          (filter `(lambda (items)
762                     (howm-filter-items-by-summary items ,(regexp-opt keys)))))
763     ;; Note that regexp-opt returns a regexp for emacs (not for grep).
764     (howm-search (howm-make-keyword-string ".*") nil nil filter)))
765
766 (defun howm-subkeyword (str)
767   (with-temp-buffer
768     (insert str)
769     (howm-keyword-for-goto)))
770
771 (defun howm-list-around ()
772   (interactive)
773   (howm-set-command 'howm-list-around)
774   (let ((f (buffer-file-name))
775         (item-list (howm-view-sort-by-reverse-date-internal
776                     (howm-all-items))))
777     (let ((howm-normalizer #'identity))
778       (howm-normalize-show "" item-list))
779     (let ((pos (cl-position-if (lambda (item)
780                                       (string= (howm-item-name item) f))
781                                     (howm-view-item-list))))
782       (goto-char (point-min))
783       (when pos
784         (forward-line pos)))
785     (howm-view-summary-check t)))
786
787 (defun howm-history ()
788   (interactive)
789   (unless (file-exists-p howm-history-file)
790     (error "No history."))
791   ;; disable expansion of %schedule etc.
792   (let ((howm-menu-display-rules nil)) ;; dirty
793     (howm-menu-open howm-history-file)))
794
795 ;; (defvar howm-history-exclude
796 ;;   (let ((strings '("[0-9][0-9][0-9][0-9]" "^[*=] [^ ]")))
797 ;;     `("| %.*%$"
798 ;;       ,(mapconcat 'regexp-quote strings "\\|"))))
799 ;; (defun howm-history ()
800 ;;   (interactive)
801 ;;   (howm-menu-open howm-history-file)
802 ;;   (howm-edit-read-only-buffer
803 ;;     (mapc #'flush-lines
804 ;;           howm-history-exclude)))
805
806 (defvar *howm-command* nil
807   "For internal use")
808 (defun howm-set-command (com)
809   (setq *howm-command* com))
810 (defun howm-command ()
811   *howm-command*)
812
813 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
814 ;; Create
815
816 (defun howm-create (&optional which-template here)
817   (interactive "p")
818   (let* ((t-c (howm-create-default-title-content))
819          (title (car t-c))
820          (content (cdr t-c)))
821     (howm-create-file-with-title title which-template nil here content)))
822
823 (howm-dont-warn-free-variable transient-mark-mode)
824 (howm-dont-warn-free-variable mark-active)
825 (defun howm-create-default-title-content ()
826   (let* ((p (point))
827          (m (or (mark t) -777))
828          (beg (min p m))
829          (end (max p m))
830          (search-str (howm-view-name)))
831     (let* ((transient-mark-p (and (boundp 'transient-mark-mode)
832                                   transient-mark-mode))
833            (mark-active-p (and (boundp 'mark-active) mark-active))
834            (active-p (if transient-mark-p
835                          mark-active-p
836                        t))
837            (strictly-active-p (and transient-mark-p mark-active-p))
838            (title-p (let* ((b (line-beginning-position))
839                            (e (line-end-position)))
840                       (and active-p
841                            (< 0 beg) (<= b beg) (<= end e) (not (= beg end)))))
842            (content-p (and strictly-active-p
843                            howm-content-from-region))
844            (search-p (and howm-title-from-search
845                           (stringp search-str)))
846            (s (cond ((or title-p content-p) (buffer-substring-no-properties beg
847                                                                             end))
848                     (search-p search-str))))
849       (cond ((null s) (cons "" ""))
850             ((eq content-p t) (cons "" s))
851             ((or title-p search-p) (cons s ""))
852             (content-p (cons "" s))
853             (t (cons "" ""))))))
854
855 (defun howm-create-here (&optional which-template)
856   (interactive "p")
857   (howm-create which-template t))
858
859 (defun howm-create-file-with-title (title &optional
860                                     which-template not-use-file here content)
861   (let ((b (current-buffer)))
862     (when (not here)
863       (howm-create-file))
864     (cond ((howm-buffer-empty-p) nil)
865           ((and here howm-create-here-just) (beginning-of-line))
866           (t (howm-create-newline)))
867     (let ((p (point))
868           (insert-f (lambda (switch)
869                       (howm-insert-template (if switch title "")
870                                             b which-template (not switch))))
871           (use-file (not not-use-file)))
872       ;; second candidate which appears when undo is called
873       (let ((end (funcall insert-f not-use-file)))
874         (save-excursion
875           (goto-char end)
876           (insert (or content "")))
877         (undo-boundary)
878         (delete-region p end))
879       (funcall insert-f use-file))
880     (howm-create-finish)))
881
882 (defun howm-create-finish ()
883   (howm-set-mode)
884   (run-hooks 'howm-create-hook))
885
886 (defun howm-create-newline ()
887   (widen)
888   (if howm-prepend
889       (howm-create-newline-prepend)
890     (howm-create-newline-append)))
891 (defun howm-create-newline-prepend ()
892   (goto-char (point-min)))
893 (defun howm-create-newline-append ()
894   (goto-char (point-max))
895   (delete-blank-lines)
896   (when (not (= (line-beginning-position) (point))) ;; not empty line
897     (insert "\n"))
898   (insert "\n"))
899
900 (defun howm-insert-template (title &optional
901                                    previous-buffer which-template not-use-file)
902   (let* ((beg (point))
903          (f (buffer-file-name previous-buffer))
904          (af (and f (howm-abbreviate-file-name f))))
905     (insert (howm-template-string which-template previous-buffer))
906     (let* ((date (format-time-string howm-template-date-format))
907            (use-file (not not-use-file))
908            (file (cond ((not use-file) "")
909                        ((null f) "")
910                        ((string= f (buffer-file-name)) "")
911                        (t (format howm-template-file-format af)))))
912       (let ((arg `((title . ,title) (date . ,date) (file . ,file)))
913             (end (point-marker)))
914         (howm-replace howm-template-rules arg beg end)
915         end))))
916
917 (defvar howm-template-receive-buffer t
918   "Non nil if howm-template should receive previous-buffer
919 when howm-template is a function.
920 Set this option to nil if backward compatibility with howm-1.2.4 or earlier
921 is necessary.")
922
923 (defun howm-template-string (which-template previous-buffer)
924   ;; which-template should be 1, 2, 3, ...
925   (setq which-template (or which-template 1))
926   (cond ((stringp howm-template) howm-template)
927         ((functionp howm-template) (let ((args (if howm-template-receive-buffer
928                                                    (list which-template
929                                                          previous-buffer)
930                                                  (list which-template))))
931                                      (apply howm-template args)))
932         ((listp howm-template) (nth (- which-template 1) howm-template))))
933
934 (defun howm-replace (rules arg &optional beg end)
935   (mapc (lambda (pair)
936           (let ((spell (car pair))
937                 (disp-f (cdr pair)))
938             (goto-char (or beg (point-min)))
939             (while (re-search-forward spell end t)
940               (delete-region (match-beginning 0) (match-end 0))
941               (funcall disp-f arg))))
942         rules))
943
944 (defun howm-template-title (arg)
945   (insert (cdr (assoc 'title arg))))
946 (defun howm-template-date (arg)
947   (insert (cdr (assoc 'date arg))))
948 (defun howm-template-previous-file (arg)
949   (insert (cdr (assoc 'file arg))))
950 (defun howm-template-cursor (arg)) ;; do nothing
951
952 (defun howm-dup ()
953   (interactive)
954   (let* ((r (howm-view-paragraph-region))
955          (s (buffer-substring-no-properties (car r) (cadr r))))
956     (howm-create-file)
957     (howm-set-mode)
958     (insert "\n" s)))
959
960 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
961 ;; Keyword
962
963 (defun howm-completing-read-keyword ()
964   (message "Scanning...")
965   (let* ((kl (howm-keyword-list))
966          (table (mapcar #'list kl))
967          (completion-ignore-case howm-keyword-case-fold-search))
968     (completing-read "Keyword: " table)))
969
970 (defun howm-insert-keyword ()
971   (interactive)
972   (insert (howm-completing-read-keyword)))
973
974 (defun howm-keyword-to-kill-ring (&optional filename-p)
975   (interactive "P")
976   (let ((title (howm-title-at-current-point filename-p)))
977     (if title
978         (howm-string-to-kill-ring title)
979       (error "No keyword."))))
980
981 (defun howm-title-at-current-point (&optional filename-p
982                                               title-regexp title-regexp-pos)
983   (let ((reg (or title-regexp howm-view-title-regexp))
984         (pos (or title-regexp-pos howm-view-title-regexp-pos)))
985     (save-excursion
986       (end-of-line)
987       (cond ((and (not filename-p)
988                   (re-search-backward reg nil t))
989              (match-string-no-properties pos))
990             ((buffer-file-name)
991              (howm-abbreviate-file-name (buffer-file-name)))
992             (t nil)))))
993
994 (defun howm-string-to-kill-ring (str)
995   (if str
996       (progn
997         (kill-new str)
998         (message "%s" str))
999     (error "Empty.")))
1000
1001 (defun howm-keyword-for-comefrom ()
1002   (save-excursion
1003     (goto-char (point-min))
1004     (let ((keyword-list nil))
1005       (while (re-search-forward howm-keyword-regexp nil t)
1006         (setq keyword-list
1007               (cons (match-string-no-properties howm-keyword-regexp-pos)
1008                     keyword-list)))
1009       (reverse keyword-list))))
1010
1011 (defun howm-keyword-list ()
1012   (let ((sep (format "[\n%s]" (or howm-keyword-list-alias-sep ""))))
1013     (with-current-buffer (howm-keyword-buffer)
1014       (delete ""
1015               (split-string (buffer-substring (point-min) (point-max)) sep)))))
1016
1017 (defun howm-keyword-add (keyword-list)
1018   (interactive "sKeyword: ")
1019   (setq keyword-list (if (stringp keyword-list)
1020                          (list keyword-list)
1021                        keyword-list))
1022   (with-current-buffer (howm-keyword-buffer)
1023     (save-excursion
1024       (goto-char (point-max))
1025       (mapc (lambda (k)
1026               (when (howm-keyword-new-p k)
1027                 (insert k "\n")))
1028             keyword-list)
1029       (when (buffer-file-name)
1030         (howm-basic-save-buffer)))))
1031
1032 (defun howm-keyword-new-p (str)
1033   (save-excursion
1034     (let ((r (format "^%s$" (regexp-quote str)))
1035           (case-fold-search howm-keyword-case-fold-search))
1036       (goto-char (point-min))
1037       (not (re-search-forward r nil t)))))
1038
1039 (defun howm-support-aliases-p ()
1040   howm-keyword-list-alias-sep)
1041 (defun howm-aliases ()
1042   (if (howm-support-aliases-p)
1043       (howm-read-aliases)
1044     nil))
1045 (defun howm-read-aliases ()
1046   (with-current-buffer (howm-keyword-buffer)
1047     (save-excursion
1048       (let ((ans nil))
1049         (goto-char (point-min))
1050         (while (search-forward howm-keyword-list-alias-sep nil t)
1051           (let* ((line (buffer-substring-no-properties (line-beginning-position)
1052                                                        (line-end-position)))
1053                  (keys (split-string line howm-keyword-list-alias-sep))
1054                  (ks (if howm-keyword-case-fold-search
1055                          (mapcar #'downcase keys)
1056                        keys)))
1057             (setq ans (cons ks ans))
1058             (end-of-line)))
1059         ans))))
1060
1061 (defun howm-expand-aliases-recursively (keyword aliases)
1062   (let ((keys (list keyword))
1063         (prev nil))
1064     (cl-labels ((expand (keys)
1065                      (sort (cl-remove-duplicates
1066                             (cl-mapcan (lambda (k)
1067                                               (cl-mapcan
1068                                                (lambda (a) (if (member k a)
1069                                                                (copy-sequence a)
1070                                                              nil))
1071                                                aliases))
1072                                             keys) :test #'string=)
1073                            #'string<)))
1074       (while (not (equal prev keys))
1075         (setq prev keys)
1076         (setq keys (expand keys))))
1077     keys))
1078 (cl-assert (equal (howm-expand-aliases-recursively "a"
1079                                                 '(("d" "e" "f") ("a" "b" "c")))
1080                '("a" "b" "c")))
1081 (cl-assert (equal (howm-expand-aliases-recursively "a"
1082                                                 '(("d" "e" "b") ("a" "b" "c")))
1083                '("a" "b" "c" "d" "e")))
1084
1085 (defun howm-keyword-aliases (keyword)
1086   "List of strings which are equivalent to KEYWORD.
1087 KEYWORD itself is always at the head of the returneded list.
1088 "
1089   ;; Return the original keyword (not downcased) for backward compatibility.
1090   ;; I'm not sure whether this behavior is really needed.
1091   (let* ((key (if howm-keyword-case-fold-search
1092                   (downcase keyword)
1093                 keyword))
1094          (aliases (howm-aliases))
1095          (equiv (if howm-keyword-aliases-recursive
1096                     (howm-expand-aliases-recursively key aliases)
1097                   (cl-remove-duplicates
1098                    (apply #'append
1099                           (cl-remove-if-not (lambda (a) (member key a))
1100                                                  aliases))))))
1101     (if (null equiv)
1102         keyword
1103       (cons keyword (remove key equiv)))))
1104
1105 (defun howm-keyword-search (keyword &optional create-p open-unique-p)
1106   (howm-message-time "key-search"
1107     (howm-set-command 'howm-keyword-search)
1108     (howm-with-normalizer
1109       (howm-keyword-search-subr keyword create-p open-unique-p))))
1110
1111 (defun howm-keyword-search-subr (keyword create-p open-unique-p)
1112   (let* ((aliases (if (howm-support-aliases-p)
1113                       (howm-keyword-aliases keyword)
1114                     keyword))
1115          (menu-p (howm-menu-keyword-p keyword))
1116          (comefrom-regexp (if menu-p ;; clean me
1117                               nil
1118                             (howm-make-keyword-regexp2 aliases)))
1119          (trio (let ((howm-search-other-dir (if menu-p ;; clean me
1120                                                  nil
1121                                                howm-search-other-dir))
1122                       (*howm-view-force-case-fold-search*
1123                        howm-keyword-case-fold-search)) ;; dirty!
1124                  (howm-call-view-search-internal aliases t)))
1125 ;; code for <http://pc8.2ch.net/test/read.cgi/unix/1077881095/823>.
1126 ;; but this change is canceled; I'll try more fundamental fix. [2005-11-04]
1127 ;;                   (if open-unique-p
1128 ;;                       (let ((r (concat "^" (regexp-quote keyword) "$")))
1129 ;;                         (howm-call-view-search r nil))
1130 ;;                     (howm-call-view-search aliases t))))
1131          (kw (car trio))
1132          (name (cadr trio))
1133          (items (cl-caddr trio))
1134          (items-pair nil)
1135          (found (if items t nil)) ;; want to forget items as soon as possible
1136          (matched (and found
1137                        (let* ((howm-keyword-format
1138                                (if menu-p ;; clean me
1139                                    (default-value 'howm-keyword-format)
1140                                  howm-keyword-format))
1141                               (r (howm-normalize items aliases
1142                                                  comefrom-regexp)))
1143                          (setq items-pair (cdr r))
1144                          (car r))))
1145          (keyword-matched (member 'keyword matched))
1146          (keyword-matched-multi (member 'keyword-multi-hits matched))
1147          (file-matched (member 'file matched))
1148          (title (howm-make-keyword-string keyword)))
1149     ;; main processing (clean me!) [2003-12-01]
1150     (cond
1151      ;; for %foo%
1152      ((and menu-p keyword-matched)
1153       (howm-keyword-search-open-menu keyword (car items-pair)
1154                                      keyword-matched-multi))
1155      ;; for [[foo]]
1156      ((and create-p (not keyword-matched))
1157       (howm-keyword-search-create title))
1158      ;; open if unique match
1159      ((and open-unique-p (howm-single-element-p items))
1160       (howm-keyword-search-open-unique items))
1161      (t
1162       (howm-call-view-summary name items-pair kw)
1163       (when (howm-normalize-oldp)
1164         ;; sorry for redundancy & inefficiency
1165         (howm-list-normalize-old aliases comefrom-regexp t))))
1166     ;; record history
1167     (when (not menu-p)
1168       (howm-write-history keyword))
1169     ;; return information
1170     `((menu-p . ,menu-p)
1171       (found . ,found)
1172       (matched . ,matched)
1173       (keyword-matched . ,keyword-matched)
1174       (create-p . ,create-p))
1175     ))
1176
1177 (defun howm-keyword-search-open-menu (keyword item-list multi-hits-p)
1178   "Open KEYWORD as menu."
1179   ;; dirty. peeking howm-view.el
1180   (let* ((item (car item-list))
1181          (fname (howm-view-item-filename item))
1182          (place (howm-view-item-place item)))
1183     (let ((howm-search-other-dir nil))
1184       (howm-menu-open fname place (howm-menu-name keyword))))
1185   (when multi-hits-p
1186     (message "Warning: found two or more %s." keyword)))
1187
1188 (defun howm-keyword-search-create (title)
1189   "create new memo <<< TITLE."
1190   (howm-create-file-with-title title)
1191   (message "New keyword."))
1192
1193 (defun howm-keyword-search-open-unique (items)
1194   "Open unique match."
1195   (howm-view-open-item (car items)))
1196
1197 ;; (defvar *howm-keyword-buffer* nil) ;; for internal use
1198 (defun howm-keyword-for-goto (&optional keyword-list)
1199   (save-excursion
1200     (let ((case-fold-search howm-keyword-case-fold-search))
1201       (sort (cl-mapcan (lambda (k)
1202                               (goto-char (point-min))
1203                               ;; when howm-check-word-break is non-nil,
1204                               ;; checking word breaks is desired for efficiency.
1205                               ;; it is not implemented yet.
1206                               (if (search-forward k nil 'noerr)
1207                                   (list k)
1208                                 nil))
1209                             (or keyword-list (howm-keyword-list)))
1210             (lambda (x y)
1211               (> (length x) (length y)))))))
1212
1213 (defun howm-keyword-add-current-buffer ()
1214   (save-excursion
1215     (goto-char (point-min))
1216     (let ((m (current-message))
1217           (keyword-list nil))
1218       (while (re-search-forward howm-keyword-regexp nil t)
1219         (let ((key-str (if howm-keyword-list-alias-sep
1220                            (mapconcat #'identity
1221                                       (howm-keyword-read)
1222                                       howm-keyword-list-alias-sep)
1223                          (match-string-no-properties howm-keyword-regexp-pos))))
1224           (setq keyword-list (cons key-str keyword-list))))
1225       (howm-keyword-add keyword-list)
1226       (message "%s" m))))
1227 (defun howm-keyword-add-items (items)
1228   (let ((files (mapcar #'howm-view-item-filename items)))
1229     (with-temp-buffer
1230       (mapc (lambda (f)
1231               (erase-buffer)
1232               (insert-file-contents f)
1233               (howm-set-configuration-for-file-name f)
1234               (howm-keyword-add-current-buffer))
1235             files))))
1236
1237 (defun howm-keyword-read ()
1238   (let ((ks nil)
1239         (beg (line-beginning-position)))
1240     (end-of-line)
1241     (skip-chars-backward " ")
1242     (while (re-search-backward howm-keyword-regexp beg t)
1243       (setq ks (cons (match-string-no-properties howm-keyword-regexp-pos) ks))
1244       (skip-chars-backward " "))
1245     (end-of-line)
1246     ks))
1247
1248 ;;; howm-mode.el ends here