]> code.delx.au - gnu-emacs-elpa/blob - packages/gnugo/gnugo.el
[gnugo] Indicate buffer not modified after save.
[gnu-emacs-elpa] / packages / gnugo / gnugo.el
1 ;;; gnugo.el --- play GNU Go in a buffer
2
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
4
5 ;; Author: Thien-Thi Nguyen <ttn@gnu.org>
6 ;; Version: 2.2.14
7
8 ;; This program is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
12
13 ;; This program is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
20
21 ;;; Commentary:
22
23 ;; Playing
24 ;; -------
25 ;;
26 ;; This file provides the command `gnugo' which allows you to play the game of
27 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
28 ;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
29 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
30 ;; Go" to refer to the process object created by running the external program.
31 ;;
32 ;; At the start of a new game, you can pass additional command-line arguments
33 ;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
34 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
35 ;; both komi and handicap.
36 ;;
37 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
38 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
39 ;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
40 ;; back through an arbitrary stone that you played, place the cursor on a
41 ;; stone and type `U' (note: uppercase). Other keybindings are described in
42 ;; the `gnugo-board-mode' documentation, which you may view with the command
43 ;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
44 ;; the last move and who is currently to play. Capture counts and other info
45 ;; are shown on the mode line immediately following the major mode name.
46 ;;
47 ;; While GNU Go is pondering its next move, certain commands that rely on its
48 ;; assistence will result in a "still waiting" error. Do not be alarmed; that
49 ;; is normal. When it is your turn again you may retry the command. In the
50 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
51 ;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
52 ;;
53 ;; If GNU Go should crash during a game the mode line will show "no process".
54 ;; Please report the event to the GNU Go maintainers so that they can improve
55 ;; the program.
56 ;;
57 ;;
58 ;; Meta-Playing (aka Customizing)
59 ;; ------------------------------
60 ;;
61 ;; Customization is presently limited to
62 ;; vars: `gnugo-program'
63 ;; `gnugo-animation-string'
64 ;; `gnugo-mode-line'
65 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
66 ;; `gnugo-xpms'
67 ;; normal hooks: `gnugo-board-mode-hook'
68 ;; `gnugo-post-move-hook'
69 ;; and the keymap: `gnugo-board-mode-map'
70 ;;
71 ;; The variable `gnugo-xpms' is a special case. To set it you need to load
72 ;; gnugo-xpms.el (http://www.emacswiki.org) or some other library w/ congruent
73 ;; interface.
74
75 ;;; Code:
76
77 (require 'cl-lib) ; use the source luke!
78 (require 'time-date) ; for `time-subtract'
79
80 ;;;---------------------------------------------------------------------------
81 ;;; Political arts
82
83 (defconst gnugo-version "2.2.14"
84 "Version of gnugo.el currently loaded.
85 This follows a MAJOR.MINOR.PATCH scheme.")
86
87 ;;;---------------------------------------------------------------------------
88 ;;; Variables for the uninquisitive programmer
89
90 (defvar gnugo-program "gnugo"
91 "*Command to start an external program that speaks GTP, such as \"gnugo\".
92 The value may also be in the form \"PROGRAM OPTIONS...\" in which case the
93 the command `gnugo' will prefix OPTIONS in its default offering when it
94 queries you for additional options. It is an error for \"--mode\" to appear
95 in OPTIONS.
96
97 For more information on GTP and GNU Go, feel free to visit:
98 http://www.gnu.org/software/gnugo")
99
100 (defvar gnugo-board-mode-map nil
101 "Keymap for GNUGO Board mode.")
102
103 (defvar gnugo-board-mode-hook nil
104 "*Hook run when entering GNUGO Board mode.")
105
106 (defvar gnugo-post-move-hook nil
107 "*Normal hook run after a move and before the board is refreshed.
108 Hook functions can prevent the call to `gnugo-refresh' by evaluating:
109 (setq inhibit-gnugo-refresh t)
110 Initially, when `run-hooks' is called, the current buffer is the GNUGO
111 Board buffer of the game. Hook functions that switch buffers must take
112 care not to call (directly or indirectly through some other function)
113 `gnugo-put' or `gnugo-get' after the switch.")
114
115 (defvar gnugo-animation-string
116 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
117 (concat jam jam jam jam jam
118 ;; "SECRET MESSAGE HERE"
119 blink blink blink blink blink blink blink blink
120 ;; Playing go is like fighting ignorance: when you think you have
121 ;; surrounded something by knowing it very well it often turns
122 ;; out that in the time you spent deepening this understanding,
123 ;; other areas of ignorance have surrounded you.
124 spin spin spin spin spin spin spin spin spin
125 ;; Playing go is not like fighting ignorance: what one person
126 ;; knows many people may come to know; knowledge does not build
127 ;; solely move by move. Wisdom, on the other hand...
128 yada yada yada))
129 "*String whose individual characters are used for animation.
130 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
131 render the stones in their respective result groups as the first character
132 in the string, then the next, and so on.")
133
134 (defvar gnugo-mode-line "~b ~w :~m :~u"
135 "*A `mode-line-format'-compliant value for GNUGO Board mode.
136 If a single string, the following special escape sequences are
137 replaced with their associated information:
138 ~b,~w black,white captures (a number)
139 ~p current player (black or white)
140 ~m move number
141 ~t time waiting for the current move
142 ~u time taken for the Ultimate (most recent) move
143 The times are in seconds, or \"-\" if that information is not available.
144 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
145
146 (defvar gnugo-X-face 'font-lock-string-face
147 "*Name of face to use for X (black) stones.")
148
149 (defvar gnugo-O-face 'font-lock-builtin-face
150 "*Name of face to use for O (white) stones.")
151
152 (defvar gnugo-grid-face 'default
153 "*Name of face to use for the grid (A B C ... 1 2 3 ...).")
154
155 ;;;---------------------------------------------------------------------------
156 ;;; Variables for the inquisitive programmer
157
158 (defconst gnugo-font-lock-keywords
159 '(("X" . gnugo-X-face)
160 ("O" . gnugo-O-face))
161 "Font lock keywords for `gnugo-board-mode'.")
162
163 (defvar gnugo-option-history nil)
164
165 (defvar gnugo-state nil) ; hint: C-c C-p
166
167 (eval-when-compile
168 (defvar gnugo-xpms nil))
169
170 ;;;---------------------------------------------------------------------------
171 ;;; Support functions
172
173 (put 'gnugo-put 'lisp-indent-function 1)
174 (defun gnugo-put (key value) (puthash key value gnugo-state))
175 (defun gnugo-get (key) (gethash key gnugo-state))
176
177 (let ((docs "Put or get move/game/board-specific properties.
178 \(This docstring is shared by `gnugo-put' and `gnugo-get'.\)
179
180 There are many properties, each named by a keyword, that record and control
181 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
182 of properties, stored in the hash table `gnugo-state'. Here we document
183 some of the more stable properties. You may wish to use them as part of
184 a `gnugo-post-move-hook' function, for example. Be careful to preserve
185 the current buffer as `gnugo-state' is made into a buffer-local variable.
186 NOTE: In the following, \"see foo\" actually means \"see foo source or
187 you may never really understand to any degree of personal satisfaction\".
188
189 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
190
191 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
192
193 :game-over -- nil until game over at which time its value is set to
194 the alist `((live GROUP ...) (dead GROUP ...))'
195
196 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
197 a simple list of one or more gametrees, updated in
198 conjunction w/ :sgf-gametree and :monkey
199
200 :sgf-gametree -- one of the gametrees in :sgf-collection
201
202 :monkey -- vector of three elements: LOC, a pointer to a node on the
203 :sgf-gametree representing the most recently-played move
204 (the next move modifies the cdr of LOC); MEM, the simple
205 reverse-chronological list of previous LOC pointers; and
206 COUNT, the number of moves from the beginning of the game
207
208 :gnugo-color -- either \"black\" or \"white\"
209 :user-color
210 :last-mover
211
212 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
213 :waiting-start
214
215 :black-captures -- these are strings since gnugo.el doesn't do anything
216 :white-captures w/ the information besides display it in the mode line;
217 gory details in functions `gnugo-propertize-board-buffer'
218 and `gnugo-merge-showboard-results' (almost more effort
219 than they are worth!)
220
221 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
222 `gnugo-toggle-image-display' and `gnugo-refresh',
223 as well as gnugo-xpms.el (available elsewhere)
224
225 :all-yy -- list of 46 keywords used as the `category' text property
226 (so that their plists, typically w/ property `display' or
227 `do-not-display') are consulted by the Emacs display engine;
228 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
229 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
230
231 :lparen-ov -- overlays shuffled about to indicate the last move; only
232 :rparen-ov one is used when displaying using images
233
234 :last-user-bpos -- board position; keep the hapless human happy
235
236 As things stabilize probably more info will be added to this docstring."))
237 (put 'gnugo-put 'function-documentation docs)
238 (put 'gnugo-get 'function-documentation docs))
239
240 (defun gnugo-describe-internal-properties ()
241 "Pretty-print `gnugo-state' properties in another buffer.
242 Handle the big, slow-to-render, and/or uninteresting ones specially."
243 (interactive)
244 (let ((buf (current-buffer))
245 (d (gnugo-get :diamond))
246 acc)
247 (maphash (lambda (&rest args)
248 (case (car args)
249 ((:xpms :local-xpms)
250 (setcdr args (format "hash: %X (%d images)"
251 (sxhash (cadr args))
252 (length (cadr args)))))
253 (:sgf-collection
254 (setcdr args (length (cadr args))))
255 (:monkey
256 (let* ((value (cadr args))
257 (loc (aref value 0)))
258 (setcdr args (list
259 (length (aref value 1))
260 (length (cdr loc))
261 (car loc))))))
262 (setq acc (cons args acc)))
263 gnugo-state)
264 (switch-to-buffer (get-buffer-create
265 (format "%s*GNUGO Board Properties*"
266 (gnugo-get :diamond))))
267 (erase-buffer)
268 (emacs-lisp-mode)
269 (setq truncate-lines t)
270 (save-excursion
271 (let ((standard-output (current-buffer)))
272 (pp (reverse acc)))
273 (goto-char (point-min))
274 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
275 (if (string= "" d)
276 ".+\n"
277 ""))))
278 (while (re-search-forward rx (point-max) t)
279 (let ((pos (get-text-property (string-to-number (match-string 1))
280 'gnugo-position buf)))
281 (delete-region (+ 2 (match-beginning 0)) (point))
282 (insert (format " %S" pos))))))
283 (message "%d properties" (length acc))))
284
285 (defun gnugo-board-buffer-p (&optional buffer)
286 "Return non-nil if BUFFER is a GNUGO Board buffer."
287 (with-current-buffer (or buffer (current-buffer)) gnugo-state))
288
289 (defun gnugo-board-user-play-ok-p (&optional buffer)
290 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
291 (with-current-buffer (or buffer (current-buffer))
292 (and gnugo-state (not (gnugo-get :waitingp)))))
293
294 (defun gnugo-other (color)
295 (if (string= "black" color) "white" "black"))
296
297 (defun gnugo-gate (&optional in-progress-p)
298 (unless (gnugo-board-buffer-p)
299 (error "Wrong buffer -- try M-x gnugo"))
300 (unless (gnugo-get :proc)
301 (error "No \"gnugo\" process!"))
302 (when (gnugo-get :waitingp)
303 (error "Not your turn yet -- please wait for \"\(%s to play\)\""
304 (gnugo-get :user-color)))
305 (when (and (gnugo-get :game-over) in-progress-p)
306 (error "Sorry, game over")))
307
308 (defun gnugo-sentinel (proc string)
309 (let ((status (process-status proc)))
310 (when (or (eq status 'exit)
311 (eq status 'signal))
312 (let ((buf (process-buffer proc)))
313 (when (buffer-live-p buf)
314 (with-current-buffer buf
315 (setq mode-line-process '( " [%s]"))
316 (when (eq proc (gnugo-get :proc))
317 (gnugo-put :proc nil))))))))
318
319 (defun gnugo-send-line (line)
320 (let ((proc (gnugo-get :proc)))
321 (process-send-string proc line)
322 (process-send-string proc "\n")))
323
324 (defun gnugo-synchronous-send/return (message)
325 "Return (TIME . STRING) where TIME is that returned by `current-time' and
326 STRING omits the two trailing newlines. See also `gnugo-query'."
327 (when (gnugo-get :waitingp)
328 (error "Sorry, still waiting for %s to play" (gnugo-get :gnugo-color)))
329 (gnugo-put :sync-return "")
330 (let ((proc (gnugo-get :proc)))
331 (set-process-filter
332 proc (lambda (proc string)
333 (let* ((so-far (gnugo-get :sync-return))
334 (start (max 0 (- (length so-far) 2))) ; backtrack a little
335 (full (gnugo-put :sync-return (concat so-far string))))
336 (when (string-match "\n\n" full start)
337 (gnugo-put :sync-return
338 (cons (current-time) (substring full 0 -2)))))))
339 (gnugo-send-line message)
340 (let (rv)
341 ;; type change => break
342 (while (stringp (setq rv (gnugo-get :sync-return)))
343 (accept-process-output proc 30))
344 (gnugo-put :sync-return "")
345 rv)))
346
347 (defun gnugo-query (message-format &rest args)
348 "Return cleaned-up value of a call to `gnugo-synchronous-send/return'.
349 The TIME portion is omitted as well as the first two characters of the STRING
350 portion (corresponding to the status indicator in the Go Text Protocol). Use
351 this function when you are sure the command cannot fail. The first arg is
352 a format string applied to the rest of the args."
353 (substring (cdr (gnugo-synchronous-send/return
354 (apply 'format message-format args)))
355 2))
356
357 (defun gnugo-lsquery (message-format &rest args)
358 (split-string (apply 'gnugo-query message-format args)))
359
360 (defsubst gnugo-treeroot (prop)
361 (cdr (assq prop (car (gnugo-get :sgf-gametree)))))
362
363 (defun gnugo-goto-pos (pos)
364 "Move point to board position POS, a letter-number string."
365 (goto-char (point-min))
366 (forward-line (- (1+ (gnugo-treeroot :SZ))
367 (string-to-number (substring pos 1))))
368 (forward-char 1)
369 (forward-char (+ (if (= 32 (following-char)) 1 2)
370 (* 2 (- (let ((letter (aref pos 0)))
371 (if (> ?I letter)
372 letter
373 (1- letter)))
374 ?A)))))
375
376 (defun gnugo-f (frag)
377 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
378
379 (defun gnugo-yang (c)
380 (cdr (assq c '((?+ . hoshi)
381 (?. . empty)
382 (?X . (bmoku . bpmoku))
383 (?O . (wmoku . wpmoku))))))
384
385 (defun gnugo-yy (yin yang &optional momentaryp)
386 (gnugo-f (format "%d-%s"
387 yin (cond ((and (consp yang) momentaryp) (cdr yang))
388 ((consp yang) (car yang))
389 (t yang)))))
390
391 (defun gnugo-toggle-image-display ()
392 (unless (and (fboundp 'display-images-p) (display-images-p))
393 (error "Display does not support images, sorry"))
394 (require 'gnugo-xpms)
395 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
396 (error "Could not load `gnugo-xpms', sorry"))
397 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
398 (unless (eq fresh (gnugo-get :xpms))
399 (gnugo-put :xpms fresh)
400 (gnugo-put :all-yy nil)))
401 (let* ((new (not (gnugo-get :display-using-images)))
402 (act (if new 'display 'do-not-display)))
403 (mapc (lambda (yy)
404 (setcar (symbol-plist yy) act))
405 (or (gnugo-get :all-yy)
406 (gnugo-put :all-yy
407 (prog1 (mapcar (lambda (ent)
408 (let* ((k (car ent))
409 (yy (gnugo-yy (cdr k) (car k))))
410 (setplist yy `(not-yet ,(cdr ent)))
411 yy))
412 (gnugo-get :xpms))
413 (let ((imul (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
414 'not-yet))))
415 (gnugo-put :w-imul (car imul))
416 (gnugo-put :h-imul (cdr imul)))))))
417 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
418 (gnugo-put :highlight-last-move-spec
419 (if new
420 '((lambda (p)
421 (get (gnugo-yy (get-text-property p 'gnugo-yin)
422 (get-text-property p 'gnugo-yang)
423 t)
424 'display))
425 0 delete-overlay)
426 (gnugo-get :default-highlight-last-move-spec)))
427 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
428 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
429 (mapc 'delete-overlay (cdar group))
430 (setcdr (car group) nil))
431 (gnugo-put :wmul (if new (gnugo-get :w-imul) 1))
432 (gnugo-put :hmul (if new (gnugo-get :h-imul) 1))
433 (gnugo-put :display-using-images new)))
434
435 (defun gnugo-toggle-grid ()
436 "Turn the grid around the board on or off."
437 (interactive)
438 (funcall (if (memq :nogrid buffer-invisibility-spec)
439 'remove-from-invisibility-spec
440 'add-to-invisibility-spec)
441 :nogrid)
442 (save-excursion (gnugo-refresh)))
443
444 (defun gnugo-propertize-board-buffer ()
445 (erase-buffer)
446 (insert (substring (cdr (gnugo-synchronous-send/return "showboard")) 3))
447 (let* ((grid-props (list 'invisible :nogrid
448 'font-lock-face gnugo-grid-face))
449 (%gpad (gnugo-f 'gpad))
450 (%gspc (gnugo-f 'gspc))
451 (%lpad (gnugo-f 'lpad))
452 (%rpad (gnugo-f 'rpad))
453 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
454 (size (gnugo-treeroot :SZ))
455 (size-string (number-to-string size)))
456 (goto-char (point-min))
457 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
458 (skip-chars-forward " ")
459 (put-text-property (1- (point)) (point) 'category %gpad)
460 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
461 (forward-char 1)
462 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
463 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
464 (let* ((row (match-string-no-properties 1))
465 (edge (match-end 0))
466 (other-edge (+ edge (* 2 size) -1))
467 (right-empty (+ other-edge (length row) 1))
468 (top-p (string= size-string row))
469 (bot-p (string= "1" row)))
470 (let* ((nL (- edge 1 (length size-string)))
471 (nR (- edge 1))
472 (ov (make-overlay nL nR (current-buffer) t)))
473 (add-text-properties nL nR grid-props)
474 ;; We redundantly set `invisible' in the overlay to workaround
475 ;; a display bug whereby text *following* the overlaid text is
476 ;; displayed with the face of the overlaid text, but only when
477 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
478 ;; This has something to do w/ the bletcherous `before-string'.
479 (overlay-put ov 'invisible :nogrid)
480 (overlay-put ov 'category %lpad))
481 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
482 ((< other-edge p))
483 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
484 (truncate (- p edge) 2))
485 row))
486 (yin (let ((A-p (= edge p))
487 (Z-p (= (1- other-edge) p)))
488 (cond ((and top-p A-p) 1)
489 ((and top-p Z-p) 3)
490 ((and bot-p A-p) 7)
491 ((and bot-p Z-p) 9)
492 (top-p 2)
493 (bot-p 8)
494 (A-p 4)
495 (Z-p 6)
496 (t 5))))
497 (yang (gnugo-yang (char-after p))))
498 (add-text-properties p (1+ p)
499 `(gnugo-position
500 ,position
501 gnugo-yin
502 ,yin
503 gnugo-yang
504 ,yang
505 category
506 ,(gnugo-yy yin yang)
507 front-sticky
508 (gnugo-position gnugo-yin))))
509 (unless (= (1- other-edge) p)
510 (add-text-properties (1+ p) (+ 2 p) ispc-props)
511 (put-text-property p (+ 2 p) 'intangible ival)))
512 (add-text-properties (1+ other-edge) right-empty grid-props)
513 (goto-char right-empty)
514 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
515 (let ((prop (if (string= "WH" (match-string 1))
516 :white-captures
517 :black-captures))
518 (beg (match-beginning 2))
519 (end (match-end 2)))
520 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
521 (gnugo-put prop (match-string-no-properties 2))))
522 (end-of-line)
523 (put-text-property right-empty (point) 'category %rpad)
524 (forward-char 1)))
525 (add-text-properties (1- (point)) (point-max) grid-props)
526 (skip-chars-forward " ")
527 (put-text-property (1- (point)) (point) 'category %gpad)
528 (put-text-property (point) (progn (end-of-line) (point))
529 'category %gspc)))
530
531 (defun gnugo-merge-showboard-results ()
532 (let ((aft (substring (cdr (gnugo-synchronous-send/return "showboard")) 3))
533 (adj 1) ; string to buffer position adjustment
534 (sync "[0-9]+ stones$")
535 (bef (buffer-substring-no-properties (point-min) (point-max)))
536 (bef-start 0) (bef-idx 0)
537 (aft-start 0) (aft-idx 0)
538 aft-sync-backtrack mis inc cut new very-strange)
539 (while (numberp (setq mis (compare-strings bef bef-start nil
540 aft aft-start nil)))
541 (setq aft-sync-backtrack nil
542 inc (if (> 0 mis)
543 (- (+ 1 mis))
544 (- mis 1))
545 bef-idx (+ bef-start inc)
546 aft-idx (+ aft-start inc)
547 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
548 (match-end 0)
549 (1+ bef-idx))
550 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
551 (let ((peek (1- aft-idx)))
552 (while (not (= 32 (aref aft peek)))
553 (setq peek (1- peek)))
554 (setq aft-sync-backtrack (1+ peek))))
555 (match-end 0)
556 (1+ aft-idx))
557 cut (+ bef-idx adj
558 (if aft-sync-backtrack
559 (- aft-sync-backtrack aft-idx)
560 0)))
561 (goto-char cut)
562 (if aft-sync-backtrack
563 (let* ((asb aft-sync-backtrack)
564 (l-p (get-text-property cut :gnugo-cf))
565 (old-len (car l-p))
566 (capprop (cdr l-p))
567 (keep (text-properties-at cut)))
568 (setq new (substring aft asb (string-match " " aft asb)))
569 (plist-put keep :gnugo-cf (cons (length new) capprop))
570 (gnugo-put capprop new)
571 (delete-char old-len)
572 (insert (apply 'propertize new keep))
573 (setq adj (+ adj (- (length new) old-len))))
574 (setq new (aref aft aft-idx))
575 (insert-and-inherit (char-to-string new))
576 (let ((yin (get-text-property cut 'gnugo-yin))
577 (yang (gnugo-yang new)))
578 (add-text-properties cut (1+ cut)
579 `(gnugo-yang
580 ,yang
581 category
582 ,(gnugo-yy yin yang))))
583 (delete-char 1)
584 ;; do this last to avoid complications w/ font lock
585 ;; (this also means we cannot include `intangible' in `front-sticky')
586 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
587 (put-text-property cut (1+ cut) 'intangible very-strange))))))
588
589 (defun gnugo-move-history (&optional rsel)
590 "Determine and return the game's move history.
591 Optional arg RSEL controls side effects and return value.
592 If nil, display the history in the echo area as \"(N moves)\"
593 followed by the space-separated list of moves. When called
594 interactively with a prefix arg (i.e., RSEL is `(4)'), display
595 similarly, but suffix with the mover (either \":B\" or \":W\").
596 If RSEL is the symbol `car' return the most-recent move; if
597 `cadr', the next-to-most-recent move; if `count' the number of
598 moves thus far.
599
600 For all other values of RSEL, do nothing and return nil."
601 (interactive "P")
602 (let ((size (gnugo-treeroot :SZ))
603 col
604 (mem (aref (gnugo-get :monkey) 1))
605 acc node mprop move)
606 (cl-labels
607 ((as-pos (cc) (if (string= "tt" cc)
608 "PASS"
609 (setq col (aref cc 0))
610 (format "%c%d"
611 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
612 (- size (- (aref cc 1) ?a)))))
613 (next (byp) (when (setq node (caar mem)
614 mprop (or (assq :B node)
615 (assq :W node)))
616 (setq move (as-pos (cdr mprop))
617 mem (cdr mem))
618 (push (if byp
619 (format "%s%s" move (car mprop))
620 move)
621 acc)))
622 (tell () (message "(%d moves) %s"
623 (length acc)
624 (mapconcat 'identity (nreverse acc) " "))))
625 (cond
626 ((not rsel) (while (next nil)) (tell))
627 ((equal '(4) rsel) (while (next t)) (tell))
628 ((eq 'car rsel) (car (next nil)))
629 ((eq 'cadr rsel) (next nil) (car (next nil)))
630 ((eq 'count rsel) (aref (gnugo-get :monkey) 2))))))
631
632 (defun gnugo-note (property value &optional movep mogrifyp)
633 (when mogrifyp
634 (let ((sz (gnugo-treeroot :SZ)))
635 (cl-labels
636 ((mog (pos) (if (string= "PASS" pos)
637 "tt"
638 (let* ((col (aref pos 0))
639 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
640 (two (+ ?a (- sz (string-to-number
641 (substring pos 1))))))
642 (format "%c%c" one two)))))
643 (setq value (if (consp value)
644 (mapcar #'mog value)
645 (mog value))))))
646 (let* ((fruit (list (cons property value)))
647 (monkey (gnugo-get :monkey))
648 (loc (aref monkey 0)))
649 (if movep
650 (let ((mem (aref monkey 1)))
651 ;; todo: do variation check/merge/branch here.
652 (setcdr loc (list fruit))
653 (aset monkey 0 (setq loc (cdr loc)))
654 (aset monkey 1 (cons loc mem))
655 (aset monkey 2 (1+ (aref monkey 2))))
656 (setcdr (last (car loc)) fruit))))
657
658 (defun gnugo-close-game (end-time resign)
659 (gnugo-put :game-end-time end-time)
660 (let ((now (or end-time (current-time))))
661 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
662 (cadr now))))
663 (gnugo-put :game-over
664 (if (or (eq t resign)
665 (and (stringp resign)
666 (string-match "[BW][+][Rr]esign" resign)))
667 (cl-labels
668 ((ls (color) (mapcar
669 (lambda (x)
670 (cons (list color)
671 (split-string x)))
672 (split-string
673 (gnugo-query "worm_stones %s" color)
674 "\n"))))
675 (let ((live (append (ls "black") (ls "white"))))
676 `((live ,@live)
677 (dead))))
678 (let ((dd (gnugo-query "dragon_data"))
679 (start 0) mem color ent live dead)
680 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
681 dd start)
682 (setq mem (match-string 1 dd)
683 color (match-string 2 dd)
684 start (match-end 0)
685 ent (cons (list color)
686 (sort (gnugo-lsquery "dragon_stones %s" mem)
687 'string<)))
688 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
689 dd start)
690 (if (match-string 2 dd)
691 (push ent live)
692 (push ent dead))
693 (setq start (match-end 0)))
694 `((live ,@live)
695 (dead ,@dead))))))
696
697 (defun gnugo-push-move (userp move)
698 (let* ((color (gnugo-get (if userp :user-color :gnugo-color)))
699 (start (gnugo-get :waiting-start))
700 (now (current-time))
701 (resignp (string= "resign" move))
702 (passp (string= "PASS" move))
703 (head (gnugo-move-history 'car))
704 (onep (and head (string= "PASS" head)))
705 (donep (or resignp (and onep passp))))
706 (unless passp
707 (gnugo-merge-showboard-results))
708 (gnugo-put :last-mover color)
709 (when userp
710 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
711 (gnugo-note (if (string= "black" color) :B :W) move t (not resignp))
712 (when resignp
713 (gnugo-note :EV "resignation"))
714 (when start
715 (gnugo-put :last-waiting (cadr (time-subtract now start))))
716 (when donep
717 (gnugo-close-game now resignp))
718 (gnugo-put :waiting-start (and (not donep) now))
719 donep))
720
721 (defun gnugo-venerate (yin yang)
722 (let* ((fg-yy (gnugo-yy yin yang))
723 (fg-disp (or (get fg-yy 'display)
724 (get fg-yy 'do-not-display)))
725 (fg-data (plist-get (cdr fg-disp) :data))
726 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
727 (bg-disp (or (get bg-yy 'display)
728 (get bg-yy 'do-not-display)))
729 (bg-data (plist-get (cdr bg-disp) :data))
730 (bop (lambda (s)
731 (let* ((start 0)
732 (ncolors
733 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
734 (setq start (match-end 0))
735 (string-to-number (match-string 1 s)))))
736 (while (and (<= 0 ncolors) (string-match ",\n" s start))
737 (setq start (match-end 0)
738 ncolors (1- ncolors)))
739 (string-match "\"" s start)
740 (match-end 0))))
741 (new (copy-sequence fg-data))
742 (lx (length fg-data))
743 (lb (length bg-data))
744 (sx (funcall bop fg-data))
745 (sb (funcall bop bg-data))
746 (color-key (aref new sx))) ; blech, heuristic
747 (while (< sx lx)
748 (when (and (not (= color-key (aref new sx)))
749 (< 0 (random 4)))
750 (aset new sx (aref bg-data sb)))
751 (incf sx)
752 (incf sb))
753 (create-image new 'xpm t :ascent 'center)))
754
755 (defun gnugo-refresh (&optional nocache)
756 "Update GNUGO Board buffer display.
757 While a game is in progress, parenthesize the last-played stone (no parens
758 for pass). If the buffer is currently displayed in the selected window,
759 recenter the board (presuming there is extra space in the window). Update
760 the mode line. Lastly, move point to the last position played by the user,
761 if that move was not a pass.
762
763 Prefix arg NOCACHE requests complete reconstruction of the display, which may
764 be slow. (This should normally be unnecessary; specify it only if the display
765 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
766 its move."
767 (interactive "P")
768 (when (and nocache (not (gnugo-get :waitingp)))
769 (gnugo-propertize-board-buffer))
770 (let* ((last-mover (gnugo-get :last-mover))
771 (other (gnugo-other last-mover))
772 (move (gnugo-move-history 'car))
773 (game-over (gnugo-get :game-over))
774 window last)
775 ;; last move
776 (when move
777 (let ((l-ov (gnugo-get :lparen-ov))
778 (r-ov (gnugo-get :rparen-ov)))
779 (if (member move '("PASS" "resign"))
780 (mapc 'delete-overlay (list l-ov r-ov))
781 (gnugo-goto-pos move)
782 (let* ((p (point))
783 (hspec (gnugo-get :highlight-last-move-spec))
784 (display-value (nth 0 hspec))
785 (l-offset (nth 1 hspec))
786 (l-new-pos (+ p l-offset))
787 (r-action (nth 2 hspec)))
788 (overlay-put l-ov 'display
789 (if (functionp display-value)
790 (funcall display-value p)
791 display-value))
792 (move-overlay l-ov l-new-pos (1+ l-new-pos))
793 (if r-action
794 (funcall r-action r-ov)
795 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
796 ;; buffer name
797 (rename-buffer (concat (gnugo-get :diamond)
798 (if game-over
799 (format "%s(game over)"
800 (if (string= move "resign")
801 (concat move "ation ")
802 ""))
803 (format "%s(%s to play)"
804 (if move (concat move " ") "")
805 other))))
806 ;; pall of death
807 (when game-over
808 (let ((live (cdr (assq 'live game-over)))
809 (dead (cdr (assq 'dead game-over)))
810 p pall)
811 (unless (eq game-over (get-text-property 1 'game-over))
812 (dolist (group (append live dead))
813 (dolist (pos (cdr group))
814 (gnugo-goto-pos pos)
815 (setq p (point))
816 (put-text-property p (1+ p) 'group group)))
817 (put-text-property 1 2 'game-over game-over))
818 (dolist (group live)
819 (when (setq pall (cdar group))
820 (mapc 'delete-overlay pall)
821 (setcdr (car group) nil)))
822 (dolist (group dead)
823 (unless (cdar group)
824 (let (ov pall c (color (caar group)))
825 (setq c (if (string= "black" color) "x" "o"))
826 (dolist (pos (cdr group))
827 (gnugo-goto-pos pos)
828 (setq p (point) ov (make-overlay p (1+ p)))
829 (overlay-put
830 ov 'display
831 (if (gnugo-get :display-using-images)
832 ;; respect the dead individually; it takes more time
833 ;; but that's not a problem (for them)
834 (gnugo-venerate (get-text-property p 'gnugo-yin)
835 (gnugo-yang (aref (upcase c) 0)))
836 (propertize c 'face 'font-lock-warning-face)))
837 (push ov pall))
838 (setcdr (car group) pall))))))
839 ;; window update
840 (when (setq window (get-buffer-window (current-buffer)))
841 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
842 (size (gnugo-treeroot :SZ))
843 (under10p (< size 10))
844 (h (- (truncate (- (window-height window)
845 (* size (gnugo-get :hmul))
846 (if gridp 2 0))
847 2)
848 (if gridp 0 1)))
849 (edges (window-edges window))
850 (right-w-edge (nth 2 edges))
851 (avail-width (- right-w-edge (nth 0 edges)))
852 (wmul (gnugo-get :wmul))
853 (imagesp (symbol-plist (gnugo-f 'ispc)))
854 (w (/ (- avail-width
855 (* size wmul)
856 (if imagesp
857 0
858 (1- size))
859 2 ; between board and grid
860 (if gridp
861 (if under10p 2 4)
862 0))
863 2.0)))
864 (dolist (pair `((tpad . ,(if (and h (< 0 h))
865 `(display ,(make-string h 10))
866 '(invisible :nogrid)))
867 (gpad . (display
868 (space :align-to
869 ,(+ w
870 2.0
871 (cond (imagesp (+ (* 0.5 wmul)
872 (if under10p
873 -0.5
874 0.5)))
875 (under10p 0)
876 (t 1))))))
877 (gspc . ,(when imagesp
878 `(display (space-width ,(- wmul 1.0)))))
879 (lpad . ,(let ((d `(display (space :align-to ,w))))
880 ;; We distinguish between these cases to
881 ;; workaround a display bug whereby the
882 ;; `before-string' is omitted entirely (not
883 ;; rendered) when interacting w/ the text
884 ;; mode last-move left-paren for moves in
885 ;; column A.
886 (if gridp
887 `(before-string
888 ,(apply 'propertize " " d))
889 d)))
890 (rpad . (display
891 (space :align-to ,(1- avail-width))))))
892 (setplist (gnugo-f (car pair)) (cdr pair)))))
893 ;; mode line update
894 (let ((cur (gnugo-get :mode-line)))
895 (unless (equal cur gnugo-mode-line)
896 (setq cur gnugo-mode-line)
897 (gnugo-put :mode-line cur)
898 (gnugo-put :mode-line-form
899 (cond ((stringp cur)
900 (setq cur (copy-sequence cur))
901 (let (acc cut c)
902 (while (setq cut (string-match "~[bwpmtu]" cur))
903 (aset cur cut ?%)
904 (setq cut (1+ cut) c (aref cur cut))
905 (aset cur cut ?s)
906 (push
907 `(,(intern (format "squig-%c" c))
908 ,(case c
909 (?b '(or (gnugo-get :black-captures) 0))
910 (?w '(or (gnugo-get :white-captures) 0))
911 (?p '(gnugo-other (gnugo-get :last-mover)))
912 (?t '(let ((ws (gnugo-get :waiting-start)))
913 (if ws
914 (cadr (time-since ws))
915 "-")))
916 (?u '(or (gnugo-get :last-waiting) "-"))
917 (?m '(gnugo-move-history 'count))))
918 acc))
919 `(let ,(delete-dups (copy-sequence acc))
920 (format ,cur ,@(reverse (mapcar 'car acc))))))
921 (t cur))))
922 (let ((form (gnugo-get :mode-line-form)))
923 (setq mode-line-process
924 (and form
925 ;; this dynamicism is nice but excessive in its wantonness
926 ;;- `(" [" (:eval ,form) "]")
927 ;; this dynamicism is ok because the user triggers it
928 (list (format " [%s]" (eval form))))))
929 (force-mode-line-update))
930 ;; last user move
931 (when (setq last (gnugo-get :last-user-bpos))
932 (gnugo-goto-pos last))))
933
934 ;;;---------------------------------------------------------------------------
935 ;;; Game play actions
936
937 (defun gnugo-get-move-insertion-filter (proc string)
938 (with-current-buffer (process-buffer proc)
939 (let* ((so-far (gnugo-get :get-move-string))
940 (full (gnugo-put :get-move-string (concat so-far string))))
941 (when (string-match "^= \\(.+\\)\n\n" full)
942 (let ((pos-or-pass (match-string 1 full)))
943 (gnugo-put :get-move-string nil)
944 (gnugo-put :waitingp nil)
945 (gnugo-push-move nil pos-or-pass)
946 (let ((buf (current-buffer)))
947 (let (inhibit-gnugo-refresh)
948 (run-hooks 'gnugo-post-move-hook)
949 (unless inhibit-gnugo-refresh
950 (with-current-buffer buf
951 (gnugo-refresh))))))))))
952
953 (defun gnugo-get-move (color)
954 (gnugo-put :waitingp t)
955 (set-process-filter (gnugo-get :proc) 'gnugo-get-move-insertion-filter)
956 (gnugo-send-line (concat "genmove " color))
957 (accept-process-output))
958
959 (defun gnugo-cleanup ()
960 (when (gnugo-board-buffer-p)
961 (unless (zerop (buffer-size))
962 (message "Thank you for playing GNU Go."))
963 (mapc (lambda (sym)
964 (setplist sym nil) ; "...is next to fordliness." --Huxley
965 (unintern sym))
966 (append (gnugo-get :all-yy)
967 (mapcar 'gnugo-f
968 '(anim
969 tpad
970 gpad
971 gspc
972 lpad
973 rpad
974 ispc))))
975 (setq gnugo-state nil)))
976
977 (defun gnugo-position ()
978 (or (get-text-property (point) 'gnugo-position)
979 (error "Not a proper position point")))
980
981 (defun gnugo-move ()
982 "Make a move on the GNUGO Board buffer.
983 The position is computed from current point.
984 Signal error if done out-of-turn or if game-over.
985 To start a game try M-x gnugo."
986 (interactive)
987 (gnugo-gate t)
988 (let* ((buf (current-buffer))
989 (pos (gnugo-position))
990 (move (format "play %s %s" (gnugo-get :user-color) pos))
991 (accept (cdr (gnugo-synchronous-send/return move))))
992 (unless (= ?= (aref accept 0))
993 (error "%s" accept))
994 (gnugo-push-move t pos) ; value always nil for non-pass move
995 (let (inhibit-gnugo-refresh)
996 (run-hooks 'gnugo-post-move-hook)
997 (unless inhibit-gnugo-refresh
998 (with-current-buffer buf
999 (gnugo-refresh))))
1000 (with-current-buffer buf
1001 (gnugo-get-move (gnugo-get :gnugo-color)))))
1002
1003 (defun gnugo-mouse-move (e)
1004 "Do `gnugo-move' at mouse location."
1005 (interactive "@e")
1006 (mouse-set-point e)
1007 (when (looking-at "[.+]")
1008 (gnugo-move)))
1009
1010 (defun gnugo-pass ()
1011 "Make a pass on the GNUGO Board buffer.
1012 Signal error if done out-of-turn or if game-over.
1013 To start a game try M-x gnugo."
1014 (interactive)
1015 (gnugo-gate t)
1016 (let ((accept (cdr (gnugo-synchronous-send/return
1017 (format "play %s PASS" (gnugo-get :user-color))))))
1018 (unless (= ?= (aref accept 0))
1019 (error "%s" accept)))
1020 (let ((donep (gnugo-push-move t "PASS"))
1021 (buf (current-buffer)))
1022 (let (inhibit-gnugo-refresh)
1023 (run-hooks 'gnugo-post-move-hook)
1024 (unless inhibit-gnugo-refresh
1025 (with-current-buffer buf
1026 (gnugo-refresh))))
1027 (unless donep
1028 (with-current-buffer buf
1029 (gnugo-get-move (gnugo-get :gnugo-color))))))
1030
1031 (defun gnugo-mouse-pass (e)
1032 "Do `gnugo-pass' at mouse location."
1033 (interactive "@e")
1034 (mouse-set-point e)
1035 (gnugo-pass))
1036
1037 (defun gnugo-resign ()
1038 (interactive)
1039 (gnugo-gate t)
1040 (if (not (y-or-n-p "Resign? "))
1041 (message "(not resigning)")
1042 (gnugo-push-move t "resign")
1043 (gnugo-refresh)))
1044
1045 (defun gnugo-animate-group (command)
1046 (message "Computing %s ..." command)
1047 (let* ((pos (gnugo-position))
1048 (orig-b-m-p (buffer-modified-p))
1049 (stones (if (memq (char-after) '(?X ?O))
1050 (gnugo-lsquery "%s %s" command pos)
1051 (error "No stone at %s" pos))))
1052 (message "Computing %s ... %s in group." command (length stones))
1053 (setplist (gnugo-f 'anim) nil)
1054 (let* ((spec (let ((spec (split-string gnugo-animation-string "" t)))
1055 (cond ((gnugo-get :display-using-images)
1056 (let* ((yin (get-text-property (point) 'gnugo-yin))
1057 (yang (gnugo-yang (char-after)))
1058 (up (get (gnugo-yy yin yang t) 'display))
1059 (dn (get (gnugo-yy yin yang) 'display))
1060 flip-flop)
1061 (mapcar (lambda (c)
1062 (if (setq flip-flop (not flip-flop))
1063 dn up))
1064 (mapcar 'string-to-char spec))))
1065 (t spec))))
1066 (cell (list spec))
1067 (ovs (save-excursion
1068 (mapcar (lambda (pos)
1069 (gnugo-goto-pos pos)
1070 (let* ((p (point))
1071 (ov (make-overlay p (1+ p))))
1072 (overlay-put ov 'category (gnugo-f 'anim))
1073 (overlay-put ov 'priority most-positive-fixnum)
1074 ov))
1075 stones))))
1076 (setplist (gnugo-f 'anim) (cons 'display cell))
1077 (while (and (cdr spec) ; let last linger lest levity lost
1078 (sit-for 0.08675309)) ; jenny jenny i got your number...
1079 (setcar cell (setq spec (cdr spec)))
1080 ;; Force redisplay of overlays.
1081 (set-buffer-modified-p orig-b-m-p))
1082 (sit-for 5)
1083 (mapc 'delete-overlay ovs)
1084 t)))
1085
1086 (defun gnugo-display-group-data (command buffer-name)
1087 (message "Computing %s ..." command)
1088 (let ((data (cdr (gnugo-synchronous-send/return
1089 (format "%s %s" command (gnugo-position))))))
1090 (switch-to-buffer buffer-name)
1091 (erase-buffer)
1092 (insert data))
1093 (message "Computing %s ... done." command))
1094
1095 (defun gnugo-worm-stones ()
1096 "In the GNUGO Board buffer, animate \"worm\" at current position.
1097 Signal error if done out-of-turn or if game-over.
1098 See variable `gnugo-animation-string' for customization."
1099 (interactive)
1100 (gnugo-gate)
1101 (gnugo-animate-group "worm_stones"))
1102
1103 (defun gnugo-worm-data ()
1104 "Display in another buffer data from \"worm\" at current position.
1105 Signal error if done out-of-turn or if game-over."
1106 (interactive)
1107 (gnugo-gate)
1108 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1109
1110 (defun gnugo-dragon-stones ()
1111 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1112 Signal error if done out-of-turn or if game-over.
1113 See variable `gnugo-animation-string' for customization."
1114 (interactive)
1115 (gnugo-gate)
1116 (gnugo-animate-group "dragon_stones"))
1117
1118 (defun gnugo-dragon-data ()
1119 "Display in another buffer data from \"dragon\" at current position.
1120 Signal error if done out-of-turn or if game-over."
1121 (interactive)
1122 (gnugo-gate)
1123 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1124
1125 (defun gnugo-toggle-dead-group ()
1126 "In a GNUGO Board buffer, during game-over, toggle a group as dead.
1127 The group is selected from current position (point). Signal error if
1128 not in game-over or if there is no group at that position.
1129
1130 In the context of GNU Go, a group is called a \"dragon\" and may be
1131 composed of more than one \"worm\" (set of directly-connected stones).
1132 It is unclear to the gnugo.el author whether or not GNU Go supports
1133 - considering worms as groups in their own right; and
1134 - toggling group aliveness via GTP.
1135 Due to these uncertainties, this command is only half complete; the
1136 changes you may see in Emacs are not propagated to the gnugo subprocess.
1137 Thus, GTP commands like `final_score' may give unexpected results.
1138
1139 If you are able to expose via GTP `change_dragon_status' in utils.c,
1140 you may consider modifying the `gnugo-toggle-dead-group' source code
1141 to enable full functionality."
1142 (interactive)
1143 (let ((game-over (or (gnugo-get :game-over)
1144 (error "Sorry, game still in play")))
1145 (group (or (get-text-property (point) 'group)
1146 (error "No stone at that position")))
1147 (now (current-time)))
1148 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1149 (cadr now)))
1150 (let ((live (assq 'live game-over))
1151 (dead (assq 'dead game-over))
1152 bef now)
1153 (if (memq group live)
1154 (setq bef live now dead)
1155 (setq bef dead now live))
1156 (setcdr bef (delq group (cdr bef)))
1157 (setcdr now (cons group (cdr now)))
1158 ;; disabled permanently -- too wrong
1159 (when nil
1160 (cl-labels
1161 ((populate (group)
1162 (let ((color (caar group)))
1163 (dolist (stone (cdr group))
1164 (gnugo-query "play %s %s" color stone)))))
1165 (if (eq now live)
1166 (populate group)
1167 ;; drastic (and wrong -- clobbers capture info, etc)
1168 (gnugo-query "clear_board")
1169 (mapc #'populate (cdr live)))))
1170 ;; here is the desired interface (to be enabled Some Day)
1171 (when nil
1172 (gnugo-query "change_dragon_status %s %s"
1173 (cadr group) (if (eq now live)
1174 'alive
1175 'dead)))))
1176 (save-excursion
1177 (gnugo-refresh)))
1178
1179 (defun gnugo-estimate-score ()
1180 "Display estimated score of a game of GNU Go.
1181 Output includes number of stones on the board and number of stones
1182 captured by each player, and the estimate of who has the advantage (and
1183 by how many stones)."
1184 (interactive)
1185 (message "Est.score ...")
1186 (let ((black (length (gnugo-lsquery "list_stones black")))
1187 (white (length (gnugo-lsquery "list_stones white")))
1188 (black-captures (gnugo-query "captures black"))
1189 (white-captures (gnugo-query "captures white"))
1190 (est (gnugo-query "estimate_score")))
1191 ;; might as well update this
1192 (gnugo-put :black-captures black-captures)
1193 (gnugo-put :white-captures white-captures)
1194 (message "Est.score ... B %s %s | W %s %s | %s"
1195 black black-captures white white-captures est)))
1196
1197 (defun gnugo-write-sgf-file (filename)
1198 "Save the game history to FILENAME (even if unfinished).
1199 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1200 (interactive "FWrite game as SGF file: ")
1201 (when (and (file-exists-p filename)
1202 (not (y-or-n-p "File exists. Continue? ")))
1203 (error "Not writing %s" filename))
1204 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1205 (set-buffer-modified-p nil))
1206
1207 (defun gnugo-read-sgf-file (filename)
1208 "Load the first game tree from FILENAME, a file in SGF format."
1209 (interactive "fSGF file to load: ")
1210 (when (file-directory-p filename)
1211 (error "Cannot load a directory (try a filename with extension .sgf)"))
1212 (let (ans play wait samep coll)
1213 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1214 ;; todo: skip it altogether when confident about `gnugo/sgf-read-file'
1215 (unless (= ?= (aref (setq ans (cdr (gnugo-synchronous-send/return
1216 (format "loadsgf %s"
1217 (expand-file-name filename)))))
1218 0))
1219 (error "%s" ans))
1220 (setq play (substring ans 2)
1221 wait (gnugo-other play)
1222 samep (string= (gnugo-get :user-color) play))
1223 (gnugo-put :last-mover wait)
1224 (unless samep
1225 (gnugo-put :gnugo-color wait)
1226 (gnugo-put :user-color play))
1227 (gnugo-put :sgf-collection (setq coll (gnugo/sgf-read-file filename)))
1228 (gnugo-put :sgf-gametree
1229 (nth (let ((n (length coll)))
1230 ;; This is better:
1231 ;; (if (= 1 n)
1232 ;; 0
1233 ;; (let* ((q (format "Which game? (1-%d)" n))
1234 ;; (choice (1- (read-number q 1))))
1235 ;; (if (and (< -1 choice) (< choice n))
1236 ;; choice
1237 ;; (message "(Selecting the first game)")
1238 ;; 0)))
1239 ;; but this is what we use (for now) to accomodate
1240 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1241 (unless (= 1 n)
1242 (message "(Selecting the first game)"))
1243 0)
1244 coll))
1245 (let* ((tree (gnugo-get :sgf-gametree))
1246 (loc tree)
1247 (count 0)
1248 mem node play game-over)
1249 (while (setq node (car loc))
1250 (when (setq play (or (assq :B node)
1251 (assq :W node)))
1252 ;; SGF[4] allows "" to mean PASS. For now,
1253 ;; we normalize here instead of at the lower layer.
1254 (when (string= "" (cdr play))
1255 (setcdr play "tt"))
1256 (incf count)
1257 (push loc mem))
1258 (setq loc (cdr loc)))
1259 (gnugo-put :game-over
1260 (setq game-over
1261 (or (cdr (assq :RE (car tree)))
1262 (and (cdr mem)
1263 (equal '("tt" "tt")
1264 (let ((order (if (string= "black" wait)
1265 '(:B :W)
1266 '(:W :B))))
1267 (mapcar (lambda (pk)
1268 (cdr (assq (funcall pk order)
1269 (car (funcall pk mem)))))
1270 '(car cadr))))
1271 'two-passes))))
1272 (gnugo-put :monkey
1273 (vector (or (car mem) (gnugo-get :sgf-gametree))
1274 mem
1275 count))
1276 (when (and game-over
1277 ;; (maybe) todo: user var to inhibit (can be slow)
1278 t)
1279 (gnugo-close-game nil game-over)))
1280 (gnugo-refresh t)
1281 (message "GNU Go %splays as %s, you as %s (%s)"
1282 (if samep "" "now ")
1283 wait play (if samep
1284 "as before"
1285 "NOTE: this is a switch!"))))
1286
1287 (defun gnugo-magic-undo (spec &optional noalt)
1288 "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1289 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1290 check that the position is occupied by a stone of the user's color,
1291 and if so, remove moves from the history until that position is clear.
1292 If SPEC is a positive number, remove exactly that many moves from the
1293 history, signaling an error if the history is exhausted before finishing.
1294 If SPEC is not recognized, signal \"bad spec\" error.
1295
1296 Refresh the board for each move undone. If (in the case where SPEC is
1297 a number) after finishing, the color to play is not the user's color,
1298 schedule a move by GNU Go.
1299
1300 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1301 turn to play. Optional second arg NOALT non-nil inhibits this."
1302 (gnugo-gate)
1303 (let* ((n 0)
1304 (monkey (gnugo-get :monkey))
1305 (mem (aref monkey 1))
1306 (count (aref monkey 2))
1307 done ans)
1308 (cond ((and (numberp spec) (< 0 spec))
1309 (setq n spec done (lambda () (zerop n))))
1310 ((string-match "^[a-z]" spec)
1311 (let ((pos (upcase spec)))
1312 (setq done `(lambda ()
1313 (gnugo-goto-pos ,pos)
1314 (memq (char-after) '(?. ?+))))
1315 (when (funcall done)
1316 (error "%s already clear" pos))
1317 (let ((u (gnugo-get :user-color)))
1318 (when (= (save-excursion
1319 (gnugo-goto-pos pos)
1320 (char-after))
1321 (if (string= "black" u)
1322 ?O
1323 ?X))
1324 (error "%s not occupied by %s" pos u)))))
1325 (t (error "Bad spec: %S" spec)))
1326 (when (gnugo-get :game-over)
1327 (gnugo-put :game-over nil))
1328 (while (not (funcall done))
1329 (setq ans (cdr (gnugo-synchronous-send/return "undo")))
1330 (unless (= ?= (aref ans 0))
1331 (error "%s" ans))
1332 (aset monkey 2 (decf count))
1333 (aset monkey 1 (setq mem (cdr mem)))
1334 (aset monkey 0 (or (car mem) (gnugo-get :sgf-gametree)))
1335 (gnugo-put :last-mover (gnugo-other (gnugo-get :last-mover)))
1336 (gnugo-merge-showboard-results) ; all
1337 (gnugo-refresh) ; this
1338 (decf n) ; is
1339 (redisplay))) ; eye candy
1340 (let* ((ulastp (string= (gnugo-get :last-mover) (gnugo-get :user-color)))
1341
1342 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1343 (gnugo-put :last-user-bpos (if (and ubpos (not (string= "PASS" ubpos)))
1344 ubpos
1345 (gnugo-get :center-position)))
1346 (gnugo-refresh t)
1347 ;; preserve restricted-functionality semantics (todo: remove restriction)
1348 (setcdr (aref (gnugo-get :monkey) 0) nil)
1349 (when (and ulastp (not noalt))
1350 (gnugo-get-move (gnugo-get :gnugo-color)))))
1351
1352 (defun gnugo-undo-one-move ()
1353 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1354 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1355 See also `gnugo-undo-two-moves'."
1356 (interactive)
1357 (gnugo-gate)
1358 (gnugo-magic-undo 1 t))
1359
1360 (defun gnugo-undo-two-moves ()
1361 "Undo a pair of moves (GNU Go's and yours).
1362 However, if you are the last mover, undo only one move.
1363 Regardless, after undoing, it is your turn to play again."
1364 (interactive)
1365 (gnugo-gate)
1366 (gnugo-magic-undo (if (string= (gnugo-get :user-color)
1367 (gnugo-get :last-mover))
1368 1
1369 2)))
1370
1371 (defun gnugo-display-final-score ()
1372 "Display final score and other info in another buffer (when game over).
1373 If the game is still ongoing, Emacs asks if you wish to stop play (by
1374 making sure two \"pass\" moves are played consecutively, if necessary).
1375 Also, add the `:RE' SGF property to the root node of the game tree."
1376 (interactive)
1377 (unless (or (gnugo-get :game-over)
1378 (and (not (gnugo-get :waitingp))
1379 (y-or-n-p "Game still in play. Stop play now? ")))
1380 (error "Sorry, game still in play"))
1381 (unless (gnugo-get :game-over)
1382 (cl-labels
1383 ((pass (userp)
1384 (message "Playing PASS for %s ..."
1385 (gnugo-get (if userp :user-color :gnugo-color)))
1386 (sit-for 1)
1387 (gnugo-push-move userp "PASS")))
1388 (unless (pass t)
1389 (pass nil)))
1390 (gnugo-refresh)
1391 (sit-for 3))
1392 (let ((b= " Black = ")
1393 (w= " White = ")
1394 (res (let* ((node (car (aref (gnugo-get :monkey) 0)))
1395 (event (and node (cdr (assq :EV node)))))
1396 (and event (string= "resignation" event)
1397 (if (assq :B node) "black" "white"))))
1398 blurb result)
1399 (if res
1400 (setq blurb (list
1401 (format "%s wins.\n"
1402 (substring (if (= ?b (aref res 0)) w= b=)
1403 3 8))
1404 "The game is over.\n"
1405 (format "Resignation by %s.\n" res))
1406 result (concat (upcase (substring (gnugo-other res) 0 1))
1407 "+Resign"))
1408 (message "Computing final score ...")
1409 (let* ((live (cdr (assq 'live (gnugo-get :game-over))))
1410 (dead (cdr (assq 'dead (gnugo-get :game-over))))
1411 (seed (gnugo-get :scoring-seed))
1412 (terr-q (format "final_status_list %%s_territory %d" seed))
1413 (terr "territory")
1414 (capt "captures")
1415 (b-terr (length (gnugo-lsquery terr-q "black")))
1416 (w-terr (length (gnugo-lsquery terr-q "white")))
1417 (b-capt (string-to-number (gnugo-get :black-captures)))
1418 (w-capt (string-to-number (gnugo-get :white-captures)))
1419 (komi (gnugo-treeroot :KM)))
1420 (setq blurb (list "The game is over. Final score:\n")
1421 result (gnugo-query "final_score %d" seed))
1422 (cond ((string= "Chinese" (gnugo-treeroot :RU))
1423 (dolist (group live)
1424 (let ((count (length (cdr group))))
1425 (if (string= "black" (caar group))
1426 (setq b-terr (+ b-terr count))
1427 (setq w-terr (+ w-terr count)))))
1428 (dolist (group dead)
1429 (let* ((color (caar group))
1430 (count (length (cdr group))))
1431 (if (string= "black" color)
1432 (setq w-terr (+ count w-terr))
1433 (setq b-terr (+ count b-terr)))))
1434 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
1435 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
1436 w-terr terr komi 'komi (+ w-terr komi))
1437 blurb))
1438 (t
1439 (dolist (group dead)
1440 (let* ((color (caar group))
1441 (adjust (* 2 (length (cdr group)))))
1442 (if (string= "black" color)
1443 (setq w-terr (+ adjust w-terr))
1444 (setq b-terr (+ adjust b-terr)))))
1445 (push (format "%s%d %s + %s %s = %3.1f\n" b=
1446 b-terr terr
1447 b-capt capt
1448 (+ b-terr b-capt))
1449 blurb)
1450 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
1451 w-terr terr
1452 w-capt capt
1453 komi 'komi
1454 (+ w-terr w-capt komi))
1455 blurb)))
1456 (push (if (string= "0" result)
1457 "The game is a draw.\n"
1458 (format "%s wins by %s.\n"
1459 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
1460 (substring result 2)))
1461 blurb)
1462 (message "Computing final score ... done")))
1463 ;; extra info
1464 (when (gnugo-get :game-end-time)
1465 (push "\n" blurb)
1466 (dolist (spec '(("Game start" . :game-start-time)
1467 (" end" . :game-end-time)))
1468 (push (format-time-string
1469 (concat (car spec) ": %Y-%m-%d %H:%M:%S %z\n")
1470 (gnugo-get (cdr spec)))
1471 blurb)))
1472 (setq blurb (apply 'concat (nreverse blurb)))
1473 (let* ((root (car (gnugo-get :sgf-gametree)))
1474 (cur (assq :RE root)))
1475 (if cur
1476 (setcdr cur result)
1477 (setcdr (last root) (list (cons :RE result)))))
1478 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
1479 (erase-buffer)
1480 (insert blurb)))
1481
1482 ;;;---------------------------------------------------------------------------
1483 ;;; Command properties and gnugo-command
1484
1485 ;; GTP commands entered by the user are never issued directly to GNU Go;
1486 ;; instead, their behavior and output are controlled by the property
1487 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
1488 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
1489 ;;
1490 ;; :full -- completely interpret the command string; the value is a
1491 ;; func that takes the list of words derived from splitting the
1492 ;; command string (minus the command) and handles everything.
1493 ;;
1494 ;; :output -- either a keyword specifying the preferred output method:
1495 ;; :message -- show output in minibuffer
1496 ;; :discard -- sometimes you just don't care;
1497 ;; or a function that takes one arg, the output string, and
1498 ;; handles it completely. default is to switch to buffer
1499 ;; "*gnugo command output*" if the output has a newline,
1500 ;; otherwise use `message'.
1501 ;;
1502 ;; :post-hook -- normal hook run after output processing (at the very end).
1503
1504 (defun gnugo-command (command)
1505 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
1506 Output and Emacs behavior depend on which command is given (some
1507 commands are handled completely by Emacs w/o using the subprocess;
1508 some commands have their output displayed in specially prepared
1509 buffers or in the echo area; some commands are instrumented to do
1510 gnugo.el-specific housekeeping).
1511
1512 For example, for the command \"help\", Emacs visits the
1513 GTP command reference info page.
1514
1515 NOTE: At this time, GTP command handling specification is still
1516 incomplete. Thus, some commands WILL confuse gnugo.el."
1517 (interactive "sCommand: ")
1518 (if (string= "" command)
1519 (message "(no command given)")
1520 (let* ((split (split-string command))
1521 (cmd (intern (car split)))
1522 (spec (get cmd :gnugo-gtp-command-spec))
1523 (full (plist-get spec :full))
1524 (last-message nil))
1525 (if full
1526 (funcall full (cdr split))
1527 (message "Doing %s ..." command)
1528 (let* ((ans (cdr (gnugo-synchronous-send/return command)))
1529 (where (plist-get spec :output)))
1530 (if (string-match "unknown.command" ans)
1531 (message ans)
1532 (cond ((functionp where) (funcall where ans))
1533 ((eq :discard where) (message ""))
1534 ((or (eq :message where)
1535 (not (string-match "\n" ans)))
1536 (message ans))
1537 (t (switch-to-buffer "*gnugo command output*")
1538 (erase-buffer)
1539 (insert ans)
1540 (message "Doing %s ... done." command)))
1541 (let ((hook
1542 ;; do not elide this binding; `run-hooks' needs it
1543 (plist-get spec :post-hook)))
1544 (run-hooks 'hook))))))))
1545
1546 ;;;---------------------------------------------------------------------------
1547 ;;; Major mode for interacting with a GNUGO subprocess
1548
1549 (put 'gnugo-board-mode 'mode-class 'special)
1550 (defun gnugo-board-mode ()
1551 "Major mode for playing GNU Go.
1552 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
1553 In this mode, keys do not self insert. Default keybindings:
1554
1555 ? View this help.
1556
1557 RET or SPC Run `gnugo-move'.
1558
1559 q or Q Quit (the latter without confirmation).
1560
1561 R Resign.
1562
1563 u Run `gnugo-undo-two-moves'.
1564
1565 U Pass to `gnugo-magic-undo' either the board position
1566 at point (if no prefix arg), or the prefix arg converted
1567 to a number. E.g., to undo 16 moves: `C-u C-u U' (see
1568 `universal-argument'); to undo 42 moves: `M-4 M-2 U'.
1569
1570 C-l Run `gnugo-refresh'.
1571
1572 _ or M-_ Bury the Board buffer (when the boss is near).
1573
1574 P Run `gnugo-pass'.
1575
1576 i Toggle display using XPM images (if supported).
1577
1578 w Run `gnugo-worm-stones'.
1579 d Run `gnugo-dragon-stones'.
1580
1581 W Run `gnugo-worm-data'.
1582 D Run `gnugo-dragon-data'.
1583
1584 t Run `gnugo-toggle-dead-group'.
1585
1586 ! Run `gnugo-estimate-score'.
1587
1588 : or ; Run `gnugo-command' (for GTP commands to GNU Go).
1589
1590 = Display board position under point (if valid).
1591
1592 h Run `gnugo-move-history'.
1593
1594 F Run `gnugo-display-final-score'.
1595
1596 s Run `gnugo-write-sgf-file'.
1597 or C-x C-w
1598 or C-x C-s
1599
1600 l Run `gnugo-read-sgf-file'."
1601 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
1602 (buffer-disable-undo) ; todo: undo undo undoing
1603 (kill-all-local-variables)
1604 (setq truncate-lines t)
1605 (use-local-map gnugo-board-mode-map)
1606 (set (make-local-variable 'font-lock-defaults)
1607 '(gnugo-font-lock-keywords t))
1608 (setq major-mode 'gnugo-board-mode)
1609 (setq mode-name "GNUGO Board")
1610 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
1611 (set (make-local-variable 'gnugo-state)
1612 (make-hash-table :size (1- 42) :test 'eq))
1613 (add-to-invisibility-spec :nogrid)
1614 (mapc (lambda (prop)
1615 (gnugo-put prop nil)) ; todo: separate display/game aspects;
1616 '(:game-over ; move latter to func `gnugo'
1617 :waitingp
1618 :last-waiting
1619 :black-captures
1620 :white-captures
1621 :mode-line
1622 :mode-line-form
1623 :display-using-images
1624 :xpms
1625 :local-xpms
1626 :all-yy))
1627 (let ((name (if (string-match "[ ]" gnugo-program)
1628 (let ((p (substring gnugo-program 0 (match-beginning 0)))
1629 (o (substring gnugo-program (match-end 0)))
1630 (h (or (car gnugo-option-history) "")))
1631 (when (string-match "--mode" o)
1632 (error "Found \"--mode\" in `gnugo-program'"))
1633 (when (and o (< 0 (length o))
1634 h (< 0 (length o))
1635 (or (< (length h) (length o))
1636 (not (string= (substring h 0 (length o))
1637 o))))
1638 (push (concat o " " h) gnugo-option-history))
1639 p)
1640 gnugo-program))
1641 (args (read-string "GNU Go options: "
1642 (car gnugo-option-history)
1643 'gnugo-option-history))
1644 (rules "Japanese")
1645 board-size user-color handicap komi minus-l infile)
1646 (mapc (lambda (x)
1647 (apply (lambda (var default opt &optional rx)
1648 (set var
1649 (or (when (string-match opt args)
1650 (let ((start (match-end 0)) s)
1651 (string-match (or rx "[0-9.]+") args start)
1652 (setq s (match-string 0 args))
1653 (if rx s (string-to-number s))))
1654 default)))
1655 x))
1656 '((board-size 19 "--boardsize")
1657 (user-color "black" "--color" "\\(black\\|white\\)")
1658 (handicap 0 "--handicap")
1659 (komi 0.0 "--komi")
1660 (minus-l nil "\\([^-]\\|^\\)-l[ ]*" "[^ ]+")
1661 (infile nil "--infile" "[ ]*[^ ]+")))
1662 (gnugo-put :user-color user-color)
1663 (when (string-match "--chinese-rules" args)
1664 (setq rules "Chinese"))
1665 (let ((proc-args (split-string args)))
1666 (gnugo-put :proc-args proc-args)
1667 (gnugo-put :proc (apply 'start-process "gnugo" nil name
1668 "--mode" "gtp" "--quiet"
1669 proc-args)))
1670 ;; Emacs is too protective sometimes, blech.
1671 (remove-hook (make-local-variable 'kill-buffer-query-functions)
1672 'process-kill-buffer-query-function
1673 t)
1674 (when (or minus-l infile)
1675 (mapc (lambda (x)
1676 (apply (lambda (prop q)
1677 (set prop (string-to-number (gnugo-query q))))
1678 x))
1679 '((board-size "query_boardsize")
1680 (komi "get_komi")
1681 (handicap "get_handicap"))))
1682 (gnugo-put :diamond (substring (process-name (gnugo-get :proc)) 5))
1683 (gnugo-put :gnugo-color (gnugo-other (gnugo-get :user-color)))
1684 (gnugo-put :highlight-last-move-spec
1685 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
1686 (gnugo-put :lparen-ov (make-overlay 1 1))
1687 (gnugo-put :rparen-ov (let ((ov (make-overlay 1 1)))
1688 (overlay-put ov 'display ")")
1689 ov))
1690 (gnugo-put :sgf-gametree (list (list '(:FF . 4) '(:GM . 1))))
1691 (let ((tree (gnugo-get :sgf-gametree)))
1692 (gnugo-put :sgf-collection (list tree))
1693 (gnugo-put :monkey (vector tree nil 0)))
1694 (let ((g-blackp (string= "black" (gnugo-get :gnugo-color))))
1695 (mapc (lambda (x) (apply 'gnugo-note x))
1696 `((:SZ ,board-size)
1697 (:DT ,(format-time-string "%Y-%m-%d"))
1698 (:RU ,rules)
1699 (:AP ("gnugo.el" . ,gnugo-version))
1700 (:KM ,komi)
1701 (,(if g-blackp :PW :PB) ,(user-full-name))
1702 (,(if g-blackp :PB :PW) ,(concat "GNU Go "
1703 (gnugo-query "version")))
1704 ,@(when (not (zerop handicap))
1705 `((:HA ,handicap)
1706 (:AB ,(gnugo-lsquery "fixed_handicap %d" handicap)
1707 nil t)))))))
1708 (set-process-sentinel (gnugo-get :proc) 'gnugo-sentinel)
1709 (set-process-buffer (gnugo-get :proc) (current-buffer))
1710 (gnugo-put :waiting-start (current-time))
1711 (gnugo-put :hmul 1)
1712 (gnugo-put :wmul 1)
1713 (run-hooks 'gnugo-board-mode-hook)
1714 (gnugo-refresh t))
1715
1716 ;;;---------------------------------------------------------------------------
1717 ;;; Entry point
1718
1719 ;;;###autoload
1720 (defun gnugo (&optional new-game)
1721 "Run gnugo in a buffer, or resume a game in progress.
1722 Prefix arg means skip the game-in-progress check and start a new
1723 game straight away.
1724
1725 You are queried for additional command-line options (Emacs supplies
1726 \"--mode gtp --quiet\" automatically). Here is a list of options
1727 that gnugo.el understands and handles specially:
1728
1729 --boardsize num Set the board size to use (5--19)
1730 --color <color> Choose your color ('black' or 'white')
1731 --handicap <num> Set the number of handicap stones (0--9)
1732
1733 If there is already a game in progress you may resume it instead of
1734 starting a new one. See `gnugo-board-mode' documentation for more info."
1735 (interactive "P")
1736 (let* ((all (let (acc)
1737 (dolist (buf (buffer-list))
1738 (when (gnugo-board-buffer-p buf)
1739 (push (cons (buffer-name buf) buf) acc)))
1740 acc))
1741 (n (length all)))
1742 (if (and (not new-game)
1743 (< 0 n)
1744 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
1745 (if (= 1 n) "" "s"))))
1746 ;; resume
1747 (switch-to-buffer
1748 (cdr (if (= 1 n)
1749 (car all)
1750 (let ((sel (completing-read "Which one? " all nil t)))
1751 (if (string= "" sel)
1752 (car all)
1753 (assoc sel all))))))
1754 ;; set up a new board
1755 (gnugo-board-mode)
1756 (let ((half (truncate (1+ (gnugo-treeroot :SZ)) 2)))
1757 (gnugo-goto-pos (format "A%d" half))
1758 (forward-char (* 2 (1- half)))
1759 (gnugo-put :last-user-bpos
1760 (gnugo-put :center-position
1761 (get-text-property (point) 'gnugo-position))))
1762 ;; first move
1763 (gnugo-put :game-start-time (current-time))
1764 (let ((g (gnugo-get :gnugo-color))
1765 (n (or (gnugo-treeroot :HA) 0))
1766 (u (gnugo-get :user-color)))
1767 (gnugo-put :last-mover g)
1768 (when (or (and (string= "black" u) (< 1 n))
1769 (and (string= "black" g) (< n 2)))
1770 (gnugo-put :last-mover u)
1771 (gnugo-refresh t)
1772 (gnugo-get-move g))))))
1773
1774 ;;;---------------------------------------------------------------------------
1775 ;;; Load-time actions
1776
1777 (unless gnugo-board-mode-map
1778 (setq gnugo-board-mode-map (make-sparse-keymap))
1779 (suppress-keymap gnugo-board-mode-map)
1780 (mapc (lambda (pair)
1781 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
1782 '(("?" . describe-mode)
1783 ("\C-m" . gnugo-move)
1784 (" " . gnugo-move)
1785 ("P" . gnugo-pass)
1786 ("R" . gnugo-resign)
1787 ("q" . (lambda () (interactive)
1788 (if (or (gnugo-get :game-over)
1789 (y-or-n-p "Quit? "))
1790 (kill-buffer nil)
1791 (message "(not quitting)"))))
1792 ("Q" . (lambda () (interactive)
1793 (kill-buffer nil)))
1794 ("U" . (lambda (x) (interactive "P")
1795 (gnugo-magic-undo
1796 (cond ((numberp x) x)
1797 ((consp x) (car x))
1798 (t (gnugo-position))))))
1799 ("u" . gnugo-undo-two-moves)
1800 ("\C-l" . gnugo-refresh)
1801 ("\M-_" . bury-buffer)
1802 ("_" . bury-buffer)
1803 ("h" . gnugo-move-history)
1804 ("i" . (lambda () (interactive)
1805 (gnugo-toggle-image-display)
1806 (save-excursion (gnugo-refresh))))
1807 ("w" . gnugo-worm-stones)
1808 ("W" . gnugo-worm-data)
1809 ("d" . gnugo-dragon-stones)
1810 ("D" . gnugo-dragon-data)
1811 ("t" . gnugo-toggle-dead-group)
1812 ("g" . gnugo-toggle-grid)
1813 ("!" . gnugo-estimate-score)
1814 (":" . gnugo-command)
1815 (";" . gnugo-command)
1816 ("=" . (lambda () (interactive)
1817 (message (gnugo-position))))
1818 ("s" . gnugo-write-sgf-file)
1819 ("\C-x\C-s" . gnugo-write-sgf-file)
1820 ("\C-x\C-w" . gnugo-write-sgf-file)
1821 ("l" . gnugo-read-sgf-file)
1822 ("F" . gnugo-display-final-score)
1823 ;; mouse
1824 ([(down-mouse-1)] . gnugo-mouse-move)
1825 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
1826 ([(down-mouse-3)] . gnugo-mouse-pass)
1827 ;; delving into the curiosities
1828 ("\C-c\C-p" . gnugo-describe-internal-properties))))
1829
1830 (unless (get 'help :gnugo-gtp-command-spec)
1831 (cl-labels
1832 ((sget (x) (get x :gnugo-gtp-command-spec))
1833 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
1834 (plist-put (sget cmd) prop val)))
1835 (add (cmd prop val) (jam cmd prop (let ((cur (plist-get
1836 (sget cmd)
1837 prop)))
1838 (append (delete val cur)
1839 (list val)))))
1840 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
1841 (let ((ls props))
1842 (while ls
1843 (funcall (if (eq :post-hook (car ls))
1844 #'add
1845 #'jam)
1846 cmd (car ls) (cadr ls))
1847 (setq ls (cddr ls)))))))
1848
1849 (defgtp 'help :full
1850 (lambda (sel)
1851 (info "(gnugo)GTP command reference")
1852 (when sel (setq sel (intern (car sel))))
1853 (let (buffer-read-only pad cur spec output found)
1854 (cl-labels
1855 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
1856 (goto-char (point-min))
1857 (save-excursion
1858 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
1859 (point-max) t)
1860 (unless pad
1861 (setq pad (make-string (- (match-beginning 1)
1862 (match-beginning 0))
1863 32)))
1864 (when (plist-get
1865 (setq spec
1866 (get (setq cur (intern (match-string 1)))
1867 :gnugo-gtp-command-spec))
1868 :full)
1869 (note "handles this command completely"))
1870 (when (setq output (plist-get spec :output))
1871 (cond ((functionp output)
1872 (note "handles the output specially"))
1873 ((eq :discard output)
1874 (note "discards the output"))
1875 ((eq :message output)
1876 (note "displays the output in the echo area"))))
1877 (when (eq sel cur)
1878 (setq found (match-beginning 0))))))
1879 (cond (found (goto-char found))
1880 ((not sel))
1881 (t (message "(no such command: %s)" sel))))))
1882
1883 (defgtp 'final_score :full
1884 (lambda (sel) (gnugo-display-final-score)))
1885
1886 (defgtp '(boardsize
1887 clear_board
1888 fixed_handicap)
1889 :output :discard
1890 :post-hook (lambda ()
1891 (gnugo-put :game-over nil)
1892 (gnugo-put :last-mover nil)
1893 (gnugo-refresh t)))
1894
1895 (defgtp 'loadsgf :full
1896 (lambda (sel) (gnugo-read-sgf-file (car sel))))
1897
1898 (defgtp '(undo gg-undo) :full
1899 (lambda (sel) (gnugo-magic-undo
1900 (let (n)
1901 (cond ((not sel) 1)
1902 ((< 0 (setq n (string-to-number (car sel)))) n)
1903 (t (car sel)))))))))
1904
1905 (provide 'gnugo)
1906
1907 \f
1908 ;;;---------------------------------------------------------------------------
1909 ;;; The remainder of this file defines a simplified SGF-handling library.
1910 ;;; When/if it should start to attain generality, it should be split off into
1911 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
1912 ;;; "gnugo/" prefix.
1913
1914 (defconst gnugo/sgf-*r4-properties*
1915 '((AB "Add Black" setup list stone)
1916 (AE "Add Empty" game list point)
1917 (AN "Annotation" game simpletext)
1918 (AP "Application" root (simpletext . simpletext))
1919 (AR "Arrow" - list (point . point))
1920 (AS "Who adds stones" - simpletext) ; (LOA)
1921 (AW "Add White" setup list stone)
1922 (B "Black" move move)
1923 (BL "Black time left" move real)
1924 (BM "Bad move" move double)
1925 (BR "Black rank" game simpletext)
1926 (BT "Black team" game simpletext)
1927 (C "Comment" - text)
1928 (CA "Charset" root simpletext)
1929 (CP "Copyright" game simpletext)
1930 (CR "Circle" - list point)
1931 (DD "Dim points" - elist point) ; (inherit)
1932 (DM "Even position" - double)
1933 (DO "Doubtful" move none)
1934 (DT "Date" game simpletext)
1935 (EV "Event" game simpletext)
1936 (FF "Fileformat" root [number (1 . 4)])
1937 (FG "Figure" - (or none (number . simpletext)))
1938 (GB "Good for Black" - double)
1939 (GC "Game comment" game text)
1940 (GM "Game" root [number (1 . 20)])
1941 (GN "Game name" game simpletext)
1942 (GW "Good for White" - double)
1943 (HA "Handicap" game number) ; (Go)
1944 (HO "Hotspot" - double)
1945 (IP "Initial pos." game simpletext) ; (LOA)
1946 (IT "Interesting" move none)
1947 (IY "Invert Y-axis" game simpletext) ; (LOA)
1948 (KM "Komi" game real) ; (Go)
1949 (KO "Ko" move none)
1950 (LB "Label" - list (point . simpletext))
1951 (LN "Line" - list (point . point))
1952 (MA "Mark" - list point)
1953 (MN "set move number" move number)
1954 (N "Nodename" - simpletext)
1955 (OB "OtStones Black" move number)
1956 (ON "Opening" game text)
1957 (OT "Overtime" game simpletext)
1958 (OW "OtStones White" move number)
1959 (PB "Player Black" game simpletext)
1960 (PC "Place" game simpletext)
1961 (PL "Player to play" setup color)
1962 (PM "Print move mode" - number) ; (inherit)
1963 (PW "Player White" game simpletext)
1964 (RE "Result" game simpletext)
1965 (RO "Round" game simpletext)
1966 (RU "Rules" game simpletext)
1967 (SE "Markup" - point) ; (LOA)
1968 (SL "Selected" - list point)
1969 (SO "Source" game simpletext)
1970 (SQ "Square" - list point)
1971 (ST "Style" root [number (0 . 3)])
1972 (SU "Setup type" game simpletext) ; (LOA)
1973 (SZ "Size" root (or number (number . number)))
1974 (TB "Territory Black" - elist point) ; (Go)
1975 (TE "Tesuji" move double)
1976 (TM "Timelimit" game real)
1977 (TR "Triangle" - list point)
1978 (TW "Territory White" - elist point) ; (Go)
1979 (UC "Unclear pos" - double)
1980 (US "User" game simpletext)
1981 (V "Value" - real)
1982 (VW "View" - elist point) ; (inherit)
1983 (W "White" move move)
1984 (WL "White time left" move real)
1985 (WR "White rank" game simpletext)
1986 (WT "White team" game simpletext)
1987 (LT "Lose on time" setup simpletext))
1988 ;; r4-specific notes
1989 ;; - changed: DT FG LB RE RU SZ
1990 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
1991 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
1992
1993 (defun gnugo/sgf-read-file (filename)
1994 "Return the collection (list) of gametrees in SGF[4] file FILENAME."
1995 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
1996 (put 'gnugo/sgf-*r4-properties* :keywords
1997 (mapcar (lambda (full)
1998 (cons (car full)
1999 (intern (format ":%s" (car full)))))
2000 gnugo/sgf-*r4-properties*))))
2001 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2002 (put 'gnugo/sgf-*r4-properties* :specs
2003 (mapcar (lambda (full)
2004 (cons (car full) (cdddr full)))
2005 gnugo/sgf-*r4-properties*)))))
2006 (cl-labels
2007 ((sw () (skip-chars-forward " \t\n"))
2008 (x (end) (let ((beg (point))
2009 (endp (case end
2010 (:end (lambda (char) (= ?\] char)))
2011 (:mid (lambda (char) (= ?\: char)))
2012 (t (lambda (char) (or (= ?\: char)
2013 (= ?\] char))))))
2014 c)
2015 (while (not (funcall endp (setq c (char-after))))
2016 (cond ((= ?\\ c)
2017 (delete-char 1)
2018 (if (eolp)
2019 (kill-line 1)
2020 (forward-char 1)))
2021 ((looking-at "\\s-+")
2022 (delete-region (point) (match-end 0))
2023 (insert " "))
2024 (t (forward-char 1))))
2025 (buffer-substring-no-properties beg (point))))
2026 (one (type end) (unless (eq 'none type)
2027 (forward-char 1)
2028 (let ((s (x end)))
2029 (case type
2030 ((stone point move simpletext color) s)
2031 ((number real double) (string-to-number s))
2032 ((text) s)
2033 (t (error "Unhandled type: %S" type))))))
2034 (val (spec) (cond ((symbolp spec)
2035 (one spec :end))
2036 ((vectorp spec)
2037 ;; todo: check range here.
2038 (one (aref spec 0) :end))
2039 ((eq 'or (car spec))
2040 (let ((v (one (cadr spec) t)))
2041 (if (= ?\] (char-after))
2042 v
2043 (forward-char 1)
2044 ;; todo: this assumes `spec' has the form
2045 ;; (or foo (foo . bar))
2046 ;; i.e., foo is not rescanned. e.g., `SZ'.
2047 ;; probably this assumption is consistent
2048 ;; w/ the SGF authors' desire to make the
2049 ;; parsing easy, but you never know...
2050 (cons v (one (cdaddr spec) :end)))))
2051 (t (cons (one (car spec) :mid)
2052 (one (cdr spec) :end)))))
2053 (short (who) (when (eobp)
2054 (error "Unexpected EOF while reading %s" who)))
2055 (atvalp () (= ?\[ (char-after)))
2056 (PROP () (let (name spec ltype)
2057 (sw) (short 'property)
2058 (when (looking-at "[A-Z]")
2059 (setq name (read (current-buffer))
2060 spec (cdr (assq name specs)))
2061 (sw)
2062 (cons
2063 (cdr (assq name keywords))
2064 (prog1 (if (= 1 (length spec))
2065 (val (car spec))
2066 (unless (memq (setq ltype (car spec))
2067 '(elist list))
2068 (error "Bad spec: %S" spec))
2069 (if (and (eq 'elist ltype) (sw)
2070 (not (atvalp)))
2071 nil
2072 (let ((type (cadr spec))
2073 mo ls)
2074 (while (and (sw) (atvalp)
2075 (setq mo (val type)))
2076 (push mo ls)
2077 (forward-char 1))
2078 (forward-char -1)
2079 (nreverse ls))))
2080 (forward-char 1))))))
2081 (NODE () (let (prop props)
2082 (sw) (short 'node)
2083 (when (= ?\; (char-after))
2084 (forward-char 1)
2085 (while (setq prop (PROP))
2086 (push prop props))
2087 (nreverse props))))
2088 (TREE () (let (nodes)
2089 (while (and (sw) (not (eobp)))
2090 (case (char-after)
2091 (?\; (push (NODE) nodes))
2092 (?\( (forward-char 1)
2093 (push (TREE) nodes))
2094 (?\) (forward-char 1))))
2095 (nreverse nodes))))
2096 (with-temp-buffer
2097 (insert-file-contents filename)
2098 (let (trees)
2099 (while (and (sw) (not (eobp)) (= 40 (char-after))) ; left paren
2100 (forward-char 1)
2101 (push (TREE) trees))
2102 (nreverse trees))))))
2103
2104 (defun gnugo/sgf-write-file (collection filename)
2105 ;; take responsibility for our actions
2106 (dolist (tree collection)
2107 (let* ((root (car tree))
2108 (who (assq :AP root))
2109 (fruit (cons "gnugo.el" gnugo-version)))
2110 (if who
2111 (setcdr who fruit)
2112 (setcdr (last root) (list (cons :AP fruit))))))
2113 ;; write it out
2114 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2115 (specs (mapcar (lambda (full)
2116 (cons (intern (format ":%s" (car full)))
2117 (cdddr full)))
2118 gnugo/sgf-*r4-properties*))
2119 p name v spec)
2120 ;; todo: escape special chars for `text' and `simpletext'.
2121 (cl-labels
2122 ((>>one (v) (insert (format "[%s]" v)))
2123 (>>two (v) (insert (format "[%s:%s]" (car v) (cdr v))))
2124 (>>nl () (cond ((memq name aft-newline-appreciated)
2125 (insert "\n"))
2126 ((< 60 (current-column))
2127 (save-excursion
2128 (goto-char p)
2129 (insert "\n"))))))
2130 (with-temp-buffer
2131 (dolist (tree collection)
2132 (insert "(")
2133 (dolist (node tree)
2134 (insert ";")
2135 (dolist (prop node)
2136 (setq p (point)
2137 name (car prop)
2138 v (cdr prop))
2139 (insert (substring (symbol-name name) 1))
2140 (cond ((not v))
2141 ((and (consp v)
2142 (memq (car (setq spec (cdr (assq name specs))))
2143 '(list elist)))
2144 (>>nl)
2145 (let ((>> (if (consp (cadr spec))
2146 #'>>two
2147 #'>>one)))
2148 (dolist (little-v v)
2149 (setq p (point)) (funcall >> little-v) (>>nl))))
2150 ((consp v)
2151 (>>two v) (>>nl))
2152 (t
2153 (>>one v) (>>nl)))))
2154 (insert ")\n"))
2155 (write-file filename)))))
2156
2157 ;;; gnugo.el ends here