]> code.delx.au - gnu-emacs-elpa/blob - chess-file.el
use zerop
[gnu-emacs-elpa] / chess-file.el
1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;;
3 ;; A game database that stores PGN format games in a single file.
4 ;;
5 ;; This is basically what you expect from a file ending in .pgn.
6 ;;
7
8 (defvar chess-file-locations)
9
10 (make-variable-buffer-local 'chess-file-locations)
11
12 (defun chess-file-handler (event &rest args)
13 (cond
14 ((eq event 'open)
15 (with-current-buffer (find-file-noselect (car args))
16 (when (or (string-match "\\.pgn\\'" (car args))
17 (save-excursion
18 (re-search-forward "^\\[Event" nil t)))
19 (chess-file-handler 'rescan)
20 (current-buffer))))
21
22 ((eq event 'rescan)
23 (save-excursion
24 (goto-char (point-min))
25 (setq chess-file-locations nil)
26 (while (re-search-forward "^\\[Event " nil t)
27 (goto-char (match-beginning 0))
28 (push (point) chess-file-locations)
29 (forward-char 1))
30 (setq chess-file-locations (nreverse chess-file-locations))))
31
32 ((eq event 'save)
33 (save-buffer))
34
35 ((eq event 'count)
36 (length chess-file-locations))
37
38 ((eq event 'read)
39 (let ((index (car args)) game)
40 (when (and (>= index 0)
41 (< index (chess-file-handler 'count)))
42 (goto-char (nth index chess-file-locations))
43 (when (setq game (chess-pgn-to-game))
44 (chess-game-set-data game 'database (current-buffer))
45 (chess-game-set-data game 'database-index index)
46 (chess-game-set-data game 'database-count
47 (chess-file-handler 'count))
48 game))))
49
50 ((eq event 'write)
51 (goto-char (point-max))
52 (while (memq (char-before) '(? ?\t ?\n ?\r))
53 (delete-backward-char 1))
54 (insert ?\n ?\n)
55 (push (point) chess-file-locations)
56 (chess-game-to-pgn (car args))
57 (1- (chess-file-handler 'count)))
58
59 ((eq event 'replace)
60 (let ((index (or (cadr args)
61 (chess-game-data (car args) 'database-index)))
62 (count (chess-file-handler 'count)))
63 (when (and (>= index 0)
64 (< index count))
65 (goto-char (nth index chess-file-locations))
66 (delete-region (point) (if (= (1+ index) count)
67 (point-max)
68 (nth (1+ index) chess-file-locations)))
69 (chess-game-to-pgn (car args))
70 (insert ?\n))))))
71
72 (provide 'chess-file)
73
74 ;;; chess-file.el ends here