1 ;;; howm-common.el --- Wiki-like note-taking tool
2 ;;; Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2015, 2016
3 ;;; HIRAOKA Kazuyuki <khi@users.sourceforge.jp>
4 ;;; $Id: howm-common.el,v 1.90 2012-12-29 08:57:18 hira Exp $
6 ;;; This program 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 1, or (at your option)
11 ;;; This program is distributed in the hope that it will be useful,
12 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ;;; GNU General Public License for more details.
16 ;;; The GNU General Public License is available by anonymouse ftp from
17 ;;; prep.ai.mit.edu in pub/gnu/COPYING. Alternately, you can write to
18 ;;; the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,
20 ;;--------------------------------------------------------------------
24 (defun howm-cl-remove-duplicates* (&rest args)
25 ":from-end version of `remove-duplicates'"
26 (apply #'cl-remove-duplicates `(,@args :from-end t)))
28 (defun howm-sort (evaluator comparer obj-list)
29 (let* ((orig (mapcar (lambda (obj) (cons (funcall evaluator obj) obj))
31 (sorted (sort orig (lambda (x y)
32 (funcall comparer (car x) (car y))))))
33 (mapcar #'cdr sorted)))
35 (defun howm-subdirectory-p (dir target &optional strict)
36 "For the directory DIR, check whether TARGET is under it.
37 When TARGET and DIR are same, (not STRICT) is returned."
39 ;; avoid unnecessary password prompting
40 ;; (I'm not sure about the return value of file-remote-p.)
41 (eq (not (file-remote-p dir)) (not (file-remote-p target)))
43 (setq target (howm-normalize-file-name target))
44 (setq dir (howm-normalize-file-name dir))
45 (if (string= target dir)
47 (and (string-match (regexp-quote dir) target)
48 (= 0 (match-beginning 0)))))))
50 (defun howm-normalize-file-name (filename)
51 (let* ((r (file-remote-p filename))
54 (file-truename (expand-file-name filename)))))
56 (if (string-match "^[A-Z]:" f)
57 (let ((drive (substring f 0 1))
58 (rest (substring f 1)))
59 (concat (downcase drive) rest))
62 (defvar howm-abbreviate-file-name t)
63 (defun howm-abbreviate-file-name (f)
64 (if (howm-abbreviate-file-name-p)
65 (abbreviate-file-name f)
67 ;; for compatibility (incomplete)
68 (howm-dont-warn-free-variable howm-template-file-abbrev)
69 (howm-dont-warn-free-variable howm-view-header-abbrev)
70 (defun howm-abbreviate-file-name-p ()
71 (cond ((boundp 'howm-template-file-abbrev) howm-template-file-abbrev)
72 ((boundp 'howm-view-header-abbrev) howm-view-header-abbrev)
73 (t howm-abbreviate-file-name)))
74 ;; (defun howm-abbreviate-file-name-p () howm-abbreviate-file-name)
76 (defun howm-expand-file-names (file-list)
77 (mapcar (lambda (f) (directory-file-name (expand-file-name f)))
80 (defun howm-insert-file-contents (file)
81 (insert-file-contents file nil nil howm-view-contents-limit))
83 ;;; for XEmacs fallback
84 ;; (if (not (fboundp 'font-lock-fontify-block))
85 ;; (defalias 'font-lock-fontify-block 'font-lock-fontify-buffer))
86 ;;; If you use APEL, you can replace a below block with (require 'poe).
87 (if (not (fboundp 'line-beginning-position))
88 (defalias 'line-beginning-position 'point-at-bol))
89 (if (not (fboundp 'line-end-position))
90 (defalias 'line-end-position 'point-at-eol))
91 ;;; Imported from APEL 10.6
92 (if (not (fboundp 'match-string-no-properties))
93 ;; Emacs 20.3 and later: (match-string-no-properties NUM &optional STRING)
94 (defun match-string-no-properties (num &optional string)
95 "Return string of text matched by last search, without text properties.
96 NUM specifies which parenthesized expression in the last regexp.
97 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
98 Zero means the entire text matched by the whole regexp or whole string.
99 STRING should be given if the last search was by `string-match' on STRING."
100 (if (match-beginning num)
103 (substring string (match-beginning num) (match-end num))))
104 (set-text-properties 0 (length result) nil result)
106 (buffer-substring-no-properties (match-beginning num)
109 (defmacro howm-message-time (name &rest body)
111 `(let ((howm-message-time-0 (current-time)))
115 (when howm-message-time
116 (message "%s (%s: %.2f sec)"
117 (or (current-message) "")
119 (howm-time-difference-second (current-time)
120 howm-message-time-0))))))
121 ;; (defun howm-message-time-from (ti0)
122 ;; (when howm-message-time
123 ;; (let ((ti1 (current-time)))
124 ;; (message "took %.2f sec."
125 ;; (howm-time-difference-second ti1 ti0)))))
126 (defun howm-time-difference-second (ti1 ti0)
127 (let ((h (- (car ti1) (car ti0)))
128 (l (- (cadr ti1) (cadr ti0)))
129 (m (- (cl-caddr ti1) (cl-caddr ti0)))
135 (defun howm-xor (a b)
137 (defun howm-buffer-empty-p (&optional buf)
138 ;; emacs20 doesn't have (buffer-size buf)
139 (with-current-buffer (or buf (current-buffer))
140 (= (buffer-size) 0)))
141 (defun howm-point-beginning-of-line ()
145 (defun howm-point-end-of-line ()
150 (defun howm-inhibit-warning-in-compilation (&rest dummy)
151 (error "This is dummy function to inhibit warning in compilation."))
153 ;; (defvar howm-reminder-quick-check-key ";")
155 (defun howm-get-value (z)
160 ;; (howm-map-with-index #'cons '(a b c)) ==> ((a . 0) (b . 1) (c . 2))
161 (defun howm-map-with-index (f seq)
162 "Map with index. For example,
163 (howm-map-with-index #'cons '(a b c)) returns ((a . 0) (b . 1) (c . 2))."
164 (let ((howm-map-with-index-count -1))
166 (setq howm-map-with-index-count (1+ howm-map-with-index-count))
167 (apply f (list x howm-map-with-index-count)))
170 (defun howm-capital-p (str)
171 "Return nil iff STR has no capital letter."
172 (let ((case-fold-search nil))
173 (string-match "[A-Z]" str)))
175 (defun howm-single-element-p (a)
176 (and a (null (cdr a))))
178 (defun howm-read-string (prompt &optional immediate-chars continued-chars
179 pass-through pass-ret-through)
180 "Read a string from minibuffer with some extensions to `read-string'.
181 (1) When the first input char is in IMMEDIATE-CHARS string,
182 this function returns the char as one letter string
183 without waiting for rest input and RET key.
184 (2) Otherwise, when the char is in CONTINUED-CHARS,
185 this function is equivalent to read-string.
186 (3) When the char is not in either IMMEDIATE-CHARS or CONTINUED-CHARS,
187 the behavior depends on PASS-THROUGH.
188 If PASS-THROUGH is nil, error is raised.
189 If PASS-THROUGH is non-nil, the input event is unread and nil is returned.
190 (4) Note that RET key at the first char is the special case.
191 If PASS-RET-THROUGH is nil, empty string is returned.
192 If PASS-RET-THROUGH is non-nil, RET is unread and nil is returned.
194 (if (null immediate-chars)
196 (save-window-excursion
197 (message "%s" prompt)
198 (select-window (minibuffer-window))
199 (let* ((ev (howm-read-event))
200 (ch (howm-event-to-character ev)))
201 (cond ((howm-characterp ch)
202 (howm-read-string-sub ev ch
203 prompt immediate-chars continued-chars
204 pass-through pass-ret-through))
206 (howm-read-string-fail ev pass-through pass-ret-through)))))))
208 (defun howm-read-string-sub (event char
209 prompt immediate-chars continued-chars
210 pass-through pass-ret-through)
211 (let* ((ichars (string-to-list (or immediate-chars "")))
212 (cchars (string-to-list (or continued-chars "")))
214 (first-str (char-to-string first-char)))
215 (cond ((member first-char ichars)
217 ((member first-char cchars)
218 (read-string prompt (cons first-str (1+ (length first-str)))))
220 (howm-read-string-fail event pass-through pass-ret-through)))))
222 (defun howm-read-string-fail (event pass-through pass-ret-through)
223 (cond ((and (howm-ret-key-event-p event) (not pass-ret-through))
227 (howm-unread-event event)
230 (error "Invalid input."))))
232 (defun howm-unread-event (event)
233 (setq unread-command-events
234 (cons event unread-command-events)))
236 (defun howm-first-n (seq n)
237 "Return the subsequence of SEQ from start to N-th item.
238 (howm-first-n '(a b c d e) 3) ==> (a b c)
239 (howm-first-n '(a b c d e) 10) ==> (a b c d e)
241 ;; GNU emacs: (subseq '(a b c d e) 0 7) ==> (a b c d e nil nil)
242 ;; xemacs: (subseq '(a b c d e) 0 7) ==> Args out of range
243 (if (<= (length seq) n)
245 (cl-subseq seq 0 n)))
248 (let ((seq '(a b c d e))
254 (let ((ans (howm-first-n seq (car z))))
255 (when (not (equal ans (cdr z)))
256 (error "howm-first-n is wrong: %s for %s" ans z))))
259 (defun howm-replace-region (beg end val)
260 (delete-region beg end)
261 ;; `format' in xemacs doesn't keep text properties.
262 (insert (if (stringp val)
266 (defmacro howm-edit-read-only-buffer (&rest body)
269 (buffer-disable-undo)
270 (setq buffer-read-only nil)
272 (set-buffer-modified-p nil)
273 (setq buffer-read-only t)))
275 (defmacro howm-rewrite-read-only-buffer (&rest body)
277 `(howm-edit-read-only-buffer
281 ;; (put 'howm-rewrite-read-only-buffer 'lisp-indent-hook 0)
282 ;; (defmacro howm-rewrite-read-only-buffer (&rest body)
284 ;; (setq buffer-read-only nil)
287 ;; (set-buffer-modified-p nil)
288 ;; (setq buffer-read-only t)))
290 (defun howm-get-buffer-for-file (file &optional buffer-name)
291 "Get buffer for FILE, and rename buffer if BUFFER-NAME is given."
292 ;; This may cause "File XXX no longer exists!" message if the file
293 ;; is deleted and the corresponding buffer still exists.
294 (let ((buf (find-file-noselect file)))
296 (with-current-buffer buf
297 (rename-buffer buffer-name)))
300 (defun howm-basic-save-buffer ()
301 "Silent version of `basic-save-buffer' without \"Wrote ...\" message."
302 (let ((original-write-region (symbol-function 'write-region)))
303 ;; make silent `write-region', which doesn't say "Wrote ...".
304 ;; I borrowed the idea from Okuyama's auto-save-buffers. thx.
305 ;; http://homepage3.nifty.com/oatu/emacs/misc.html
306 (cl-flet ((write-region (start end filename
307 &optional append visit lockname must)
308 (funcall original-write-region
309 start end filename append
310 'dont-say-wrote-foobar
312 (basic-save-buffer)))
313 ;; As a side effect, basic-save-buffer does not update buffer-modified-p.
314 (set-visited-file-modtime)
315 (set-buffer-modified-p nil))
317 (defvar howm-log-buffer-name-format " *howm-log:%s*")
318 (defun howm-write-log (message fmt file &optional limit remove-fmt)
319 "Write MESSAGE with format FMT to the top of FILE.
320 FORMAT must have two %s; the formar is time and the latter is message.
321 When LIMIT is non-nil, only that number of recent messages are recorded.
322 When REMOVE-FMT is non-nil, it is used to generate regular expression
323 to remove matched lines. REMOVE-FMT must have one %s."
325 (let ((buffer-name (format howm-log-buffer-name-format
326 (file-name-nondirectory file))))
327 (with-current-buffer (howm-get-buffer-for-file file buffer-name)
328 (goto-char (point-min))
331 (flush-lines (format remove-fmt (regexp-quote message)))))
333 (format-time-string howm-dtime-format (current-time))
337 ;; Since I don't understand `selective-display' in goto-line,
339 (goto-char (point-min))
340 (when (= (forward-line limit) 0) ;; buffer lines > LIMIT
341 (delete-region (point) (point-max))))
342 (howm-basic-save-buffer)))))
344 (defun howm-get-symbol (soft &rest args)
345 "Return the canonical symbol for a specified name.
346 If SOFT is non-nil, return nil when the corresponding symbol does not exist.
347 Name of returned symbol is concatenation of ARGS.
348 Both strings and symbols are acceptable in ARGS."
349 (funcall (if soft #'intern-soft #'intern)
350 (mapconcat (lambda (s)
351 (cond ((sequencep s) s)
352 ((symbolp s) (symbol-name s))
353 (t (error "Not supported: %S" s))))
357 ;; snap://Info-mode/elisp#Killing Buffers
358 (defun howm-buffer-killed-p (buffer)
359 "Return t if BUFFER is killed."
360 (not (buffer-name buffer)))
362 (defun howm-classify (classifier lis &optional reverse)
363 "Classify elements in given list.
364 CLASSIFIER is criterion of classification for list LIS.
365 If REVERSE is non-nil, order of elements are reversed (faster).
367 (howm-classify (lambda (s) (substring s 0 1)) '(\"aaa\" \"abc\" \"xyz\"))
368 returns ((\"a\" \"aaa\" \"abc\") (\"x\" \"xyz\"))."
371 (let* ((label (funcall classifier x))
372 (pair (assoc label ans)))
374 (setq ans (cons (cons label (list x)) ans))
375 (setcdr pair (cons x (cdr pair))))))
379 (reverse (mapcar (lambda (pair) (cons (car pair) (reverse (cdr pair))))
381 ;; (howm-classify (lambda (s) (substring s 0 1)) '("aaa" "abc" "xyz"))
383 (defun howm-message-nolog (str &rest args)
384 (let ((message-log-max nil))
385 (apply #'message `(,str ,@args))))
387 (defun howm-decode-time (&optional specified-time)
388 "Decode SPECIFIED-TIME and remove DOW, DST, ZONE.
389 When we do something like (encode-time (decode-time)), we use this function
390 instead of the original `decode-time', so that we can force
391 current timezone rule uniformly to avoid inconsistency."
392 (butlast (decode-time specified-time) 3))
394 (defmacro howm-with-need (&rest body)
395 "Execute BODY where (need xxx) exits from this form if xxx is nil."
397 (let ((g (cl-gensym)))
399 (cl-labels ((need (x) (or x (throw ',g nil))))
402 (defun howm-goto-line (n)
403 ;; see the document of `goto-line'
404 (goto-char (point-min)) (forward-line (1- n)))
406 ;; view-in-background
408 (defvar *howm-view-in-background* nil
410 Don't set this variable directly.
411 Use `howm-view-in-background' and `howm-view-in-background-p' instead.")
413 (defmacro howm-view-in-background (&rest body)
414 "Obsolete. Do not use this any more."
416 `(let ((*howm-view-in-background* t))
419 (defun howm-view-in-background-p ()
420 *howm-view-in-background*)
422 ;;; history of search
424 (defvar howm-history-format "> %s | %s")
425 (defvar howm-history-remove-format "| %s$")
427 (defun howm-write-history (message)
428 (when (and howm-history-file
429 (or (null howm-history-limit) (> howm-history-limit 0)))
430 (howm-write-log message howm-history-format howm-history-file
432 (and howm-history-unique howm-history-remove-format))))
436 (defvar howm-call-process-last-command nil
437 "List of arguments for last `howm-call-process'.
438 This variable exists only for debug. You can reproduce the last call
440 (apply #'howm-call-process howm-call-process-last-command)")
442 (defmacro howm-with-coding-system (coding-system &rest body)
443 "With CODING-SYSTEM, execute BODY.
445 (howm-with-coding-system 'euc-jp-unix ...) ;; for both read and write
446 (howm-with-coding-system '(utf-8-unix . sjis-unix) ...) ;; (read . write)
447 (howm-with-coding-system nil ...) ;; howm-process-coding-system is used."
449 (let ((g (cl-gensym))
450 (cs (or coding-system 'howm-process-coding-system)))
452 (coding-system-for-read (or (car-safe ,g) ,g))
453 (coding-system-for-write (or (cdr-safe ,g) ,g)))
456 (defun howm-call-process (command args
457 &optional expected-return-value stdin-string)
458 (setq howm-call-process-last-command (list command args
459 expected-return-value
462 (howm-with-coding-system nil
463 (let ((r (howm-call-process-here command args stdin-string)))
464 (when (and expected-return-value
465 (not (= expected-return-value r)))
466 (error "Process returns %s instead of expected %s."
467 r expected-return-value))
468 (howm-buffer-lines)))))
470 (defun howm-call-process-here (command args &optional stdin-string)
473 (insert (or stdin-string ""))
475 (a `(,beg ,end ,command t (t nil) nil ,@args)))
476 (howm-with-coding-system nil
477 (apply #'call-process-region a))))
479 (defun howm-buffer-lines (&optional buf)
483 (split-string (buffer-substring (point-min) (point-max)) "\n")))
485 (defun howm-call-process* (command common-args rest-args &rest options)
486 ;; (howm-call-process* "grep" '("pattern") '("001" ... "999"))
487 ;; is expanded to concatenation of
488 ;; (howm-call-process "grep" '("pattern" "001" ... "099"))
489 ;; (howm-call-process "grep" '("pattern" "101" ... "199"))
490 ;; ..., depending on howm-command-length-limit.
491 (cl-labels ((div (a limit measure)
492 ;; (div '(3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8) 20 #'identity)
493 ;; ==> ((3 1 4 1 5) (9 2 6) (5 3 5) (8 9) (7 9 3) (2 3 8))
494 ;; [create new group when sum >= 20]
495 (let ((sum limit) ;; measure >= 0 is assumed.
498 (let* ((w (funcall measure x))
500 (if (< new-sum limit)
502 ans (cons (cons x (car ans)) (cdr ans)))
504 ans (cons (list x) ans)))))
506 (reverse (mapcar #'reverse ans)))))
507 ;; XEmacs 21.4 lacks "string-bytes".
508 (let* ((len (symbol-function
509 (cl-find-if #'fboundp '(string-bytes length))))
510 (limit (apply #'- howm-command-length-limit
511 (mapcar len (cons command common-args))))
512 (as (div rest-args limit len)))
513 (cl-mapcan (lambda (args)
514 (apply #'howm-call-process
515 command (append common-args args) options))
518 ;;; schedule-interval & reminder-setting (clean me)
520 (defvar howm-reminder-schedule-interval nil
521 "For internal use. Do not setq this variable.
522 Use `howm-with-schedule-interval' instead.")
523 (defun howm-reminder-schedule-interval-from ()
524 (car howm-reminder-schedule-interval))
525 (defun howm-reminder-schedule-interval-to ()
526 (cdr howm-reminder-schedule-interval))
527 (defmacro howm-with-schedule-interval (interval &rest body)
528 "Set the interval of visible schedule items in reminder list on menu.
529 INTERVAL is a form like (-1 2), which means 'from yesterday to the day
530 after tomorrow'. BODY is evaluated under this setting;
531 `howm-reminder-schedule-interval-from' returns -1 and
532 `howm-reminder-schedule-interval-to' returns 2."
534 `(let ((howm-reminder-schedule-interval ,(cons 'cons interval)))
537 (defmacro howm-with-reminder-setting (&rest body)
539 `(howm-with-schedule-interval
540 (howm-menu-schedule-days-before howm-menu-schedule-days)
541 (let ((howm-todo-menu-types howm-reminder-menu-types)) ;; dirty!
546 ;; http://www.bookshelf.jp/cgi-bin/goto.cgi?file=meadow&node=switch%20config
547 ;; http://pc2.2ch.net/test/read.cgi/software/1056601345/510
549 (defun howm-xemacsp ()
552 (defmacro howm-defun-xemacs (func args emacs-f xemacs-f)
553 (declare (indent 'defun))
559 (howm-defun-xemacs howm-deactivate-mark ()
561 (zmacs-deactivate-region))
563 (howm-defun-xemacs howm-read-event ()
565 ;; We have to skip #<magic-event Expose> when howm-action-lock-date is
566 ;; called (RET is hit on date format like [2005-10-15]) in menu buffer.
568 ;; Though (make-event 'key-press `(key ,(read-char))) looks to be a simpler
569 ;; solution, it causes error when RET RET is hit in the above situation.
570 ;; I don't have enough time to examine it now.
571 (let ((ev (next-event)))
572 (if (key-press-event-p ev)
576 ;; Though this function is used only once, I dare to define it
577 ;; with howm-defun-xemacs macro in order to avoid warning
578 ;; in byte-compilation on GNU emacs. I don't have enough energy now.
579 (howm-defun-xemacs howm-ret-key-event ()
580 (event-convert-list '(return))
581 (make-event 'key-press '(key return)))
583 (defvar howm-ret-key-event (howm-ret-key-event))
585 (defun howm-ret-key-event-p (event)
586 (or (equal event 13) (equal event howm-ret-key-event)))
588 (howm-defun-xemacs howm-event-to-character (event)
589 (and (howm-characterp event) event)
590 (event-to-character event))
592 (howm-defun-xemacs howm-characterp (x)
596 (defvar howm-infinity
598 1.0e+100 ;; xemacs info on my machine is broken :(
603 ;; (defmacro howm-define-maybe (fname fargs &rest fbody)
604 ;; (when (not (fboundp fname))
605 ;; `(defun ,fname ,fargs
608 ;; (howm-define-maybe caddr (x)
609 ;; (car (cdr (cdr x))))
611 ;; (howm-define-maybe second (x)
614 ;; (howm-define-maybe third (x)
619 ;; (defun howm-regexp-opt (strings &optional paren)
620 ;; "Imitation of `regexp-opt' without optimization.
621 ;; This is used for large set of strings when `regexp-opt' causes an error
622 ;; \"Variable binding depth exceeds max-specpdl-size\"."
623 ;; (let* ((open (if paren "\\(" ""))
624 ;; (close (if paren "\\)" ""))
625 ;; (re (concat open (mapconcat 'regexp-quote strings "\\|") close)))
626 ;; (if (eq paren 'words)
627 ;; (concat "\\<" re "\\>")
632 (provide 'howm-common)
634 ;;; howm-common.el ends here