]> code.delx.au - gnu-emacs-elpa/blob - packages/gnugo/gnugo.el
[gnugo int] Accomodate XPM w/ :color-symbols property.
[gnu-emacs-elpa] / packages / gnugo / gnugo.el
1 ;;; gnugo.el --- play GNU Go in a buffer -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
4
5 ;; Author: Thien-Thi Nguyen <ttn@gnu.org>
6 ;; Maintainer: Thien-Thi Nguyen <ttn@gnu.org>
7 ;; Version: 2.3.1
8 ;; Package-Requires: ((ascii-art-to-unicode "1.5"))
9
10 ;; This program is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; This program is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; Playing
26 ;; -------
27 ;;
28 ;; This file provides the command `gnugo' which allows you to play the game of
29 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
30 ;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
31 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
32 ;; Go" to refer to the process object created by running the external program.
33 ;;
34 ;; At the start of a new game, you can pass additional command-line arguments
35 ;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
36 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
37 ;; both komi and handicap.
38 ;;
39 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
40 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
41 ;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
42 ;; back through an arbitrary stone that you played, place the cursor on a
43 ;; stone and type `U' (note: uppercase).
44 ;;
45 ;; There are a great many other commands. Other keybindings are described in
46 ;; the `gnugo-board-mode' documentation, which you may view with the command
47 ;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
48 ;; the last move and who is currently to play. Capture counts and other info
49 ;; are shown on the mode line immediately following the major mode name.
50 ;;
51 ;; While GNU Go is pondering its next move, certain commands that rely on its
52 ;; assistence will result in a "still waiting" error. Do not be alarmed; that
53 ;; is normal. When it is your turn again you may retry the command. In the
54 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
55 ;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
56 ;;
57 ;; If GNU Go should crash during a game the mode line will show "no process".
58 ;; Please report the event to the GNU Go maintainers so that they can improve
59 ;; the program.
60 ;;
61 ;;
62 ;; Meta-Playing (aka Customizing)
63 ;; ------------------------------
64 ;;
65 ;; Customization is presently limited to
66 ;; vars: `gnugo-program'
67 ;; `gnugo-animation-string'
68 ;; `gnugo-mode-line'
69 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
70 ;; `gnugo-undo-reaction'
71 ;; `gnugo-xpms'
72 ;; normal hooks: `gnugo-board-mode-hook'
73 ;; `gnugo-frolic-mode-hook'
74 ;; `gnugo-start-game-hook'
75 ;; `gnugo-post-move-hook'
76 ;; and the keymaps: `gnugo-board-mode-map'
77 ;; `gnugo-frolic-mode-map'
78 ;;
79 ;;
80 ;; Meta-Meta-Playing (aka Hacking)
81 ;; -------------------------------
82 ;;
83 ;; <http://git.sv.gnu.org/cgit/emacs/elpa.git/tree/packages/gnugo/HACKING>
84 ;;
85 ;;
86 ;; Tip Jar
87 ;; -------
88 ;;
89 ;; <http://www.gnuvola.org/software/gnugo/>
90
91 ;;; Code:
92
93 (eval-when-compile (require 'cl)) ; use the source luke!
94 (require 'ascii-art-to-unicode) ; for `aa2u'
95 (require 'time-date) ; for `time-subtract'
96
97 ;;;---------------------------------------------------------------------------
98 ;;; Political arts
99
100 (defconst gnugo-version "2.3.1"
101 "Version of gnugo.el currently loaded.
102 This follows a MAJOR.MINOR.PATCH scheme.")
103
104 ;;;---------------------------------------------------------------------------
105 ;;; Variables for the uninquisitive programmer
106
107 (defvar gnugo-program "gnugo"
108 "Name of the GNU Go program (executable file).
109 \\[gnugo] validates this using `executable-find'.
110 This program must accept command line args:
111 --mode gtp --quiet
112 For more information on GTP and GNU Go, please visit:
113 <http://www.gnu.org/software/gnugo>")
114
115 (defvar gnugo-board-mode-map nil
116 "Keymap for GNUGO Board mode.")
117
118 (defvar gnugo-frolic-mode-map nil
119 "Keymap for GNUGO Frolic mode.")
120
121 (defvar gnugo-board-mode-hook nil
122 "Hook run when entering GNUGO Board mode.")
123
124 (defvar gnugo-start-game-hook nil
125 "Normal hook run immediately before the first move of the game.
126 To find out who is to move first, use `gnugo-current-player'.
127 See also `gnugo-board-mode'.")
128
129 (defvar gnugo-post-move-hook nil
130 "Normal hook run after a move and before the board is refreshed.
131 Initially, when `run-hooks' is called, the current buffer is the GNUGO
132 Board buffer of the game. Hook functions that switch buffers must take
133 care not to call (directly or indirectly through some other function)
134 `gnugo-put' or `gnugo-get' after the switch.")
135
136 (defvar gnugo-animation-string
137 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
138 (concat jam jam jam jam jam
139 ;; "SECRET MESSAGE HERE"
140 blink blink blink blink blink blink blink blink
141 ;; Playing go is like fighting ignorance: when you think you have
142 ;; surrounded something by knowing it very well it often turns
143 ;; out that in the time you spent deepening this understanding,
144 ;; other areas of ignorance have surrounded you.
145 spin spin spin spin spin spin spin spin spin
146 ;; Playing go is not like fighting ignorance: what one person
147 ;; knows many people may come to know; knowledge does not build
148 ;; solely move by move. Wisdom, on the other hand...
149 yada yada yada))
150 "String whose individual characters are used for animation.
151 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
152 render the stones in their respective result groups as the first character
153 in the string, then the next, and so on.")
154
155 (defvar gnugo-mode-line "~b ~w :~m :~u"
156 "A `mode-line-format'-compliant value for GNUGO Board mode.
157 If a single string, the following special escape sequences are
158 replaced with their associated information:
159 ~b,~w black,white captures (a number)
160 ~p current player (black or white)
161 ~m move number
162 ~t time waiting for the current move
163 ~u time taken for the Ultimate (most recent) move
164 The times are in seconds, or \"-\" if that information is not available.
165 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
166
167 (defvar gnugo-X-face 'font-lock-string-face
168 "Name of face to use for X (black) stones.")
169
170 (defvar gnugo-O-face 'font-lock-builtin-face
171 "Name of face to use for O (white) stones.")
172
173 (defvar gnugo-grid-face 'default
174 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
175
176 (defvar gnugo-undo-reaction 'play!
177 "What to do if undo (or oops) leaves GNU Go to play.
178 After `gnugo-undo-one-move', `gnugo-undo-two-moves' or `gnugo-oops',
179 when GNU Go is to play, this can be a symbol:
180 play -- make GNU Go play (unless in Zombie mode)
181 play! -- make GNU Go play unconditionally (traditional behavior)
182 zombie -- enable Zombie mode (`gnugo-zombie-mode')
183 one-shot -- like `zombie' but valid only for the next move
184 Any other value, or (as a special case) for `gnugo-undo-one-move',
185 any value other than `zombie', is taken as `one-shot'. Note that
186 making GNU Go play will probably result in the recently-liberated
187 board position becoming re-occupied.")
188
189 (defvar gnugo-xpms nil
190 "List of 46 ((TYPE . LOCATION) . XPM-IMAGE) forms.
191 XPM-IMAGE is an image as returned by `create-image' with
192 inline data (i.e., property :data with string value).
193
194 TYPE is a symbol, one of:
195 hoshi -- unoccupied position with dot
196 empty -- unoccupied position sans dot
197 bpmoku, bmoku -- black stone with and sans highlight point
198 wpmoku, wmoku -- white stone with and sans highlight point
199
200 LOCATION is an integer encoding edge, corner, or center:
201 1 2 3
202 4 5 6
203 7 8 9
204 For instance, 4 means \"left edge\", 9 means \"bottom right\".
205
206 There is only one location for hoshi: center. The other five
207 types each have all possible locations. So (+ 1 (* 9 5)) => 46.
208
209 The value can also be a function (satisfying `functionp') that
210 takes one arg, the size of the board, and returns the appropriate
211 list of forms.")
212
213 ;;;---------------------------------------------------------------------------
214 ;;; Variables for the inquisitive programmer
215
216 (defconst gnugo-font-lock-keywords
217 '(("X" . gnugo-X-face)
218 ("O" . gnugo-O-face))
219 "Font lock keywords for `gnugo-board-mode'.")
220
221 (defvar gnugo-option-history nil)
222
223 (defvar gnugo-state nil) ; hint: C-c C-p
224
225 (defvar gnugo-frolic-parent-buffer nil)
226 (defvar gnugo-frolic-origin nil)
227
228 (defvar gnugo-btw nil)
229
230 ;;;---------------------------------------------------------------------------
231 ;;; Support functions
232
233 (defsubst gnugo--mkht (&rest etc)
234 (apply 'make-hash-table :test 'eq etc))
235
236 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
237 (compare-strings s1 beg1 nil s2 beg2 nil))
238
239 (defun gnugo-put (key value)
240 "Associate move/game/board-specific property KEY with VALUE.
241
242 There are many properties, each named by a keyword, that record and control
243 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
244 of properties, stored in the hash table `gnugo-state'. Here we document
245 some of the more stable properties. You may wish to use them as part of
246 a `gnugo-post-move-hook' function, for example. Be careful to preserve
247 the current buffer as `gnugo-state' is made into a buffer-local variable.
248 NOTE: In the following, \"see foo\" actually means \"see foo source or
249 you may never really understand to any degree of personal satisfaction\".
250
251 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
252
253 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
254
255 :game-over -- nil until game over at which time its value is set to
256 the alist `((live GROUP ...) (dead GROUP ...))'
257
258 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
259 a simple list of one or more gametrees, updated in
260 conjunction w/ :sgf-gametree and :monkey
261
262 :sgf-gametree -- one of the gametrees in :sgf-collection
263
264 :monkey -- vector of two elements:
265 MEM, a pointer to one of the branches in the gametree;
266 BIDX, the index of the \"current branch\"
267
268 :gnugo-color -- either \"black\" or \"white\"
269 :user-color
270 :last-mover
271
272 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
273 :waiting-start
274
275 :black-captures -- these are strings since gnugo.el doesn't do anything
276 :white-captures w/ the information besides display it in the mode line;
277 gory details in functions `gnugo-propertize-board-buffer'
278 and `gnugo-merge-showboard-results' (almost more effort
279 than they are worth!)
280
281 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
282 `gnugo-toggle-image-display' and `gnugo-refresh',
283 as well as gnugo-xpms.el (available elsewhere)
284
285 :all-yy -- list of 46 symbols used as the `category' text property
286 (so that their plists, typically w/ property `display' or
287 `do-not-display') are consulted by the Emacs display engine;
288 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
289 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
290
291 :paren-ov -- a pair (left and right) of overlays shuffled about to indicate
292 the last move; only one is used when displaying using images
293
294 :last-user-bpos -- board position; keep the hapless human happy
295
296 As things stabilize probably more info will be added to this docstring."
297 (declare (indent 1))
298 (puthash key value gnugo-state))
299
300 (defun gnugo-get (key)
301 "Return the move/game/board-specific value for KEY.
302 See `gnugo-put'."
303 (gethash key gnugo-state))
304
305 (defun gnugo--forget (&rest keys)
306 (dolist (key keys)
307 (remhash key gnugo-state)))
308
309 (defsubst gnugo--tree-mnum (tree)
310 (aref tree 1))
311
312 (defsubst gnugo--tree-ends (tree)
313 (aref tree 0))
314
315 (defsubst gnugo--set-tree-ends (tree ls)
316 (aset tree 0 (apply 'vector ls))
317 (gnugo--tree-ends tree))
318
319 (defun gnugo--root-node (&optional tree)
320 (aref (or tree (gnugo-get :sgf-gametree))
321 2))
322
323 (defun gnugo-describe-internal-properties ()
324 "Pretty-print `gnugo-state' properties in another buffer.
325 Handle the big, slow-to-render, and/or uninteresting ones specially."
326 (interactive)
327 (let ((buf (current-buffer))
328 (d (gnugo-get :diamond))
329 (acc (loop for key being the hash-keys of gnugo-state
330 using (hash-values val)
331 collect (cons key
332 (case key
333 ((:xpms)
334 (format "hash: %X (%d images)"
335 (sxhash val)
336 (length val)))
337 (:sgf-collection
338 (length val))
339 (:sgf-gametree
340 (list (hash-table-count
341 (gnugo--tree-mnum val))
342 (gnugo--root-node val)
343 (gnugo--tree-ends val)))
344 (:monkey
345 (let ((mem (aref val 0)))
346 (list (aref val 1)
347 (car mem))))
348 (t val))))))
349 (switch-to-buffer (get-buffer-create
350 (format "%s*GNUGO Board Properties*"
351 d)))
352 (erase-buffer)
353 (emacs-lisp-mode)
354 (setq truncate-lines t)
355 (save-excursion
356 (pp acc
357 (current-buffer))
358 (goto-char (point-min))
359 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
360 (if (string= "" d)
361 ".+\n"
362 ""))))
363 (while (re-search-forward rx (point-max) t)
364 (let ((pos (get-text-property (string-to-number (match-string 1))
365 'gnugo-position buf)))
366 (delete-region (+ 2 (match-beginning 0)) (point))
367 (insert (format " %S" pos))))))
368 (message "%d properties" (length acc))))
369
370 (defun gnugo-board-buffer-p (&optional buffer)
371 "Return non-nil if BUFFER is a GNUGO Board buffer."
372 (eq 'gnugo-board-mode
373 (buffer-local-value
374 'major-mode
375 (or buffer (current-buffer)))))
376
377 (defun gnugo-board-user-play-ok-p (&optional buffer)
378 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
379 (with-current-buffer (or buffer (current-buffer))
380 (and gnugo-state (not (gnugo-get :waiting)))))
381
382 (defsubst gnugo--blackp (string)
383 (string= "black" string))
384
385 (defun gnugo-other (color)
386 (if (gnugo--blackp color) "white" "black"))
387
388 (defun gnugo-current-player ()
389 "Return the current player, either \"black\" or \"white\"."
390 (gnugo-other (gnugo-get :last-mover)))
391
392 (defsubst gnugo--prop<-color (color)
393 (if (gnugo--blackp color) :B :W))
394
395 (defun gnugo-gate (&optional in-progress-p)
396 (unless (gnugo-board-buffer-p)
397 (user-error "Wrong buffer -- try M-x gnugo"))
398 (unless (gnugo-get :proc)
399 (user-error "No \"gnugo\" process!"))
400 (destructuring-bind (&optional color . suggestion)
401 (gnugo-get :waiting)
402 (when color
403 (apply 'user-error
404 "%s -- please wait for \"(%s to play)\""
405 (if suggestion
406 (list "Still thinking"
407 color)
408 (list "Not your turn yet"
409 (gnugo-other color))))))
410 (when (and in-progress-p (gnugo-get :game-over))
411 (user-error "Sorry, game over")))
412
413 (defun gnugo-sentinel (proc string)
414 (let ((status (process-status proc)))
415 (when (memq status '(exit signal))
416 (let ((buf (process-buffer proc)))
417 (when (buffer-live-p buf)
418 (with-current-buffer buf
419 (setq mode-line-process
420 (list " [%s ("
421 (propertize (car (split-string string))
422 'face 'font-lock-warning-face)
423 ")]"))
424 (when (eq proc (gnugo-get :proc))
425 (gnugo--forget :proc))))))))
426
427 (defun gnugo--begin-exchange (proc filter line)
428 (declare (indent 2)) ; good time, for a rime
429 ; nice style, for a wile...
430 (set-process-filter proc filter)
431 (process-send-string proc line)
432 (process-send-string proc "\n"))
433
434 (defun gnugo--q (fmt &rest args)
435 "Send formatted command \"FMT ARGS...\"; wait for / return response.
436 The response is a string whose first two characters indicate the
437 status of the command. See also `gnugo-query'."
438 (let ((slow (gnugo-get :waiting))
439 (proc (gnugo-get :proc)))
440 (when slow
441 (user-error "Sorry, still waiting for %s to %s"
442 (car slow) (if (cdr slow)
443 "receive a suggestion"
444 "play")))
445 (process-put proc :incomplete t)
446 (process-put proc :srs "") ; synchronous return stash
447 (gnugo--begin-exchange
448 proc (lambda (proc string)
449 (let ((full (concat (process-get proc :srs)
450 string)))
451 (process-put proc :srs full)
452 (unless (numberp (gnugo--compare-strings
453 full (max 0 (- (length full)
454 2))
455 "\n\n" nil))
456 (process-put proc :incomplete nil))))
457 (if (null args)
458 fmt
459 (apply #'format fmt args)))
460 (while (process-get proc :incomplete)
461 (accept-process-output proc 30))
462 (prog1 (substring (process-get proc :srs) 0 -2)
463 (process-put proc :srs ""))))
464
465 (defsubst gnugo--no-worries (string)
466 (= ?= (aref string 0)))
467
468 (defun gnugo--q/ue (fmt &rest args)
469 (let ((ans (apply 'gnugo--q fmt args)))
470 (unless (gnugo--no-worries ans)
471 (user-error "%s" ans))
472 (substring ans 2)))
473
474 (defun gnugo-query (message-format &rest args)
475 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
476 Return a string that omits the first two characters (corresponding
477 to the status indicator in the Go Text Protocol). Use this function
478 when you are sure the command cannot fail."
479 (substring (apply 'gnugo--q message-format args)
480 2))
481
482 (defun gnugo--nquery (cmd)
483 (string-to-number (gnugo-query cmd)))
484
485 (defun gnugo-lsquery (message-format &rest args)
486 (split-string (apply 'gnugo-query message-format args)))
487
488 (defsubst gnugo--count-query (fmt &rest args)
489 (length (apply 'gnugo-lsquery fmt args)))
490
491 (defsubst gnugo--root-prop (prop &optional tree)
492 (cdr (assq prop (gnugo--root-node tree))))
493
494 (defun gnugo--set-root-prop (prop value &optional tree)
495 (let* ((root (gnugo--root-node tree))
496 (cur (assq prop root)))
497 (if cur
498 (setcdr cur value)
499 (push (cons prop value)
500 (cdr (last root))))))
501
502 (defun gnugo-goto-pos (pos)
503 "Move point to board position POS, a letter-number string."
504 (goto-char (point-min))
505 (forward-line (- (1+ (gnugo-get :SZ))
506 (string-to-number (substring pos 1))))
507 (forward-char 1)
508 (forward-char (+ (if (= 32 (following-char)) 1 2)
509 (* 2 (- (let ((letter (aref pos 0)))
510 (if (> ?I letter)
511 letter
512 (1- letter)))
513 ?A)))))
514
515 (defun gnugo-f (id)
516 (intern (if (symbolp id)
517 (symbol-name id)
518 id)
519 (gnugo-get :obarray)))
520
521 (defun gnugo-yang (c)
522 (cdr (assq c '((?+ . hoshi)
523 (?. . empty)
524 (?X . (bmoku . bpmoku))
525 (?O . (wmoku . wpmoku))))))
526
527 (defun gnugo-yy (yin yang &optional momentaryp)
528 (gnugo-f (format "%d-%s"
529 yin (cond ((symbolp yang) yang)
530 (momentaryp (cdr yang))
531 (t (car yang))))))
532
533 (defun gnugo-toggle-image-display ()
534 (unless (display-images-p)
535 (user-error "Display does not support images, sorry"))
536 (let ((fresh (if (functionp gnugo-xpms)
537 (funcall gnugo-xpms (gnugo-get :SZ))
538 gnugo-xpms)))
539 (unless fresh
540 (user-error "Sorry, `gnugo-xpms' unset"))
541 (unless (eq fresh (gnugo-get :xpms))
542 (gnugo-put :xpms fresh)
543 (gnugo--forget :all-yy)))
544 (let* ((new (not (gnugo-get :display-using-images)))
545 (act (if new 'display 'do-not-display)))
546 (mapc (lambda (yy)
547 (setcar (symbol-plist yy) act))
548 (or (gnugo-get :all-yy)
549 (gnugo-put :all-yy
550 (prog1 (mapcar (lambda (ent)
551 (let* ((k (car ent))
552 (yy (gnugo-yy (cdr k) (car k))))
553 (setplist yy `(not-yet ,(cdr ent)))
554 yy))
555 (gnugo-get :xpms))
556 (gnugo-put :imul
557 (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
558 'not-yet)))))))
559 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
560 (gnugo-put :highlight-last-move-spec
561 (if new
562 '((lambda (p)
563 (get (gnugo-yy (get-text-property p 'gnugo-yin)
564 (get-text-property p 'gnugo-yang)
565 t)
566 'display))
567 0 delete-overlay)
568 (gnugo-get :default-highlight-last-move-spec)))
569 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
570 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
571 (mapc 'delete-overlay (cdar group))
572 (setcdr (car group) nil))
573 (gnugo-put :mul (if new
574 (gnugo-get :imul)
575 '(1 . 1)))
576 (gnugo-put :display-using-images new)))
577
578 (define-minor-mode gnugo-grid-mode
579 "If enabled, display grid around the board."
580 :variable
581 ((not (memq :nogrid buffer-invisibility-spec))
582 .
583 (lambda (bool)
584 (funcall (if bool
585 'remove-from-invisibility-spec
586 'add-to-invisibility-spec)
587 :nogrid)
588 (save-excursion (gnugo-refresh)))))
589
590 (defun gnugo-propertize-board-buffer ()
591 (erase-buffer)
592 (insert (substring (gnugo--q "showboard") 3))
593 (let* ((grid-props (list 'invisible :nogrid
594 'font-lock-face gnugo-grid-face))
595 (%gpad (gnugo-f 'gpad))
596 (%gspc (gnugo-f 'gspc))
597 (%lpad (gnugo-f 'lpad))
598 (%rpad (gnugo-f 'rpad))
599 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
600 (size (gnugo-get :SZ))
601 (size-string (number-to-string size)))
602 (goto-char (point-min))
603 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
604 (skip-chars-forward " ")
605 (put-text-property (1- (point)) (point) 'category %gpad)
606 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
607 (forward-char 1)
608 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
609 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
610 (let* ((row (match-string-no-properties 1))
611 (edge (match-end 0))
612 (other-edge (+ edge (* 2 size) -1))
613 (right-empty (+ other-edge (length row) 1))
614 (top-p (string= size-string row))
615 (bot-p (string= "1" row)))
616 (let* ((nL (- edge 1 (length size-string)))
617 (nR (- edge 1))
618 (ov (make-overlay nL nR (current-buffer) t)))
619 (add-text-properties nL nR grid-props)
620 ;; We redundantly set `invisible' in the overlay to workaround
621 ;; a display bug whereby text *following* the overlaid text is
622 ;; displayed with the face of the overlaid text, but only when
623 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
624 ;; This has something to do w/ the bletcherous `before-string'.
625 (overlay-put ov 'invisible :nogrid)
626 (overlay-put ov 'category %lpad))
627 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
628 ((< other-edge p))
629 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
630 (truncate (- p edge) 2))
631 row))
632 (yin (let ((A-p (= edge p))
633 (Z-p (= (1- other-edge) p)))
634 (cond ((and top-p A-p) 1)
635 ((and top-p Z-p) 3)
636 ((and bot-p A-p) 7)
637 ((and bot-p Z-p) 9)
638 (top-p 2)
639 (bot-p 8)
640 (A-p 4)
641 (Z-p 6)
642 (t 5))))
643 (yang (gnugo-yang (char-after p))))
644 (add-text-properties p (1+ p)
645 `(gnugo-position
646 ,position
647 gnugo-yin
648 ,yin
649 gnugo-yang
650 ,yang
651 category
652 ,(gnugo-yy yin yang)
653 front-sticky
654 (gnugo-position gnugo-yin))))
655 (unless (= (1- other-edge) p)
656 (add-text-properties (1+ p) (+ 2 p) ispc-props)
657 (put-text-property p (+ 2 p) 'intangible ival)))
658 (add-text-properties (1+ other-edge) right-empty grid-props)
659 (goto-char right-empty)
660 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
661 (let ((prop (if (string= "WH" (match-string 1))
662 :white-captures
663 :black-captures))
664 (beg (match-beginning 2))
665 (end (match-end 2)))
666 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
667 (gnugo-put prop (match-string-no-properties 2))))
668 (end-of-line)
669 (put-text-property right-empty (point) 'category %rpad)
670 (forward-char 1)))
671 (add-text-properties (1- (point)) (point-max) grid-props)
672 (skip-chars-forward " ")
673 (put-text-property (1- (point)) (point) 'category %gpad)
674 (put-text-property (point) (progn (end-of-line) (point))
675 'category %gspc)))
676
677 (defun gnugo-merge-showboard-results ()
678 (let ((aft (substring (gnugo--q "showboard") 3))
679 (adj 1) ; string to buffer position adjustment
680
681 (sync "[0-9]* stones$")
682 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
683 ;; restrictive a condition that fails in the case of:
684 ;;
685 ;; (before)
686 ;; ... WHITE has captured 1 stones
687 ;; ^
688 ;; (after)
689 ;; ... WHITE has captured 14 stones
690 ;; ^
691 ;;
692 ;; where the after count has more digits than the before count,
693 ;; but shares the same leading digits. In this case, the result
694 ;; of `compare-strings' points to the SPC following the before
695 ;; count (indicated by caret in this example).
696
697 (bef (buffer-substring-no-properties (point-min) (point-max)))
698 (bef-start 0) (bef-idx 0)
699 (aft-start 0) (aft-idx 0)
700 aft-sync-backtrack mis inc cut new very-strange
701
702 (inhibit-read-only t))
703 (while (numberp (setq mis (gnugo--compare-strings
704 bef bef-start
705 aft aft-start)))
706 (setq aft-sync-backtrack nil
707 inc (if (cl-minusp mis)
708 (- (+ 1 mis))
709 (- mis 1))
710 bef-idx (+ bef-start inc)
711 aft-idx (+ aft-start inc)
712 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
713 (match-end 0)
714 (1+ bef-idx))
715 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
716 (let ((peek (1- aft-idx)))
717 (while (not (= 32 (aref aft peek)))
718 (setq peek (1- peek)))
719 (setq aft-sync-backtrack (1+ peek))))
720 (match-end 0)
721 (1+ aft-idx))
722 cut (+ bef-idx adj
723 (if aft-sync-backtrack
724 (- aft-sync-backtrack aft-idx)
725 0)))
726 (goto-char cut)
727 (if aft-sync-backtrack
728 (let* ((asb aft-sync-backtrack)
729 (l-p (get-text-property cut :gnugo-cf))
730 (old-len (car l-p))
731 (capprop (cdr l-p))
732 (keep (text-properties-at cut)))
733 (setq new (substring aft asb (string-match " " aft asb)))
734 (plist-put keep :gnugo-cf (cons (length new) capprop))
735 (gnugo-put capprop new)
736 (delete-char old-len)
737 (insert (apply 'propertize new keep))
738 (incf adj (- (length new) old-len)))
739 (setq new (aref aft aft-idx))
740 (insert-and-inherit (char-to-string new))
741 (let ((yin (get-text-property cut 'gnugo-yin))
742 (yang (gnugo-yang new)))
743 (add-text-properties cut (1+ cut)
744 `(gnugo-yang
745 ,yang
746 category
747 ,(gnugo-yy yin yang))))
748 (delete-char 1)
749 ;; do this last to avoid complications w/ font lock
750 ;; (this also means we cannot include `intangible' in `front-sticky')
751 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
752 (put-text-property cut (1+ cut) 'intangible very-strange))))))
753
754 (defsubst gnugo--move-prop (node)
755 (or (assq :B node)
756 (assq :W node)))
757
758 (defun gnugo--as-pos-func ()
759 (lexical-let ((size (gnugo-get :SZ)))
760 ;; rv
761 (lambda (cc)
762 (if (string= "" cc)
763 "PASS"
764 (let ((col (aref cc 0)))
765 (format "%c%d"
766 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
767 (- size (- (aref cc 1) ?a))))))))
768
769 (defsubst gnugo--resignp (string)
770 (string= "resign" string))
771
772 (defsubst gnugo--passp (string)
773 (string= "PASS" string))
774
775 (defun gnugo-move-history (&optional rsel color)
776 "Determine and return the game's move history.
777 Optional arg RSEL controls side effects and return value.
778 If nil, display the history in the echo area as \"(N moves)\"
779 followed by the space-separated list of moves. When called
780 interactively with a prefix arg (i.e., RSEL is `(4)'), display
781 similarly, but suffix with the mover (either \":B\" or \":W\").
782 RSEL may also be a symbol that selects what to return:
783 car -- the most-recent move
784 cadr -- the next-to-most-recent move
785 two -- the last two moves as a list, oldest last
786 bpos -- the last stone on the board placed by COLOR
787 For all other values of RSEL, do nothing and return nil."
788 (interactive "P")
789 (let* ((monkey (gnugo-get :monkey))
790 (mem (aref monkey 0))
791 (as-pos (gnugo--as-pos-func))
792 acc node mprop move)
793 (cl-flet*
794 ((as-pos-maybe (x) (if (gnugo--resignp x)
795 x
796 (funcall as-pos x)))
797 (remem () (setq node (pop mem)
798 mprop (gnugo--move-prop node)))
799 (next (byp) (when (remem)
800 (setq move (as-pos-maybe (cdr mprop)))
801 (push (if byp
802 (format "%s%s" move (car mprop))
803 move)
804 acc)))
805 (nn () (next nil))
806 (tell () (message "(%d moves) %s"
807 (length acc)
808 (mapconcat 'identity (nreverse acc) " ")))
809 (finish (byp) (while mem (next byp)) (tell)))
810 (pcase rsel
811 (`(4) (finish t))
812 (`nil (finish nil))
813 (`car (car (nn)))
814 (`cadr (nn) (car (nn)))
815 (`two (nn) (nn) acc)
816 (`bpos (loop with prop = (gnugo--prop<-color color)
817 while mem
818 when (and (remem)
819 (eq prop (car mprop))
820 (setq move (cdr mprop))
821 ;; i.e., "normal CC" position
822 (= 2 (length move)))
823 return (funcall as-pos move)))
824 (_ nil)))))
825
826 (define-derived-mode gnugo-frolic-mode special-mode "GNUGO Frolic"
827 "A special mode for manipulating a GNUGO gametree.
828
829 \\{gnugo-frolic-mode-map}"
830 (setq truncate-lines t)
831 (buffer-disable-undo))
832
833 (defun gnugo-frolic-quit ()
834 "Kill GNUGO Frolic buffer and switch to its parent buffer."
835 (interactive)
836 (let ((bye (current-buffer)))
837 (switch-to-buffer (when (buffer-live-p gnugo-frolic-parent-buffer)
838 gnugo-frolic-parent-buffer))
839 (kill-buffer bye)))
840
841 (defun gnugo-frolic-return-to-origin ()
842 "Move point to the board's current position."
843 (interactive)
844 (if (not gnugo-frolic-origin)
845 (message "No origin")
846 (goto-char gnugo-frolic-origin)
847 (recenter (- (count-lines (line-beginning-position)
848 (point-max))))))
849
850 (defun gnugo-frolic-in-the-leaves ()
851 "Display the game tree in a *GNUGO Frolic* buffer.
852 This looks something like:
853
854 1 B -- E7 E7 E7 E7
855 2 W -- K10 K10 K10 K10
856 3 B -- E2 E2 E2 E2
857 4 W -- J3 J3 J3 J3
858 5 B -- A6 A6 A6 A6
859 6 W -- C9 C9 C9 C9
860
861 ├─────┬─────┐
862 │ │ │
863 7 B -- H7 !B8 C8 C8
864
865 ├─────┐
866 │ │
867 8 W -- D9 D9 D9 E9
868 9 B -- H8 H8
869 10 W -- PASS PASS
870 11 B -- H5 PASS
871 12 W -- PASS
872 13 B -- *PASS
873
874 with 0, 1, ... N (in this case N is 3) in the header line
875 to indicate the branches. Branch 0 is the \"main line\".
876 Point (* in this example) indicates the current position,
877 \"!\" indicates comment properties (e.g., B8, branch 1),
878 and moves not actually on the game tree (e.g., E7, branch 3)
879 are dimmed. Type \\[describe-mode] in that buffer for details."
880 (interactive)
881 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
882 "*GNUGO Frolic*")))
883 (from (or gnugo-frolic-parent-buffer
884 (current-buffer)))
885 ;; todo: use defface once we finally succumb to ‘customize’
886 (dimmed-node-face (list :inherit 'default
887 :foreground "gray50"))
888 (tree (gnugo-get :sgf-gametree))
889 (ends (copy-sequence (gnugo--tree-ends tree)))
890 (mnum (gnugo--tree-mnum tree))
891 (seen (gnugo--mkht))
892 (soil (gnugo--mkht))
893 (width (length ends))
894 (lanes (number-sequence 0 (1- width)))
895 (monkey (gnugo-get :monkey))
896 (as-pos (gnugo--as-pos-func))
897 (at (car (aref monkey 0)))
898 (bidx (aref monkey 1))
899 (valid (map 'vector (lambda (end)
900 (gethash (car end) mnum))
901 ends))
902 (max-move-num (apply 'max (append valid nil)))
903 (inhibit-read-only t)
904 finish)
905 (cl-flet
906 ((on (node)
907 (gethash node seen))
908 (emph (s face)
909 (propertize s 'face face))
910 (fsi (properties fmt &rest args)
911 (insert (apply 'propertize
912 (apply 'format fmt args)
913 properties))))
914 ;; breathe in
915 (loop
916 for bx below width
917 do (loop
918 with fork
919 for node in (aref ends bx)
920 do (if (setq fork (on node))
921 (cl-flet
922 ((tip-p (bix)
923 ;; todo: ignore non-"move" nodes
924 (eq node (car (aref ends bix))))
925 (link (other)
926 (pushnew other (gethash node soil))))
927 (unless (tip-p bx)
928 (unless (tip-p fork)
929 (link fork))
930 (link bx)))
931 (puthash node bx seen))
932 until fork))
933 ;; breathe out
934 (switch-to-buffer buf)
935 (gnugo-frolic-mode)
936 (erase-buffer)
937 (setq header-line-format
938 (lexical-let ((full (concat
939 (make-string 11 ?\s)
940 (mapconcat (lambda (n)
941 (format "%-5s" n))
942 lanes
943 " "))))
944 `((:eval
945 (funcall
946 ,(lambda ()
947 (cl-flet
948 ((sp (w) (propertize
949 " " 'display
950 `(space :width ,w))))
951 (concat
952 (when (eq 'left scroll-bar-mode)
953 (let ((w (or scroll-bar-width
954 (frame-parameter
955 nil 'scroll-bar-width)))
956 (cw (frame-char-width)))
957 (sp (if w
958 (/ w cw)
959 2))))
960 (let ((fc (fringe-columns 'left t)))
961 (unless (zerop fc)
962 (sp fc)))
963 (condition-case nil
964 (substring full (window-hscroll))
965 (error ""))))))))))
966 (set (make-local-variable 'gnugo-frolic-parent-buffer) from)
967 (set (make-local-variable 'gnugo-state)
968 (buffer-local-value 'gnugo-state from))
969 (loop
970 with props
971 for n ; move number
972 from max-move-num downto 1
973 do (setq props (list 'n n))
974 do
975 (loop
976 with (move forks br)
977 initially (progn
978 (goto-char (point-min))
979 (fsi props
980 "%3d %s -- "
981 n (aref ["W" "B"] (logand 1 n))))
982 for bx below width
983 do (let* ((node (unless (< (aref valid bx) n)
984 ;; todo: ignore non-"move" nodes
985 (pop (aref ends bx))))
986 (zow (list* 'bx bx props))
987 (ok (when node
988 (= bx (on node))))
989 (comment (when ok
990 (cdr (assq :C node))))
991 (s (cond ((not node) "")
992 ((not (setq move (gnugo--move-prop node))) "-")
993 (t (funcall as-pos (cdr move))))))
994 (when comment
995 (push comment zow)
996 (push 'help-echo zow))
997 (when (and ok (setq br (gethash node soil)))
998 (push (cons bx (sort br '<))
999 forks))
1000 (fsi zow
1001 "%c%-5s"
1002 (if comment ?! ?\s)
1003 (cond ((and (eq at node)
1004 (or ok (= bx bidx)))
1005 (when (= bx bidx)
1006 (setq finish (point-marker)))
1007 (emph s (list :inherit 'default
1008 :foreground (frame-parameter
1009 nil 'cursor-color))))
1010 ((not ok)
1011 (emph s dimmed-node-face))
1012 (t s))))
1013 finally do
1014 (when (progn (fsi props "\n")
1015 (setq forks (nreverse forks)))
1016 (let* ((margin (make-string 11 ?\s))
1017 (heads (mapcar #'car forks))
1018 (tails (mapcar #'cdr forks)))
1019 (cl-flet*
1020 ((spaced (lanes func)
1021 (mapconcat func lanes " "))
1022 ;; live to play ~ ~ ()
1023 ;; play to learn (+) (-) . o O
1024 ;; learn to live --ttn .M. _____U
1025 (dashed (lanes func) ;;; _____ ^^^^
1026 (mapconcat func lanes "-----"))
1027 (cnxn (lanes set)
1028 (spaced lanes (lambda (bx)
1029 (if (memq bx set)
1030 "|"
1031 " "))))
1032 (pad-unless (condition)
1033 (if condition
1034 ""
1035 " "))
1036 (edge (set)
1037 (insert margin
1038 (cnxn lanes set)
1039 "\n")))
1040 (edge heads)
1041 (loop with bef
1042 for ls on forks
1043 do (let* ((one (car ls))
1044 (yes (append
1045 ;; "aft" heads
1046 (mapcar 'car (cdr ls))
1047 ;; ‘bef’ tails
1048 (apply 'append (mapcar 'cdr bef))))
1049 (ord (sort one '<))
1050 (beg (car ord))
1051 (end (car (last ord))))
1052 (cl-flet
1053 ((also (b e) (cnxn (number-sequence b e)
1054 yes)))
1055 (insert
1056 margin
1057 (also 0 (1- beg))
1058 (pad-unless (zerop beg))
1059 (dashed (number-sequence beg end)
1060 (lambda (bx)
1061 (cond ((memq bx ord) "+")
1062 ((memq bx yes) "|")
1063 (t "-"))))
1064 (pad-unless (>= end width))
1065 (also (1+ end) (1- width))
1066 "\n"))
1067 (push one bef)))
1068 (edge (apply 'append tails))
1069 (aa2u (line-beginning-position
1070 (- (1+ (length forks))))
1071 (point))))))))
1072 (when finish
1073 (set (make-local-variable 'gnugo-frolic-origin) finish)
1074 (gnugo-frolic-return-to-origin))))
1075
1076 (defun gnugo--awake (how)
1077 ;; Valid HOW elements:
1078 ;; require-valid-branch
1079 ;; (line . numeric)
1080 ;; (line . move-string)
1081 ;; (omit . [VAR...])
1082 ;; Invalid elements blissfully ignored. :-D
1083 (let* ((tree (gnugo-get :sgf-gametree))
1084 (ends (gnugo--tree-ends tree))
1085 (width (length ends))
1086 (monkey (gnugo-get :monkey))
1087 (line (case (cdr (assq 'line how))
1088 (numeric
1089 (count-lines (point-min) (line-beginning-position)))
1090 (move-string
1091 (save-excursion
1092 (when (re-search-backward "^ *[0-9]+ [BW]" nil t)
1093 (match-string 0))))
1094 (t nil)))
1095 (col (current-column))
1096 (a (unless (> 10 col)
1097 (let ((try (/ (- col 10)
1098 6)))
1099 (unless (<= width try)
1100 try))))
1101 (rv (list a)))
1102 (when (memq 'require-valid-branch how)
1103 (unless a
1104 (user-error "No branch here")))
1105 (loop with omit = (cdr (assq 'omit how))
1106 for (name . value) in `((line . ,line)
1107 (bidx . ,(aref monkey 1))
1108 (monkey . ,monkey)
1109 (width . ,width)
1110 (ends . ,ends)
1111 (tree . ,tree))
1112 do (unless (memq name omit)
1113 (push value rv)))
1114 rv))
1115
1116 (defmacro gnugo--awakened (how &rest body)
1117 (declare (indent 1))
1118 `(destructuring-bind ,(loop with omit = (cdr (assq 'omit how))
1119 with ls = (list 'a)
1120 for name in '(line bidx monkey
1121 width ends
1122 tree)
1123 do (unless (memq name omit)
1124 (push name ls))
1125 finally return ls)
1126 (gnugo--awake ',how)
1127 ,@body))
1128
1129 (defsubst gnugo--move-to-bcol (bidx)
1130 (move-to-column (+ 10 (* 6 bidx))))
1131
1132 (defun gnugo--swiz (direction &optional blunt)
1133 (gnugo--awakened (require-valid-branch
1134 (omit tree)
1135 (line . numeric))
1136 (let* ((b (cond ((numberp blunt)
1137 (unless (and (< -1 blunt)
1138 (< blunt width))
1139 (user-error "No such branch: %s" blunt))
1140 blunt)
1141 (t (mod (+ direction a) width))))
1142 (flit (if blunt (lambda (n)
1143 (cond ((= n a) b)
1144 ((= n b) a)
1145 (t n)))
1146 (lambda (n)
1147 (mod (+ direction n) width))))
1148 (was (copy-sequence ends))
1149 (new-bidx (funcall flit bidx)))
1150 (loop for bx below width
1151 do (aset ends (funcall flit bx)
1152 (aref was bx)))
1153 (unless (= new-bidx bidx)
1154 (aset monkey 1 new-bidx))
1155 (gnugo-frolic-in-the-leaves)
1156 (goto-char (point-min))
1157 (forward-line line)
1158 (gnugo--move-to-bcol b))))
1159
1160 (defun gnugo-frolic-exchange-left ()
1161 "Exchange the current branch with the one to its left."
1162 (interactive)
1163 (gnugo--swiz -1 t))
1164
1165 (defun gnugo-frolic-rotate-left ()
1166 "Rotate all branches left."
1167 (interactive)
1168 (gnugo--swiz -1))
1169
1170 (defun gnugo-frolic-exchange-right ()
1171 "Exchange the current branch with the one to its right."
1172 (interactive)
1173 (gnugo--swiz 1 t))
1174
1175 (defun gnugo-frolic-rotate-right ()
1176 "Rotate all branches right."
1177 (interactive)
1178 (gnugo--swiz 1))
1179
1180 (defun gnugo-frolic-set-as-main-line ()
1181 "Make the current branch the main line."
1182 (interactive)
1183 (gnugo--swiz nil 0))
1184
1185 (defun gnugo-frolic-prune-branch ()
1186 "Remove the current branch from the gametree.
1187 This fails if there is only one branch in the tree.
1188 This fails if the monkey is on the current branch
1189 \(a restriction that will probably be lifted Real Soon Now\)."
1190 (interactive)
1191 (gnugo--awakened (require-valid-branch
1192 (line . move-string))
1193 ;; todo: define meaningful eviction semantics; remove restriction
1194 (when (= a bidx)
1195 (user-error "Cannot prune with monkey on branch"))
1196 (when (= 1 width)
1197 (user-error "Cannot prune last remaining branch"))
1198 (let ((new (append ends nil)))
1199 ;; Explicit ignorance avoids byte-compiler warning.
1200 (ignore (pop (nthcdr a new)))
1201 (gnugo--set-tree-ends tree new))
1202 (when (< a bidx)
1203 (aset monkey 1 (decf bidx)))
1204 (gnugo-frolic-in-the-leaves)
1205 (when line
1206 (goto-char (point-min))
1207 (search-forward line)
1208 (gnugo--move-to-bcol (min a (- width 2))))))
1209
1210 (defun gnugo--sideways (backwards n)
1211 (gnugo--awakened ((omit tree ends monkey bidx line))
1212 (gnugo--move-to-bcol (mod (if backwards
1213 (- (or a width) n)
1214 (+ (or a -1) n))
1215 width))))
1216
1217 (defun gnugo-frolic-backward-branch (&optional n)
1218 "Move backward N (default 1) branches."
1219 (interactive "p")
1220 (gnugo--sideways t n))
1221
1222 (defun gnugo-frolic-forward-branch (&optional n)
1223 "Move forward N (default 1) branches."
1224 (interactive "p")
1225 (gnugo--sideways nil n))
1226
1227 (defun gnugo--vertical (n direction)
1228 (when (> 0 n)
1229 (setq n (- n)
1230 direction (- direction)))
1231 (gnugo--awakened ((line . numeric)
1232 (omit tree ends width monkey bidx))
1233 (let ((stop (if (> 0 direction)
1234 0
1235 (max 0 (1- (count-lines (point-min)
1236 (point-max))))))
1237 (col (unless a
1238 (current-column))))
1239 (loop while (not (= line stop))
1240 do (loop do (progn
1241 (forward-line direction)
1242 (incf line direction))
1243 until (get-text-property (point) 'n))
1244 until (zerop (decf n)))
1245 (if a
1246 (gnugo--move-to-bcol a)
1247 (move-to-column col)))))
1248
1249 (defun gnugo-frolic-previous-move (&optional n)
1250 "Move to the Nth (default 1) previous move."
1251 (interactive "p")
1252 (gnugo--vertical n -1))
1253
1254 (defun gnugo-frolic-next-move (&optional n)
1255 "Move to the Nth (default 1) next move."
1256 (interactive "p")
1257 (gnugo--vertical n 1))
1258
1259 (defun gnugo-frolic-tip-move ()
1260 "Move to the tip of the current branch."
1261 (interactive)
1262 (gnugo--awakened ((omit line bidx monkey width)
1263 require-valid-branch)
1264 (goto-char (point-max))
1265 (let ((mnum (gnugo--tree-mnum tree))
1266 (node (car (aref ends a))))
1267 (re-search-backward (format "^%3d" (gethash node mnum)))
1268 (gnugo--move-to-bcol a))))
1269
1270 (defun gnugo-boss-is-near ()
1271 "Do `bury-buffer' until the current one is not a GNU Board."
1272 (interactive)
1273 (while (gnugo-board-buffer-p)
1274 (bury-buffer)))
1275
1276 (defsubst gnugo--no-regrets (monkey ends)
1277 (eq (aref ends (aref monkey 1))
1278 (aref monkey 0)))
1279
1280 (defun gnugo--as-cc-func ()
1281 (lexical-let ((size (gnugo-get :SZ)))
1282 (lambda (pos)
1283 (let* ((col (aref pos 0))
1284 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
1285 (two (+ ?a (- size (string-to-number
1286 (substring pos 1))))))
1287 (format "%c%c" one two)))))
1288
1289 (defun gnugo--decorate (node &rest plist)
1290 (loop with tp = (last node)
1291 with fruit
1292 while plist
1293 do (setf
1294 fruit (list (cons ; DWR: LtR OoE assumed.
1295 (pop plist)
1296 (pop plist)))
1297 (cdr tp) fruit
1298 tp fruit)))
1299
1300 (defun gnugo-close-game (end-time resign)
1301 (gnugo-put :game-end-time end-time)
1302 (let ((now (or end-time (current-time))))
1303 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1304 (cadr now))))
1305 (gnugo-put :game-over
1306 (if (or (eq t resign)
1307 (and (stringp resign)
1308 (string-match "[BW][+][Rr]esign" resign)))
1309 (cl-flet
1310 ((ls (color) (mapcar
1311 (lambda (x)
1312 (cons (list color)
1313 (split-string x)))
1314 (split-string
1315 (gnugo-query "worm_stones %s" color)
1316 "\n"))))
1317 (let ((live (append (ls "black") (ls "white"))))
1318 `((live ,@live)
1319 (dead))))
1320 (let ((dd (gnugo-query "dragon_data"))
1321 (start 0) mem color ent live dead)
1322 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1323 dd start)
1324 (setq mem (match-string 1 dd)
1325 color (match-string 2 dd)
1326 start (match-end 0)
1327 ent (cons (list color)
1328 (sort (gnugo-lsquery "dragon_stones %s" mem)
1329 'string<)))
1330 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1331 dd start)
1332 (if (match-string 2 dd)
1333 (push ent live)
1334 (push ent dead))
1335 (setq start (match-end 0)))
1336 `((live ,@live)
1337 (dead ,@dead))))))
1338
1339 (defun gnugo--unclose-game ()
1340 (gnugo--forget :game-over ; all those in -close-game
1341 :scoring-seed
1342 :game-end-time)
1343 (let* ((root (gnugo--root-node))
1344 (cur (assq :RE root)))
1345 (when cur
1346 (assert (not (eq cur (car root))) nil
1347 ":RE at head of root node: %S"
1348 root)
1349 (delq cur root))))
1350
1351 (defun gnugo-push-move (who move)
1352 (let* ((simple (booleanp who))
1353 (ucolor (gnugo-get :user-color))
1354 (color (if simple
1355 (if who
1356 ucolor
1357 (gnugo-get :gnugo-color))
1358 who))
1359 (start (gnugo-get :waiting-start))
1360 (now (current-time))
1361 (resignp (gnugo--resignp move))
1362 (passp (gnugo--passp move))
1363 (head (gnugo-move-history 'car))
1364 (onep (and head (gnugo--passp head)))
1365 (donep (or resignp (and onep passp))))
1366 (unless resignp
1367 (gnugo--q/ue "play %s %s" color move))
1368 (unless passp
1369 (gnugo-merge-showboard-results))
1370 (gnugo-put :last-mover color)
1371 (when (if simple
1372 who
1373 (string= ucolor color))
1374 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1375 ;; update :sgf-gametree and :monkey
1376 (let* ((property (gnugo--prop<-color color))
1377 (pair (cons property (cond (resignp move)
1378 (passp "")
1379 (t (funcall (gnugo--as-cc-func)
1380 move)))))
1381 (fruit (list pair))
1382 (monkey (gnugo-get :monkey))
1383 (mem (aref monkey 0))
1384 (tip (car mem))
1385 (tree (gnugo-get :sgf-gametree))
1386 (ends (gnugo--tree-ends tree))
1387 (mnum (gnugo--tree-mnum tree))
1388 (count (length ends))
1389 (tip-move-num (gethash tip mnum))
1390 (bidx (aref monkey 1)))
1391 ;; Detect déjà-vu. That is, when placing "A", avoid:
1392 ;;
1393 ;; X---Y---A new
1394 ;; \
1395 ;; --A---B old
1396 ;;
1397 ;; (such "variations" do not actually vary!) in favor of:
1398 ;;
1399 ;; X---Y---A new
1400 ;; \
1401 ;; --B old
1402 ;;
1403 ;; This linear search loses for multiple ‘old’ w/ "A",
1404 ;; a very unusual (but not invalid, sigh) situation.
1405 (loop
1406 with (bx previous)
1407 for i
1408 ;; Start with latest / highest likelihood for hit.
1409 ;; (See "to the right" comment, below.)
1410 from (if (gnugo--no-regrets monkey ends)
1411 1
1412 0)
1413 below count
1414 if (setq bx (mod (+ bidx i) count)
1415 previous
1416 (loop with node
1417 for m on (aref ends bx)
1418 while (< tip-move-num
1419 (gethash (setq node (car m))
1420 mnum))
1421 if (eq mem (cdr m))
1422 return
1423 (when (equal pair (assq property node))
1424 m)
1425 finally return
1426 nil))
1427 ;; yes => follow
1428 return
1429 (progn
1430 (unless (= bidx bx)
1431 (rotatef (aref ends bidx)
1432 (aref ends bx)))
1433 (setq mem previous))
1434 ;; no => construct
1435 finally do
1436 (progn
1437 (unless (gnugo--no-regrets monkey ends)
1438 (setq ends (gnugo--set-tree-ends
1439 tree (let ((ls (append ends nil)))
1440 ;; copy old to the right of new
1441 (push mem (nthcdr bidx ls))
1442 ls))))
1443 (puthash fruit (1+ (gethash tip mnum)) mnum)
1444 (push fruit mem)
1445 (aset ends bidx mem)))
1446 (setf (aref monkey 0) mem))
1447 (when start
1448 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1449 (when donep
1450 (gnugo-close-game now resignp))
1451 (gnugo-put :waiting-start (and (not donep) now))
1452 donep))
1453
1454 (defun gnugo-venerate (yin yang)
1455 (let* ((fg-yy (gnugo-yy yin yang))
1456 (fg-disp (or (get fg-yy 'display)
1457 (get fg-yy 'do-not-display)))
1458 (fg-props (cdr fg-disp))
1459 (fg-data (plist-get fg-props :data))
1460 (c-symbs (plist-get fg-props :color-symbols))
1461 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1462 (bg-disp (or (get bg-yy 'display)
1463 (get bg-yy 'do-not-display)))
1464 (bg-data (plist-get (cdr bg-disp) :data))
1465 (bop (lambda (s)
1466 (let* ((start 0)
1467 (ncolors
1468 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1469 (setq start (match-end 0))
1470 (string-to-number (match-string 1 s)))))
1471 (while (and (not (cl-minusp ncolors))
1472 (string-match ",\n" s start))
1473 (setq start (match-end 0)
1474 ncolors (1- ncolors)))
1475 (string-match "\"" s start)
1476 (match-end 0))))
1477 (new (copy-sequence fg-data))
1478 (lx (length fg-data))
1479 (sx (funcall bop fg-data))
1480 (sb (funcall bop bg-data))
1481 (color-key (aref new sx))) ; blech, heuristic
1482 (while (< sx lx)
1483 (when (and (not (= color-key (aref new sx)))
1484 (cl-plusp (random 4)))
1485 (aset new sx (aref bg-data sb)))
1486 (incf sx)
1487 (incf sb))
1488 (apply 'create-image new 'xpm t
1489 :ascent 'center (when c-symbs
1490 (list :color-symbols
1491 c-symbs)))))
1492
1493 (defun gnugo-refresh (&optional nocache)
1494 "Update GNUGO Board buffer display.
1495 While a game is in progress, parenthesize the last-played stone (no parens
1496 for pass). If the buffer is currently displayed in the selected window,
1497 recenter the board (presuming there is extra space in the window). Update
1498 the mode line. Lastly, move point to the last position played by the user,
1499 if that move was not a pass.
1500
1501 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1502 be slow. (This should normally be unnecessary; specify it only if the display
1503 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1504 its move."
1505 (interactive "P")
1506 (let* ((move (gnugo-move-history 'car))
1507 (game-over (gnugo-get :game-over))
1508 (inhibit-read-only t)
1509 window last)
1510 (when (and nocache (not (gnugo-get :waiting)))
1511 (gnugo-propertize-board-buffer))
1512 ;; last move
1513 (when move
1514 (destructuring-bind (l-ov . r-ov) (gnugo-get :paren-ov)
1515 (if (member move '("PASS" "resign"))
1516 (mapc 'delete-overlay (list l-ov r-ov))
1517 (gnugo-goto-pos move)
1518 (let* ((p (point))
1519 (hspec (gnugo-get :highlight-last-move-spec))
1520 (display-value (nth 0 hspec))
1521 (l-offset (nth 1 hspec))
1522 (l-new-pos (+ p l-offset))
1523 (r-action (nth 2 hspec)))
1524 (overlay-put l-ov 'display
1525 (if (functionp display-value)
1526 (funcall display-value p)
1527 display-value))
1528 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1529 (if r-action
1530 (funcall r-action r-ov)
1531 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1532 ;; buffer name
1533 (rename-buffer (concat (gnugo-get :diamond)
1534 (if game-over
1535 (format "%s(game over)"
1536 (if (gnugo--resignp move)
1537 (concat move "ation ")
1538 ""))
1539 (format "%s(%s to play)"
1540 (if move (concat move " ") "")
1541 (gnugo-current-player)))))
1542 ;; pall of death
1543 (when game-over
1544 (let ((live (cdr (assq 'live game-over)))
1545 (dead (cdr (assq 'dead game-over)))
1546 p pall)
1547 (unless (eq game-over (get-text-property 1 'game-over))
1548 (dolist (group (append live dead))
1549 (dolist (pos (cdr group))
1550 (gnugo-goto-pos pos)
1551 (setq p (point))
1552 (put-text-property p (1+ p) 'group group)))
1553 (put-text-property 1 2 'game-over game-over))
1554 (dolist (group live)
1555 (when (setq pall (cdar group))
1556 (mapc 'delete-overlay pall)
1557 (setcdr (car group) nil)))
1558 (dolist (group dead)
1559 (unless (cdar group)
1560 (let (ov pall c (color (caar group)))
1561 (setq c (if (gnugo--blackp color) "x" "o"))
1562 (dolist (pos (cdr group))
1563 (gnugo-goto-pos pos)
1564 (setq p (point) ov (make-overlay p (1+ p)))
1565 (overlay-put
1566 ov 'display
1567 (if (gnugo-get :display-using-images)
1568 ;; respect the dead individually; it takes more time
1569 ;; but that's not a problem (for them)
1570 (gnugo-venerate (get-text-property p 'gnugo-yin)
1571 (gnugo-yang (aref (upcase c) 0)))
1572 (propertize c 'face 'font-lock-warning-face)))
1573 (push ov pall))
1574 (setcdr (car group) pall))))))
1575 ;; window update
1576 (when (setq window (get-buffer-window (current-buffer)))
1577 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1578 (size (gnugo-get :SZ))
1579 (under10p (< size 10))
1580 (mul (gnugo-get :mul))
1581 (h (- (truncate (- (window-height window)
1582 (* size (cdr mul))
1583 (if gridp 2 0))
1584 2)
1585 (if gridp 0 1)))
1586 (edges (window-edges window))
1587 (right-w-edge (nth 2 edges))
1588 (avail-width (- right-w-edge (nth 0 edges)))
1589 (wmul (car mul))
1590 (imagesp (symbol-plist (gnugo-f 'ispc)))
1591 (w (/ (- avail-width
1592 (* size wmul)
1593 (if imagesp
1594 0
1595 (1- size))
1596 2 ; between board and grid
1597 (if gridp
1598 (if under10p 2 4)
1599 0))
1600 2.0)))
1601 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1602 `(display ,(make-string h 10))
1603 '(invisible :nogrid)))
1604 (gpad . (display
1605 (space :align-to
1606 ,(+ w
1607 2.0
1608 (cond (imagesp (+ (* 0.5 wmul)
1609 (if under10p
1610 -0.5
1611 0.5)))
1612 (under10p 0)
1613 (t 1))))))
1614 (gspc . ,(when imagesp
1615 `(display
1616 (space-width
1617 ,(-
1618 ;; DWR: image width alone => OBOE!
1619 ;;- wmul
1620 ;; NB: ‘(* wmul cw)’ is the same
1621 ;; as ‘(car (image-size ... t))’.
1622 (let ((cw (frame-char-width)))
1623 (/ (+ 1.0 (* wmul cw))
1624 cw))
1625 1.0)))))
1626 (lpad . ,(let ((d `(display (space :align-to ,w))))
1627 ;; We distinguish between these cases to
1628 ;; workaround a display bug whereby the
1629 ;; `before-string' is omitted entirely (not
1630 ;; rendered) when interacting w/ the text
1631 ;; mode last-move left-paren for moves in
1632 ;; column A.
1633 (if gridp
1634 `(before-string
1635 ,(apply 'propertize " " d))
1636 d)))
1637 (rpad . (display
1638 (space :align-to ,(1- avail-width))))))
1639 (setplist (gnugo-f (car pair)) (cdr pair)))))
1640 ;; mode line update
1641 (let ((cur (gnugo-get :mode-line)))
1642 (unless (equal cur gnugo-mode-line)
1643 (setq cur gnugo-mode-line)
1644 (gnugo-put :mode-line cur)
1645 (gnugo-put :mode-line-form
1646 (cond ((stringp cur)
1647 (setq cur (copy-sequence cur))
1648 (let (acc cut c)
1649 (while (setq cut (string-match "~[bwpmtu]" cur))
1650 (aset cur cut ?%)
1651 (setq c (aref cur (incf cut)))
1652 (aset cur cut ?s)
1653 (push
1654 `(,(intern (format "squig-%c" c))
1655 ,(case c
1656 (?b '(or (gnugo-get :black-captures) 0))
1657 (?w '(or (gnugo-get :white-captures) 0))
1658 (?p '(gnugo-current-player))
1659 (?t '(let ((ws (gnugo-get :waiting-start)))
1660 (if ws
1661 (cadr (time-since ws))
1662 "-")))
1663 (?u '(or (gnugo-get :last-waiting) "-"))
1664 (?m '(let ((tree (gnugo-get :sgf-gametree))
1665 (monkey (gnugo-get :monkey)))
1666 (gethash (car (aref monkey 0))
1667 (gnugo--tree-mnum tree)
1668 ;; should be unnecessary
1669 "?")))))
1670 acc))
1671 `(let ,(delete-dups (copy-sequence acc))
1672 (format ,cur ,@(reverse (mapcar 'car acc))))))
1673 (t cur))))
1674 (let ((form (gnugo-get :mode-line-form)))
1675 (setq mode-line-process
1676 (and form
1677 ;; this dynamicism is nice but excessive in its wantonness
1678 ;;- `(" [" (:eval ,form) "]")
1679 ;; this dynamicism is ok because the user triggers it
1680 (format " [%s]" (eval form)))))
1681 (force-mode-line-update))
1682 ;; last user move
1683 (when (setq last (gnugo-get :last-user-bpos))
1684 (gnugo-goto-pos last))))
1685
1686 (defun gnugo--turn-the-wheel (&optional now)
1687 (unless (gnugo-get :waiting)
1688 (let ((color (gnugo-current-player))
1689 (wheel (gnugo-get :wheel)))
1690 (setcar wheel
1691 (when (and (not (gnugo-get :game-over))
1692 (member color (cdr wheel)))
1693 (run-at-time
1694 (if now
1695 nil
1696 2) ;;; sec (frettoloso? dubioso!)
1697 nil
1698 (lambda (buf color wheel)
1699 (setcar wheel nil)
1700 (with-current-buffer buf
1701 (gnugo-get-move color)))
1702 (current-buffer)
1703 color wheel))))))
1704
1705 (defun gnugo--finish-move (&optional now)
1706 (let ((buf (current-buffer)))
1707 (run-hooks 'gnugo-post-move-hook)
1708 (set-buffer buf))
1709 (gnugo-refresh)
1710 (gnugo--turn-the-wheel now))
1711
1712 ;;;---------------------------------------------------------------------------
1713 ;;; Game play actions
1714
1715 (defun gnugo--rename-buffer-portion (&optional back)
1716 (let ((old "to play")
1717 (new "waiting for suggestion"))
1718 (when back
1719 (rotatef old new))
1720 (let ((name (buffer-name)))
1721 (when (string-match old name)
1722 (rename-buffer (replace-match new t t name))))))
1723
1724 (defun gnugo--display-suggestion (color suggestion)
1725 (message "%sSuggestion for %s: %s"
1726 (gnugo-get :diamond)
1727 color suggestion))
1728
1729 (defun gnugo-get-move-insertion-filter (proc string)
1730 (with-current-buffer (process-buffer proc)
1731 (let* ((so-far (gnugo-get :get-move-string))
1732 (full (gnugo-put :get-move-string (concat so-far string))))
1733 (when (string-match "^= \\(.+\\)\n\n" full)
1734 (setq full (match-string 1 full)) ; POS or "PASS"
1735 (destructuring-bind (color . suggestion)
1736 (gnugo-get :waiting)
1737 (gnugo--forget :get-move-string
1738 :waiting)
1739 (if suggestion
1740 (progn
1741 (gnugo--rename-buffer-portion t)
1742 (unless (or (gnugo--passp full)
1743 (eq 'nowarp suggestion))
1744 (gnugo-goto-pos full))
1745 (gnugo--display-suggestion color full))
1746 (gnugo-push-move color full)
1747 (gnugo--finish-move)))))))
1748
1749 (defun gnugo-get-move (color &optional suggestion)
1750 (gnugo-put :waiting (cons color suggestion))
1751 (gnugo--begin-exchange
1752 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1753 ;; We used to use ‘genmove’ here, but that forced asymmetry in
1754 ;; downstream handling, an impediment to GNU Go vs GNU Go fun.
1755 (concat "reg_genmove " color))
1756 (accept-process-output))
1757
1758 (defun gnugo-cleanup ()
1759 (when (gnugo-board-buffer-p)
1760 (unless (zerop (buffer-size))
1761 (message "Thank you for playing GNU Go."))
1762 (setq gnugo-state nil)))
1763
1764 (defun gnugo-position ()
1765 (or (get-text-property (point) 'gnugo-position)
1766 (user-error "Not a proper position point")))
1767
1768 (defun gnugo-request-suggestion (&optional nowarp)
1769 "Request a move suggestion from GNU Go.
1770 After some time (during which you can do other stuff),
1771 Emacs displays the suggestion in the echo area and warps the
1772 cursor to the suggested position. Prefix arg inhibits warp."
1773 (interactive "P")
1774 (gnugo-gate t)
1775 (gnugo--rename-buffer-portion)
1776 (gnugo-get-move (gnugo-current-player)
1777 (if nowarp
1778 'nowarp
1779 t)))
1780
1781 (defun gnugo--karma (color) ; => BOOL
1782 (when (member color (cdr (gnugo-get :wheel)))
1783 t))
1784
1785 (defsubst gnugo--:karma (role)
1786 (gnugo--karma (gnugo-get role)))
1787
1788 (defun gnugo--assist-state (&optional gate)
1789 (let ((bool (gnugo--:karma :user-color)))
1790 (if (and bool gate)
1791 (user-error "Sorry, Assist mode enabled")
1792 bool)))
1793
1794 (defun gnugo--user-play (pos-or-pass)
1795 (gnugo-gate t)
1796 ;; The "user" in this func's name used to signify both
1797 ;; who does the action and for whom the action is done.
1798 ;; Now, it signifies only the former.
1799 (let ((color (gnugo-current-player)))
1800 ;; Don't get confused by mixed signals.
1801 (when (gnugo--karma color)
1802 (if (equal color (gnugo-get :one-shot))
1803 (gnugo--forget :one-shot)
1804 (user-error "Sorry, you cannot play for %s at this time"
1805 color)))
1806 (gnugo-push-move color pos-or-pass))
1807 (gnugo--finish-move t))
1808
1809 (defun gnugo-move ()
1810 "Make a move on the GNUGO Board buffer.
1811 The position is computed from current point.
1812 Signal error if done out-of-turn or if game-over.
1813 To start a game try M-x gnugo."
1814 (interactive)
1815 (gnugo--user-play (gnugo-position)))
1816
1817 (defun gnugo-mouse-move (e)
1818 "Do `gnugo-move' at mouse location."
1819 (interactive "@e")
1820 (mouse-set-point e)
1821 (when (memq (following-char) '(?. ?+))
1822 (gnugo-move)))
1823
1824 (defun gnugo-pass ()
1825 "Make a pass on the GNUGO Board buffer.
1826 Signal error if done out-of-turn or if game-over.
1827 To start a game try M-x gnugo."
1828 (interactive)
1829 (gnugo--user-play "PASS"))
1830
1831 (defun gnugo-mouse-pass (e)
1832 "Do `gnugo-pass' at mouse location."
1833 (interactive "@e")
1834 (mouse-set-point e)
1835 (gnugo-pass))
1836
1837 (defun gnugo-resign ()
1838 (interactive)
1839 (gnugo-gate t)
1840 (if (not (y-or-n-p "Resign? "))
1841 (message "(not resigning)")
1842 (gnugo-push-move t "resign")
1843 (gnugo-refresh)))
1844
1845 (defun gnugo-animate-group (w/d)
1846 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1847 (gnugo-gate)
1848 (let* ((pos (gnugo-position))
1849 (orig-b-m-p (buffer-modified-p))
1850 blurb stones)
1851 (unless (memq (following-char) '(?X ?O))
1852 (user-error "No stone at %s" pos))
1853 (setq blurb (message "Computing %s stones ..." w/d)
1854 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1855 (message "%s %s in group." blurb (length stones))
1856 (setplist (gnugo-f 'anim) nil)
1857 (let* ((spec (if (gnugo-get :display-using-images)
1858 (loop with yin = (get-text-property (point) 'gnugo-yin)
1859 with yang = (gnugo-yang (following-char))
1860 with up = (get (gnugo-yy yin yang t) 'display)
1861 with dn = (get (gnugo-yy yin yang) 'display)
1862 for n below (length gnugo-animation-string)
1863 collect (if (zerop (logand 1 n))
1864 dn up))
1865 (split-string gnugo-animation-string "" t)))
1866 (cell (list spec))
1867 (ovs (save-excursion
1868 (mapcar (lambda (pos)
1869 (gnugo-goto-pos pos)
1870 (let* ((p (point))
1871 (ov (make-overlay p (1+ p))))
1872 (overlay-put ov 'category (gnugo-f 'anim))
1873 (overlay-put ov 'priority most-positive-fixnum)
1874 ov))
1875 stones))))
1876 (setplist (gnugo-f 'anim) (cons 'display cell))
1877 (while (and (cdr spec) ; let last linger lest levity lost
1878 (sit-for 0.08675309)) ; jenny jenny i got your number...
1879 (setcar cell (setq spec (cdr spec)))
1880 ;; Force redisplay of overlays.
1881 (set-buffer-modified-p orig-b-m-p))
1882 (sit-for 5)
1883 (mapc 'delete-overlay ovs)
1884 t)))
1885
1886 (defun gnugo-display-group-data (command buffer-name)
1887 (gnugo-gate)
1888 (message "Computing %s ..." command)
1889 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1890 (switch-to-buffer buffer-name)
1891 (erase-buffer)
1892 (insert data))
1893 (message "Computing %s ... done." command))
1894
1895 (defun gnugo-worm-stones ()
1896 "In the GNUGO Board buffer, animate \"worm\" at current position.
1897 Signal error if done out-of-turn or if game-over.
1898 See variable `gnugo-animation-string' for customization."
1899 (interactive)
1900 (gnugo-animate-group 'worm))
1901
1902 (defun gnugo-worm-data ()
1903 "Display in another buffer data from \"worm\" at current position.
1904 Signal error if done out-of-turn or if game-over."
1905 (interactive)
1906 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1907
1908 (defun gnugo-dragon-stones ()
1909 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1910 Signal error if done out-of-turn or if game-over.
1911 See variable `gnugo-animation-string' for customization."
1912 (interactive)
1913 (gnugo-animate-group 'dragon))
1914
1915 (defun gnugo-dragon-data ()
1916 "Display in another buffer data from \"dragon\" at current position.
1917 Signal error if done out-of-turn or if game-over."
1918 (interactive)
1919 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1920
1921 (defun gnugo-estimate-score ()
1922 "Display estimated score of a game of GNU Go.
1923 Output includes number of stones on the board and number of stones
1924 captured by each player, and the estimate of who has the advantage (and
1925 by how many stones)."
1926 (interactive)
1927 (message "Est.score ...")
1928 (let ((black (gnugo--count-query "list_stones black"))
1929 (white (gnugo--count-query "list_stones white"))
1930 (black-captures (gnugo-query "captures black"))
1931 (white-captures (gnugo-query "captures white"))
1932 (est (gnugo-query "estimate_score")))
1933 ;; might as well update this
1934 (gnugo-put :black-captures black-captures)
1935 (gnugo-put :white-captures white-captures)
1936 (message "Est.score ... B %s %s | W %s %s | %s"
1937 black black-captures white white-captures est)))
1938
1939 (defun gnugo--ok-file (filename)
1940 (setq default-directory
1941 (file-name-directory
1942 (expand-file-name filename)))
1943 (set-buffer-modified-p nil))
1944
1945 (defun gnugo-write-sgf-file (filename)
1946 "Save the game history to FILENAME (even if unfinished).
1947 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1948 (interactive "FWrite game as SGF file: ")
1949 (when (and (file-exists-p filename)
1950 (not (y-or-n-p "File exists. Continue? ")))
1951 (user-error "Not writing %s" filename))
1952 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1953 (gnugo--ok-file filename))
1954
1955 (defun gnugo--dance-dance (karma)
1956 (destructuring-bind (dance btw)
1957 (aref [(moshpit " Zombie")
1958 (classic nil)
1959 (reverse " Zombie Assist") ; "Assist Zombie"? no thanks! :-D
1960 (stilted " Assist")]
1961 (cl-flet
1962 ((try (n prop)
1963 (if (member (gnugo-get prop)
1964 karma)
1965 n
1966 0)))
1967 (+ (try 2 :user-color)
1968 (try 1 :gnugo-color))))
1969 (gnugo-put :dance dance) ; pure cruft (for now)
1970 (setq gnugo-btw btw)))
1971
1972 (defun gnugo--who-is-who (wait play samep)
1973 (unless samep
1974 (let ((wheel (gnugo-get :wheel)))
1975 (when wheel
1976 (gnugo--dance-dance
1977 (setcdr wheel (mapcar 'gnugo-other
1978 (cdr wheel)))))))
1979 (message "GNU Go %splays as %s, you as %s (%s)"
1980 (if samep "" "now ")
1981 wait play (if samep
1982 "as before"
1983 "NOTE: this is a switch!")))
1984
1985 (defsubst gnugo--nodep (x)
1986 (keywordp (caar x)))
1987
1988 (defun gnugo--SZ! (size)
1989 (gnugo-put :SZ size)
1990 (gnugo-put :center-position
1991 (funcall (gnugo--as-pos-func)
1992 (let ((c (+ -1 ?a (truncate (1+ size) 2))))
1993 (string c c)))))
1994
1995 (defun gnugo--plant-and-climb (collection &optional sel)
1996 (gnugo-put :sgf-collection collection)
1997 (let ((tree (nth (or sel 0) collection)))
1998 (gnugo-put :sgf-gametree tree)
1999 (gnugo-put :monkey (vector
2000 ;; mem
2001 (aref (gnugo--tree-ends tree) 0)
2002 ;; bidx
2003 0))
2004 tree))
2005
2006 (defun gnugo-read-sgf-file (filename)
2007 "Load the first game tree from FILENAME, a file in SGF format."
2008 (interactive "fSGF file to load: ")
2009 (when (file-directory-p filename)
2010 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
2011 (let (play wait samep coll tree game-over)
2012 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
2013 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
2014 (setq play (gnugo--q/ue "loadsgf %s" (expand-file-name filename))
2015 wait (gnugo-other play)
2016 samep (string= (gnugo-get :user-color) play))
2017 (gnugo-put :last-mover wait)
2018 (unless samep
2019 (gnugo-put :gnugo-color wait)
2020 (gnugo-put :user-color play))
2021 (setq coll (gnugo/sgf-create filename)
2022 tree (gnugo--plant-and-climb
2023 coll (let ((n (length coll)))
2024 ;; This is better:
2025 ;; (if (= 1 n)
2026 ;; 0
2027 ;; (let* ((q (format "Which game? (1-%d)" n))
2028 ;; (choice (1- (read-number q 1))))
2029 ;; (if (and (< -1 choice) (< choice n))
2030 ;; choice
2031 ;; (message "(Selecting the first game)")
2032 ;; 0)))
2033 ;; but this is what we use (for now) to accomodate
2034 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
2035 (unless (= 1 n)
2036 (message "(Selecting the first game)"))
2037 0)))
2038 ;; This is deliberately undocumented for now.
2039 (gnugo--SZ! (gnugo--root-prop :SZ tree))
2040 (when (setq game-over (or (gnugo--root-prop :RE tree)
2041 (when (equal '("PASS" "PASS")
2042 (gnugo-move-history 'two))
2043 'two-passes)))
2044 (gnugo-close-game nil game-over))
2045 (gnugo-put :last-user-bpos
2046 (gnugo-move-history 'bpos (gnugo-get :user-color)))
2047 (gnugo-refresh t)
2048 (gnugo--ok-file filename)
2049 (gnugo--who-is-who wait play samep)))
2050
2051 (defun gnugo--mem-with-played-stone (pos &optional noerror)
2052 (let ((color (case (following-char)
2053 (?X :B)
2054 (?O :W))))
2055 (if (not color)
2056 (unless noerror
2057 (user-error "No stone at %s" pos))
2058 (loop with fruit = (cons color (funcall (gnugo--as-cc-func) pos))
2059 for mem on (aref (gnugo-get :monkey) 0)
2060 when (equal fruit (caar mem))
2061 return mem
2062 finally return nil))))
2063
2064 (defun gnugo--climb-towards-root (spec &optional reaction keep)
2065 (gnugo-gate)
2066 (gnugo--assist-state t)
2067 (let* ((user-color (gnugo-get :user-color))
2068 (monkey (gnugo-get :monkey))
2069 (tree (gnugo-get :sgf-gametree))
2070 (ends (gnugo--tree-ends tree))
2071 (remorseful (not (gnugo--no-regrets monkey ends)))
2072 (stop (if (numberp spec)
2073 (nthcdr (if (zerop spec)
2074 (if (string= (gnugo-get :last-mover)
2075 user-color)
2076 1
2077 2)
2078 spec)
2079 (aref monkey 0))
2080 (cdr (gnugo--mem-with-played-stone
2081 (if (stringp spec)
2082 spec
2083 (gnugo-position)))))))
2084 (when (gnugo-get :game-over)
2085 (gnugo--unclose-game))
2086 (while (and (not (eq stop (aref monkey 0)))
2087 (gnugo--no-worries (gnugo--q "undo")))
2088 (pop (aref monkey 0))
2089 (gnugo-put :last-mover (gnugo-current-player))
2090 (gnugo-merge-showboard-results) ; all
2091 (gnugo-refresh) ; this
2092 (redisplay)) ; eye candy
2093 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
2094 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
2095 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
2096 ubpos
2097 (gnugo-get :center-position)))
2098 (gnugo-refresh t)
2099 (unless (or keep remorseful)
2100 (aset ends (aref monkey 1) (aref monkey 0)))
2101 (when ulastp
2102 (let ((g (gnugo-get :gnugo-color)))
2103 (cl-flet ((turn () (gnugo--turn-the-wheel t)))
2104 (case (or reaction gnugo-undo-reaction)
2105 (play (turn))
2106 (play! (let ((wheel (gnugo-get :wheel)))
2107 (letf (((cdr wheel) (cons g (cdr wheel))))
2108 (turn))))
2109 (zombie (gnugo-zombie-mode 1))
2110 (t (gnugo-put :one-shot g)))))))))
2111
2112 (defun gnugo-undo-one-move (&optional me-next)
2113 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
2114 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
2115 Prefix arg ME-NEXT means to arrange for you to play
2116 the color of the next move (and GNU Go the opposite).
2117 This is useful after loading an SGF file whose last
2118 move was done by the color you prefer to play:
2119 \\[gnugo-read-sgf-file] FILENAME RET
2120 C-u \\[gnugo-undo-one-move]
2121
2122 See also `gnugo-undo-two-moves'."
2123 (interactive "P")
2124 (gnugo-gate)
2125 (when me-next
2126 (let* ((play (gnugo-get :last-mover))
2127 (wait (gnugo-other play))
2128 (samep (string= play (gnugo-get :user-color))))
2129 (gnugo-put :user-color play)
2130 (gnugo-put :gnugo-color wait)
2131 (gnugo--who-is-who wait play samep)))
2132 (gnugo--climb-towards-root 1 (case gnugo-undo-reaction
2133 (zombie gnugo-undo-reaction)
2134 (t 'one-shot))))
2135
2136 (defun gnugo-undo-two-moves ()
2137 "Undo a pair of moves (GNU Go's and yours).
2138 However, if you are the last mover, undo only one move.
2139 Regardless, after undoing, it is your turn to play again."
2140 (interactive)
2141 (gnugo--climb-towards-root 0))
2142
2143 (defun gnugo-oops (&optional position)
2144 "Like `gnugo-undo-two-moves', but keep the undone moves.
2145 The kept moves become a sub-gametree (variation) when play resumes.
2146 Prefix arg means, instead, undo repeatedly up to and including
2147 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
2148 (interactive "P")
2149 (gnugo--climb-towards-root (unless position
2150 0)
2151 nil t))
2152
2153 (defun gnugo-okay (&optional full)
2154 "Redo a pair of undone moves.
2155 Prefix arg means to redo all the undone moves."
2156 (interactive "P")
2157 (gnugo-gate)
2158 (let* ((tree (gnugo-get :sgf-gametree))
2159 (ends (gnugo--tree-ends tree))
2160 (monkey (gnugo-get :monkey)))
2161 (if (gnugo--no-regrets monkey ends)
2162 (message "Oop ack!")
2163 (let* ((as-pos (gnugo--as-pos-func))
2164 (mnum (gnugo--tree-mnum tree))
2165 (mem (aref monkey 0))
2166 (bidx (aref monkey 1))
2167 (end (aref ends bidx))
2168 (ucolor (gnugo-get :user-color))
2169 (uprop (gnugo--prop<-color ucolor)))
2170 (cl-flet ((mvno (node) (gethash node mnum)))
2171 (loop
2172 with ok = (if full
2173 (mvno (car end))
2174 (+ 2 (mvno (car mem))))
2175 with (node move todo)
2176 for ls on end
2177 do (progn
2178 (setq node (car ls)
2179 move (gnugo--move-prop node))
2180 (when (and move (>= ok (mvno node)))
2181 (let ((userp (eq uprop (car move))))
2182 (push (list userp
2183 (funcall as-pos (cdr move)))
2184 todo))))
2185 until (eq mem (cdr ls))
2186 finally do
2187 (loop
2188 for (userp pos) in todo
2189 do (progn
2190 (gnugo-push-move userp pos)
2191 (gnugo-refresh)
2192 (redisplay)))))))))
2193
2194 (defun gnugo-display-final-score (&optional comment)
2195 "Display final score and other info in another buffer (when game over).
2196 If the game is still ongoing, Emacs asks if you wish to stop play (by
2197 making sure two \"pass\" moves are played consecutively, if necessary).
2198 Also, add the `:RE' SGF property to the root node of the game tree.
2199 Prefix arg COMMENT means to also attach the text (slightly compacted)
2200 to the last move, as a comment."
2201 (interactive "P")
2202 (let ((game-over (gnugo-get :game-over)))
2203 (unless (or game-over
2204 (and (not (gnugo-get :waiting))
2205 (y-or-n-p "Game still in play. Stop play now? ")))
2206 (user-error "Sorry, game still in play"))
2207 (unless game-over
2208 (cl-flet
2209 ((pass (userp)
2210 (message "Playing PASS for %s ..."
2211 (gnugo-get (if userp :user-color :gnugo-color)))
2212 (sit-for 1)
2213 (gnugo-push-move userp "PASS")))
2214 (unless (pass t)
2215 (pass nil)))
2216 (gnugo-refresh)
2217 (sit-for 3)))
2218 (let ((b= " Black = ")
2219 (w= " White = ")
2220 (res (when (gnugo--resignp (gnugo-move-history 'car))
2221 (gnugo-get :last-mover)))
2222 blurb result)
2223 (if res
2224 (setq blurb (list
2225 (format "%s wins.\n"
2226 (substring (if (= ?b (aref res 0)) w= b=)
2227 3 8))
2228 "The game is over.\n"
2229 (format "Resignation by %s.\n" res))
2230 result (concat (upcase (substring (gnugo-other res) 0 1))
2231 "+Resign"))
2232 (message "Computing final score ...")
2233 (let* ((g-over (gnugo-get :game-over))
2234 (live (cdr (assq 'live g-over)))
2235 (dead (cdr (assq 'dead g-over)))
2236 (seed (gnugo-get :scoring-seed))
2237 (terr-q (format "final_status_list %%s_territory %d" seed))
2238 (terr "territory")
2239 (capt "captures")
2240 (b-terr (gnugo--count-query terr-q "black"))
2241 (w-terr (gnugo--count-query terr-q "white"))
2242 (b-capt (string-to-number (gnugo-get :black-captures)))
2243 (w-capt (string-to-number (gnugo-get :white-captures)))
2244 (komi (gnugo--root-prop :KM)))
2245 (setq blurb (list "The game is over. Final score:\n")
2246 result (gnugo-query "final_score %d" seed))
2247 (cond ((string= "Chinese" (gnugo--root-prop :RU))
2248 (dolist (group live)
2249 (incf (if (gnugo--blackp (caar group))
2250 b-terr
2251 w-terr)
2252 (length (cdr group))))
2253 (dolist (group dead)
2254 (incf (if (gnugo--blackp (caar group))
2255 w-terr
2256 b-terr)
2257 (length (cdr group))))
2258 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
2259 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
2260 w-terr terr komi 'komi (+ w-terr komi))
2261 blurb))
2262 (t
2263 (dolist (group dead)
2264 (incf (if (gnugo--blackp (caar group))
2265 w-terr
2266 b-terr)
2267 (* 2 (length (cdr group)))))
2268 (push (format "%s%d %s + %s %s = %3.1f\n" b=
2269 b-terr terr
2270 b-capt capt
2271 (+ b-terr b-capt))
2272 blurb)
2273 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
2274 w-terr terr
2275 w-capt capt
2276 komi 'komi
2277 (+ w-terr w-capt komi))
2278 blurb)))
2279 (push (if (string= "0" result)
2280 "The game is a draw.\n"
2281 (format "%s wins by %s.\n"
2282 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
2283 (substring result 2)))
2284 blurb)
2285 (message "Computing final score ... done")))
2286 ;; extra info
2287 (let ((beg (gnugo-get :game-start-time))
2288 (end (gnugo-get :game-end-time)))
2289 (when end
2290 (push "\n" blurb)
2291 (cl-flet
2292 ((yep (pretty moment)
2293 (push (format-time-string
2294 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
2295 moment)
2296 blurb)))
2297 (yep "Game start" beg)
2298 (yep " end" end))))
2299 (setq blurb (apply 'concat (nreverse blurb)))
2300 (gnugo--set-root-prop :RE result)
2301 (when comment
2302 (let ((node (car (aref (gnugo-get :monkey) 0))))
2303 (gnugo--decorate
2304 (delq (assq :C node) node)
2305 :C
2306 (with-temp-buffer ; lame
2307 (insert blurb)
2308 (when (search-backward "\n\nGame start:" nil t)
2309 (delete-region (point) (point-max)))
2310 (cl-flet ((rep (old new)
2311 (goto-char (point-min))
2312 (while (search-forward old nil t)
2313 (replace-match new))))
2314 (rep "The game is over. " "")
2315 (rep "territory" "T")
2316 (rep "captures" "C")
2317 (rep "komi" "K"))
2318 (buffer-string)))))
2319 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
2320 (erase-buffer)
2321 (insert blurb)))
2322
2323 (defun gnugo-quit ()
2324 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
2325 If the game is not over, ask for confirmation first."
2326 (interactive)
2327 (if (or (gnugo-get :game-over)
2328 (y-or-n-p "Quit? "))
2329 (kill-buffer nil)
2330 (message "(not quitting)")))
2331
2332 (defun gnugo-leave-me-alone ()
2333 "Kill the current buffer unconditionally."
2334 (interactive)
2335 (kill-buffer nil))
2336
2337 (defun gnugo-fancy-undo (count)
2338 "Rewind the game tree in various ways.
2339 Prefix arg COUNT means to undo that many moves.
2340 Otherwise, undo repeatedly up to and including the move
2341 which placed the stone at point."
2342 (interactive "P")
2343 (gnugo--climb-towards-root
2344 (if (numberp count)
2345 count
2346 (car-safe count))))
2347
2348 (define-minor-mode gnugo-image-display-mode
2349 "If enabled, display the board using images.
2350 See function `display-images-p' and variable `gnugo-xpms'."
2351 :variable
2352 ((gnugo-get :display-using-images)
2353 .
2354 (lambda (bool)
2355 (unless (eq bool (gnugo-get :display-using-images))
2356 (gnugo-toggle-image-display)
2357 (save-excursion (gnugo-refresh))))))
2358
2359 (defsubst gnugo--node-with-played-stone (pos &optional noerror)
2360 (car (gnugo--mem-with-played-stone pos noerror)))
2361
2362 (defun gnugo-describe-position ()
2363 "Display the board position under cursor in the echo area.
2364 If there a stone at that position, also display its move number."
2365 (interactive)
2366 (let* ((pos (gnugo-position)) ; do first (can throw)
2367 (node (gnugo--node-with-played-stone pos t)))
2368 (message
2369 "%s%s" pos
2370 (or (when node
2371 (let* ((tree (gnugo-get :sgf-gametree))
2372 (mnum (gnugo--tree-mnum tree))
2373 (move-num (gethash node mnum)))
2374 (format " (move %d)" move-num)))
2375 ""))))
2376
2377 (defun gnugo-switch-to-another ()
2378 "Switch to another GNU Go game buffer (if any)."
2379 (interactive)
2380 (loop for buf in (cdr (buffer-list))
2381 if (gnugo-board-buffer-p buf)
2382 return (progn
2383 (bury-buffer)
2384 (switch-to-buffer buf))
2385 finally do (message "(only one)")))
2386
2387 (defun gnugo-comment (node comment)
2388 "Add to NODE a COMMENT (string) property.
2389 Called interactively, NODE is the one corresponding to the
2390 stone at point, and any previous comment is inserted as the
2391 initial-input (see `read-string').
2392
2393 If COMMENT is nil or the empty string, remove the property entirely."
2394 (interactive
2395 (let* ((pos (gnugo-position))
2396 (node (gnugo--node-with-played-stone pos)))
2397 (list node
2398 (read-string (format "Comment for %s: "
2399 (gnugo-describe-position))
2400 (cdr (assq :C node))))))
2401 (setq node (delq (assq :C node) node))
2402 (unless (zerop (length comment))
2403 (gnugo--decorate node :C comment)))
2404
2405 (defun gnugo--struggle (prop updn)
2406 (unless (eq updn (gnugo--:karma prop)) ; drudgery avoidance
2407 (let ((color (gnugo-get prop)))
2408 (if updn
2409 ;; enable
2410 (gnugo-gate)
2411 ;; disable
2412 (let ((waiting (gnugo-get :waiting)))
2413 (when (and waiting (string= color (car waiting)))
2414 (gnugo--rename-buffer-portion)
2415 (setcdr waiting
2416 ;; heuristic: Warp only if it appears
2417 ;; that the user is "following along".
2418 (or (ignore-errors
2419 (string= (gnugo-position)
2420 (gnugo-move-history 'bpos color)))
2421 'nowarp))
2422 (gnugo--display-suggestion color "forthcoming")
2423 (sit-for 2))))
2424 (let* ((wheel (gnugo-get :wheel))
2425 (timer (car wheel))
2426 (karma (cdr wheel)))
2427 (when (timerp timer)
2428 (cancel-timer timer))
2429 (setcar wheel nil)
2430 (setcdr wheel (setq karma
2431 ;; walk to the west, fly to the east,
2432 ;; talk and then rest, cry and then feast.
2433 ;; 99 beers down thirsty throats sloshed?
2434 ;; 500 years under pink mountains squashed?
2435 ;; balk with the best, child now re-creased!
2436 (if updn
2437 (push color karma)
2438 (delete color karma))))
2439 (gnugo--dance-dance karma))
2440 (gnugo--turn-the-wheel t))))
2441
2442 (define-minor-mode gnugo-assist-mode
2443 "If enabled (\"Assist\" in mode line), GNU Go plays for you.
2444 When disabling, if GNU Go has already started thinking of
2445 a move to play for you, the thinking is not cancelled but instead
2446 transformed into a move suggestion (see `gnugo-request-suggestion')."
2447 :variable
2448 ((gnugo--assist-state)
2449 .
2450 (lambda (bool)
2451 (gnugo--struggle :user-color bool))))
2452
2453 (define-minor-mode gnugo-zombie-mode
2454 "If enabled (\"Zombie\" in mode line), GNU Go lets you play for it.
2455 When disabling, if GNU Go has already started thinking of
2456 a move to play, the thinking is not cancelled but instead
2457 transformed into a move suggestion (see `gnugo-request-suggestion')."
2458 :variable
2459 ((not (gnugo--:karma :gnugo-color))
2460 .
2461 (lambda (bool)
2462 (gnugo--struggle :gnugo-color (not bool)))))
2463
2464 ;;;---------------------------------------------------------------------------
2465 ;;; Command properties and gnugo-command
2466
2467 ;; GTP commands entered by the user are never issued directly to GNU Go;
2468 ;; instead, their behavior and output are controlled by the property
2469 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2470 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2471 ;;
2472 ;; :full -- completely interpret the command string; the value is a
2473 ;; func that takes the list of words derived from splitting the
2474 ;; command string (minus the command) and handles everything.
2475 ;;
2476 ;; :output -- either a keyword specifying the preferred output method:
2477 ;; :message -- show output in minibuffer
2478 ;; :discard -- sometimes you just don't care;
2479 ;; or a function that takes one arg, the output string, and
2480 ;; handles it completely. default is to switch to buffer
2481 ;; "*gnugo command output*" if the output has a newline,
2482 ;; otherwise use `message'.
2483 ;;
2484 ;; :post-thunk -- run after output processing (at the very end).
2485
2486 (defun gnugo-command (command)
2487 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2488 Output and Emacs behavior depend on which command is given (some
2489 commands are handled completely by Emacs w/o using the subprocess;
2490 some commands have their output displayed in specially prepared
2491 buffers or in the echo area; some commands are instrumented to do
2492 gnugo.el-specific housekeeping).
2493
2494 For example, for the command \"help\", Emacs visits the
2495 GTP command reference info page.
2496
2497 NOTE: At this time, GTP command handling specification is still
2498 incomplete. Thus, some commands WILL confuse gnugo.el."
2499 (interactive "sCommand: ")
2500 (if (string= "" command)
2501 (message "(no command given)")
2502 (let* ((split (split-string command))
2503 (cmd (intern (car split)))
2504 (spec (get cmd :gnugo-gtp-command-spec))
2505 (full (plist-get spec :full)))
2506 (if full
2507 (funcall full (cdr split))
2508 (message "Doing %s ..." command)
2509 (let* ((ans (gnugo--q command))
2510 (where (plist-get spec :output)))
2511 (if (string-match "unknown.command" ans)
2512 (message "%s" ans)
2513 (cond ((functionp where) (funcall where ans))
2514 ((eq :discard where) (message ""))
2515 ((or (eq :message where)
2516 (not (string-match "\n" ans)))
2517 (message "%s" ans))
2518 (t (switch-to-buffer "*gnugo command output*")
2519 (erase-buffer)
2520 (insert ans)
2521 (message "Doing %s ... done." command)))
2522 (let ((thunk (plist-get spec :post-thunk)))
2523 (when thunk (funcall thunk)))))))))
2524
2525 ;;;---------------------------------------------------------------------------
2526 ;;; Major mode for interacting with a GNUGO subprocess
2527
2528 (define-derived-mode gnugo-board-mode special-mode "GNUGO Board"
2529 "Major mode for playing GNU Go.
2530 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2531 In this mode, keys do not self insert.
2532
2533 \\{gnugo-board-mode-map}"
2534 (buffer-disable-undo) ; todo: undo undo undoing
2535 (setq font-lock-defaults '(gnugo-font-lock-keywords t)
2536 truncate-lines t)
2537 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2538 (set (make-local-variable 'gnugo-state)
2539 (gnugo--mkht :size (1- 42)))
2540 (set (make-local-variable 'gnugo-btw) nil)
2541 (add-to-list 'minor-mode-alist '(gnugo-btw gnugo-btw))
2542 (gnugo-put :highlight-last-move-spec
2543 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2544 (gnugo-put :paren-ov (cons (make-overlay 1 1)
2545 (let ((ov (make-overlay 1 1)))
2546 (overlay-put ov 'display ")")
2547 ov)))
2548 (gnugo-put :mul '(1 . 1))
2549 (gnugo-put :obarray (make-vector 31 nil))
2550 (add-to-invisibility-spec :nogrid))
2551
2552 ;;;---------------------------------------------------------------------------
2553 ;;; Entry point
2554
2555 ;;;###autoload
2556 (defun gnugo (&optional new-game)
2557 "Run gnugo in a buffer, or resume a game in progress.
2558 If there is already a game in progress you may resume it instead
2559 of starting a new one. Prefix arg means skip the game-in-progress
2560 check and start a new game straight away.
2561
2562 Before starting, Emacs queries you for additional command-line
2563 options (Emacs supplies \"--mode gtp --quiet\" automatically).
2564
2565 Note that specifying \"--infile FILENAME\" (or, \"-l FILENAME\")
2566 silently clobbers certain other options, such as \"--color\".
2567 For details, see info node `(gnugo) Invoking GNU Go'.
2568
2569 \\<gnugo-board-mode-map>
2570 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2571 See `gnugo-board-mode' for a full list of commands."
2572 (interactive "P")
2573 (let* ((all (let (acc)
2574 (dolist (buf (buffer-list))
2575 (when (gnugo-board-buffer-p buf)
2576 (push (cons (buffer-name buf) buf) acc)))
2577 acc))
2578 (n (length all)))
2579 (if (and (not new-game)
2580 (cl-plusp n)
2581 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2582 (if (= 1 n) "" "s"))))
2583 ;; resume
2584 (switch-to-buffer
2585 (cdr (if (= 1 n)
2586 (car all)
2587 (let ((sel (completing-read "Which one? " all nil t)))
2588 (if (string= "" sel)
2589 (car all)
2590 (assoc sel all))))))
2591 ;; sanity check
2592 (unless (executable-find gnugo-program)
2593 (user-error "Invalid `gnugo-program': %S" gnugo-program))
2594 ;; set up a new board
2595 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2596 (gnugo-board-mode)
2597 (let* ((filename nil)
2598 (user-color "black")
2599 (args (loop
2600 with ls = (split-string
2601 ;; todo: grok ‘gnugo --help’; completion
2602 (read-string
2603 "GNU Go options: "
2604 (car gnugo-option-history)
2605 'gnugo-option-history))
2606 with ok
2607 while ls do
2608 (let ((arg (pop ls)))
2609 (cl-flet
2610 ((ex (opt fn)
2611 (if filename
2612 (warn "%s %s ignored" opt fn)
2613 (setq filename fn))))
2614 (cond
2615 ((string= "--color" arg)
2616 (push arg ok)
2617 (push
2618 ;; Unfortunately, GTP does not provide
2619 ;; a way to query the user color, so
2620 ;; we must resort to this weirdness.
2621 (setq user-color
2622 (pop ls))
2623 ok))
2624 ((string= "--infile" arg)
2625 (ex "--infile" (pop ls)))
2626 ((string-match "^-l" arg)
2627 (ex "-l" (if (< 2 (length arg))
2628 (substring arg 2)
2629 (pop ls))))
2630 (t (push arg ok)))))
2631 finally return (nreverse ok)))
2632 (proc (apply 'start-process "gnugo"
2633 (current-buffer)
2634 gnugo-program
2635 "--mode" "gtp" "--quiet"
2636 args))
2637 root board-size handicap komi)
2638 (gnugo-put :user-color user-color)
2639 (gnugo-put :proc proc)
2640 (set-process-sentinel proc 'gnugo-sentinel)
2641 ;; Emacs is too protective sometimes, blech.
2642 (set-process-query-on-exit-flag proc nil)
2643 (gnugo-put :diamond (substring (process-name proc) 5))
2644 (gnugo-put :gnugo-color (gnugo-other user-color))
2645 (if filename
2646 (gnugo-read-sgf-file (expand-file-name filename))
2647 (cl-flet
2648 ((r! (&rest plist) (apply 'gnugo--decorate root plist)))
2649 (gnugo--SZ!
2650 (setq root (gnugo--root-node
2651 (gnugo--plant-and-climb
2652 (gnugo/sgf-create "(;FF[4]GM[1])" t)))
2653 komi (gnugo--nquery "get_komi")
2654 handicap (gnugo--nquery "get_handicap")
2655 board-size (gnugo--nquery "query_boardsize")))
2656 ;; Work around a GNU Go 3.8 (and possibly earlier/later)
2657 ;; bug whereby GTP command ‘get_handicap’ fails to return
2658 ;; the N set by ‘--handicap N’ on the command line.
2659 (let ((actually (member "--handicap" args)))
2660 ;; Checking ‘(zerop handicap)’ first is not strictly
2661 ;; necessary; it represents a hope that some day GNU Go
2662 ;; will DTRT (or provide rationale for this weird behavior)
2663 ;; and become worthy of our trust.
2664 (when (and (zerop handicap) actually)
2665 (setq handicap (string-to-number (cadr actually)))))
2666 (r! :SZ board-size
2667 :DT (format-time-string "%Y-%m-%d")
2668 :RU (if (member "--chinese-rules" args)
2669 "Chinese"
2670 "Japanese")
2671 :AP (cons "gnugo.el" gnugo-version)
2672 :KM komi)
2673 (let ((ub (gnugo--blackp user-color)))
2674 (r! (if ub :PW :PB) (concat "GNU Go " (gnugo-query "version"))
2675 (if ub :PB :PW) (user-full-name)))
2676 (unless (zerop handicap)
2677 (r! :HA handicap
2678 :AB (mapcar (gnugo--as-cc-func)
2679 (gnugo-lsquery "fixed_handicap %d"
2680 handicap)))))))
2681 (gnugo-put :waiting-start (current-time))
2682 (gnugo-refresh t)
2683 (gnugo-goto-pos (or (gnugo-get :last-user-bpos)
2684 (gnugo-get :center-position)))
2685 ;; first move
2686 (gnugo-put :game-start-time (current-time))
2687 (let ((g (gnugo-get :gnugo-color))
2688 (n (or (gnugo--root-prop :HA) 0))
2689 (u (gnugo-get :user-color)))
2690 (unless (gnugo-get :last-mover)
2691 (gnugo-put :last-mover
2692 (if (or (and (gnugo--blackp u) (< 1 n))
2693 (and (gnugo--blackp g) (< n 2)))
2694 u
2695 g)))
2696 (let ((karma (list g)))
2697 (gnugo-put :wheel (cons nil karma))
2698 (gnugo--dance-dance karma))
2699 (run-hooks 'gnugo-start-game-hook)
2700 (gnugo--turn-the-wheel)))))
2701
2702 ;;;---------------------------------------------------------------------------
2703 ;;; Load-time actions
2704
2705 (unless gnugo-frolic-mode-map
2706 (setq gnugo-frolic-mode-map (make-sparse-keymap))
2707 (suppress-keymap gnugo-frolic-mode-map)
2708 (mapc (lambda (pair)
2709 (define-key gnugo-frolic-mode-map (car pair) (cdr pair)))
2710 '(("q" . gnugo-frolic-quit)
2711 ("Q" . gnugo-frolic-quit)
2712 ("\C-q" . gnugo-frolic-quit)
2713 ("C" . gnugo-frolic-quit) ; like ‘View-kill-and-leave’
2714 ("\C-b" . gnugo-frolic-backward-branch)
2715 ("\C-f" . gnugo-frolic-forward-branch)
2716 ("\C-p" . gnugo-frolic-previous-move)
2717 ("\C-n" . gnugo-frolic-next-move)
2718 ("t" . gnugo-frolic-tip-move)
2719 ("j" . gnugo-frolic-exchange-left)
2720 ("J" . gnugo-frolic-rotate-left)
2721 ("k" . gnugo-frolic-exchange-right)
2722 ("K" . gnugo-frolic-rotate-right)
2723 ("\C-m" . gnugo-frolic-set-as-main-line)
2724 ("\C-\M-p" . gnugo-frolic-prune-branch)
2725 ("o" . gnugo-frolic-return-to-origin))))
2726
2727 (unless gnugo-board-mode-map
2728 (setq gnugo-board-mode-map (make-sparse-keymap))
2729 (suppress-keymap gnugo-board-mode-map)
2730 (mapc (lambda (pair)
2731 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2732 '(("?" . describe-mode)
2733 ("S" . gnugo-request-suggestion)
2734 ("\C-m" . gnugo-move)
2735 (" " . gnugo-move)
2736 ("P" . gnugo-pass)
2737 ("R" . gnugo-resign)
2738 ("q" . gnugo-quit)
2739 ("Q" . gnugo-leave-me-alone)
2740 ("U" . gnugo-fancy-undo)
2741 ("\M-u" . gnugo-undo-one-move)
2742 ("u" . gnugo-undo-two-moves)
2743 ("\C-?" . gnugo-undo-two-moves)
2744 ("o" . gnugo-oops)
2745 ("O" . gnugo-okay)
2746 ("\C-l" . gnugo-refresh)
2747 ("\M-_" . gnugo-boss-is-near)
2748 ("_" . gnugo-boss-is-near)
2749 ("h" . gnugo-move-history)
2750 ("L" . gnugo-frolic-in-the-leaves)
2751 ("\C-c\C-l" . gnugo-frolic-in-the-leaves)
2752 ("i" . gnugo-image-display-mode)
2753 ("w" . gnugo-worm-stones)
2754 ("W" . gnugo-worm-data)
2755 ("d" . gnugo-dragon-stones)
2756 ("D" . gnugo-dragon-data)
2757 ("g" . gnugo-grid-mode)
2758 ("!" . gnugo-estimate-score)
2759 (":" . gnugo-command)
2760 (";" . gnugo-command)
2761 ("=" . gnugo-describe-position)
2762 ("s" . gnugo-write-sgf-file)
2763 ("\C-x\C-s" . gnugo-write-sgf-file)
2764 ("\C-x\C-w" . gnugo-write-sgf-file)
2765 ("l" . gnugo-read-sgf-file)
2766 ("F" . gnugo-display-final-score)
2767 ("A" . gnugo-switch-to-another)
2768 ("C" . gnugo-comment)
2769 ("\C-c\C-a" . gnugo-assist-mode)
2770 ("\C-c\C-z" . gnugo-zombie-mode)
2771 ;; mouse
2772 ([(down-mouse-1)] . gnugo-mouse-move)
2773 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
2774 ([(down-mouse-3)] . gnugo-mouse-pass)
2775 ;; delving into the curiosities
2776 ("\C-c\C-p" . gnugo-describe-internal-properties))))
2777
2778 (unless (get 'help :gnugo-gtp-command-spec)
2779 (cl-flet*
2780 ((sget (x) (get x :gnugo-gtp-command-spec))
2781 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2782 (plist-put (sget cmd) prop val)))
2783 (validpos (s &optional go)
2784 (let ((pos (upcase s)))
2785 (loop with size = (gnugo-get :SZ)
2786 for c across (funcall (gnugo--as-cc-func)
2787 pos)
2788 do (let ((norm (- c ?a)))
2789 (unless (and (< -1 norm)
2790 (> size norm))
2791 (user-error "Invalid position: %s"
2792 pos))))
2793 (when go
2794 (gnugo-goto-pos pos))
2795 pos))
2796 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2797 (let ((ls props))
2798 (while ls
2799 (jam cmd (car ls) (cadr ls))
2800 (setq ls (cddr ls)))))))
2801 (cl-macrolet ((deffull (who &body body)
2802 (declare (indent 1))
2803 `(defgtp ',who :full (lambda (sel)
2804 ,@body))))
2805
2806 (deffull help
2807 (info "(gnugo)GTP command reference")
2808 (when sel (setq sel (intern (car sel))))
2809 (let (buffer-read-only pad cur spec output found)
2810 (cl-flet
2811 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2812 (goto-char (point-min))
2813 (save-excursion
2814 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2815 (point-max) t)
2816 (unless pad
2817 (setq pad (make-string (- (match-beginning 1)
2818 (match-beginning 0))
2819 32)))
2820 (when (plist-get
2821 (setq spec
2822 (get (setq cur (intern (match-string 1)))
2823 :gnugo-gtp-command-spec))
2824 :full)
2825 (note "handles this command completely"))
2826 (when (setq output (plist-get spec :output))
2827 (if (functionp output)
2828 (note "handles the output specially")
2829 (case output
2830 (:discard (note "discards the output"))
2831 (:message (note "displays the output in the echo area")))))
2832 (when (eq sel cur)
2833 (setq found (make-marker))
2834 (set-marker found (match-beginning 0))))))
2835 (cond (found (goto-char found) (set-marker found nil))
2836 ((not sel))
2837 (t (message "(no such command: %s)" sel)))))
2838
2839 (deffull final_score
2840 ;; Explicit ignorance avoids byte-compiler warning.
2841 (ignore sel)
2842 (gnugo-display-final-score))
2843
2844 (defgtp '(boardsize
2845 clear_board
2846 fixed_handicap)
2847 :output :discard
2848 :post-thunk (lambda ()
2849 (gnugo--unclose-game)
2850 (gnugo--forget :last-mover)
2851 ;; ugh
2852 (gnugo--SZ! (gnugo--nquery "query_boardsize"))
2853 (gnugo-refresh t)))
2854
2855 (deffull loadsgf
2856 (gnugo-read-sgf-file (car sel)))
2857
2858 (deffull (undo gg-undo)
2859 (gnugo--climb-towards-root
2860 (let (n)
2861 (cond ((not sel) 1)
2862 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2863 (t (validpos (car sel) t)))))))))
2864
2865 (provide 'gnugo)
2866
2867 \f
2868 ;;;---------------------------------------------------------------------------
2869 ;;; The remainder of this file defines a simplified SGF-handling library.
2870 ;;; When/if it should start to attain generality, it should be split off into
2871 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2872 ;;; "gnugo/" prefix.
2873
2874 (defconst gnugo/sgf-*r4-properties*
2875 '((AB "Add Black" setup list stone)
2876 (AE "Add Empty" game list point)
2877 (AN "Annotation" game simpletext)
2878 (AP "Application" root (simpletext . simpletext))
2879 (AR "Arrow" - list (point . point))
2880 (AS "Who adds stones" - simpletext) ; (LOA)
2881 (AW "Add White" setup list stone)
2882 (B "Black" move move)
2883 (BL "Black time left" move real)
2884 (BM "Bad move" move double)
2885 (BR "Black rank" game simpletext)
2886 (BT "Black team" game simpletext)
2887 (C "Comment" - text)
2888 (CA "Charset" root simpletext)
2889 (CP "Copyright" game simpletext)
2890 (CR "Circle" - list point)
2891 (DD "Dim points" - elist point) ; (inherit)
2892 (DM "Even position" - double)
2893 (DO "Doubtful" move none)
2894 (DT "Date" game simpletext)
2895 (EV "Event" game simpletext)
2896 (FF "Fileformat" root [number (1 . 4)])
2897 (FG "Figure" - (or none (number . simpletext)))
2898 (GB "Good for Black" - double)
2899 (GC "Game comment" game text)
2900 (GM "Game" root [number (1 . 20)])
2901 (GN "Game name" game simpletext)
2902 (GW "Good for White" - double)
2903 (HA "Handicap" game number) ; (Go)
2904 (HO "Hotspot" - double)
2905 (IP "Initial pos." game simpletext) ; (LOA)
2906 (IT "Interesting" move none)
2907 (IY "Invert Y-axis" game simpletext) ; (LOA)
2908 (KM "Komi" game real) ; (Go)
2909 (KO "Ko" move none)
2910 (LB "Label" - list (point . simpletext))
2911 (LN "Line" - list (point . point))
2912 (MA "Mark" - list point)
2913 (MN "set move number" move number)
2914 (N "Nodename" - simpletext)
2915 (OB "OtStones Black" move number)
2916 (ON "Opening" game text)
2917 (OT "Overtime" game simpletext)
2918 (OW "OtStones White" move number)
2919 (PB "Player Black" game simpletext)
2920 (PC "Place" game simpletext)
2921 (PL "Player to play" setup color)
2922 (PM "Print move mode" - number) ; (inherit)
2923 (PW "Player White" game simpletext)
2924 (RE "Result" game simpletext)
2925 (RO "Round" game simpletext)
2926 (RU "Rules" game simpletext)
2927 (SE "Markup" - point) ; (LOA)
2928 (SL "Selected" - list point)
2929 (SO "Source" game simpletext)
2930 (SQ "Square" - list point)
2931 (ST "Style" root [number (0 . 3)])
2932 (SU "Setup type" game simpletext) ; (LOA)
2933 (SZ "Size" root (or number (number . number)))
2934 (TB "Territory Black" - elist point) ; (Go)
2935 (TE "Tesuji" move double)
2936 (TM "Timelimit" game real)
2937 (TR "Triangle" - list point)
2938 (TW "Territory White" - elist point) ; (Go)
2939 (UC "Unclear pos" - double)
2940 (US "User" game simpletext)
2941 (V "Value" - real)
2942 (VW "View" - elist point) ; (inherit)
2943 (W "White" move move)
2944 (WL "White time left" move real)
2945 (WR "White rank" game simpletext)
2946 (WT "White team" game simpletext)
2947 (LT "Lose on time" setup simpletext))
2948 ;; r4-specific notes
2949 ;; - changed: DT FG LB RE RU SZ
2950 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2951 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2952
2953 (defun gnugo/sgf-create (file-or-data &optional data-p)
2954 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2955 FILE-OR-DATA is a file name or SGF[4] data.
2956 Optional arg DATA-P non-nil means FILE-OR-DATA is
2957 a string containing SGF[4] data.
2958 A collection is a list of gametrees, each a vector of four elements:
2959
2960 ENDS -- a vector of node lists, with shared tails
2961 (last element of all the lists is the root node)
2962
2963 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2964 have a move number of the previous \"move\" node (or zero)
2965
2966 ROOT -- the root node"
2967 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2968 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2969 (put 'gnugo/sgf-*r4-properties* :keywords
2970 (mapcar (lambda (full)
2971 (cons (car full)
2972 (intern (format ":%s" (car full)))))
2973 gnugo/sgf-*r4-properties*))))
2974 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2975 (put 'gnugo/sgf-*r4-properties* :specs
2976 (mapcar (lambda (full)
2977 (cons (car full) (cdddr full)))
2978 gnugo/sgf-*r4-properties*))))
2979 SZ)
2980 (cl-labels
2981 ((sw () (skip-chars-forward " \t\n"))
2982 (x (end preserve-whitespace)
2983 (let ((beg (point))
2984 (endp (case end
2985 (:end (lambda (char) (= ?\] char)))
2986 (:mid (lambda (char) (= ?\: char)))
2987 (t (lambda (char) (or (= ?\: char)
2988 (= ?\] char))))))
2989 c)
2990 (while (not (funcall endp (setq c (following-char))))
2991 (cond ((= ?\\ c)
2992 (delete-char 1)
2993 (if (eolp)
2994 (kill-line 1)
2995 (forward-char 1)))
2996 ((unless preserve-whitespace
2997 (looking-at "\\s-+"))
2998 (delete-region (point) (match-end 0))
2999 (insert " "))
3000 (t (forward-char 1))))
3001 (buffer-substring-no-properties beg (point))))
3002 (one (type end) (let ((s (progn
3003 (forward-char 1)
3004 (x end (eq 'text type)))))
3005 (case type
3006 ((stone point move)
3007 ;; blech, begone bu"tt"-ugly blatherings
3008 ;; (but bide brobdingnagian boards)...
3009 (if (and (string= "tt" s)
3010 SZ
3011 (>= 19 SZ))
3012 ""
3013 s))
3014 ((simpletext color) s)
3015 ((number real double) (string-to-number s))
3016 ((text) s)
3017 ((none) "")
3018 (t (error "Unhandled type: %S" type)))))
3019 (val (spec) (cond ((symbolp spec)
3020 (one spec :end))
3021 ((vectorp spec)
3022 ;; todo: check range here.
3023 (one (aref spec 0) :end))
3024 ((eq 'or (car spec))
3025 (let ((v (one (cadr spec) t)))
3026 (if (= ?\] (following-char))
3027 v
3028 (forward-char 1)
3029 ;; todo: this assumes `spec' has the form
3030 ;; (or foo (foo . bar))
3031 ;; i.e., foo is not rescanned. e.g., `SZ'.
3032 ;; probably this assumption is consistent
3033 ;; w/ the SGF authors' desire to make the
3034 ;; parsing easy, but you never know...
3035 (cons v (one (cdaddr spec) :end)))))
3036 (t (cons (one (car spec) :mid)
3037 (one (cdr spec) :end)))))
3038 (short (who) (when (eobp)
3039 (error "Unexpected EOF while reading %s" who)))
3040 (atvalp () (= ?\[ (following-char)))
3041 (PROP () (let (name spec ltype)
3042 (sw) (short 'property)
3043 (when (looking-at "[A-Z]")
3044 (setq name (read (current-buffer))
3045 spec (cdr (assq name specs)))
3046 (sw)
3047 (cons
3048 (cdr (assq name keywords))
3049 (prog1 (if (= 1 (length spec))
3050 (val (car spec))
3051 (unless (memq (setq ltype (car spec))
3052 '(elist list))
3053 (error "Bad spec: %S" spec))
3054 (if (and (eq 'elist ltype) (sw)
3055 (not (atvalp)))
3056 nil
3057 (let ((type (cadr spec))
3058 mo ls)
3059 (while (and (sw) (atvalp)
3060 (setq mo (val type)))
3061 (push mo ls)
3062 (forward-char 1))
3063 (forward-char -1)
3064 (nreverse ls))))
3065 (forward-char 1))))))
3066 (morep () (and (sw) (not (eobp))))
3067 (seek (c) (and (morep) (= c (following-char))))
3068 (seek-into (c) (when (seek c)
3069 (forward-char 1)
3070 t))
3071 (NODE () (when (seek-into ?\;)
3072 (loop with prop
3073 while (setq prop (PROP))
3074 collect (progn
3075 (when (eq :SZ (car prop))
3076 (setq SZ (cdr prop)))
3077 prop))))
3078 (TREE (parent mnum)
3079 (let ((ls parent)
3080 prev node)
3081 (seek-into ?\()
3082 (while (seek ?\;)
3083 (setq prev (car ls)
3084 node (NODE))
3085 (puthash node (+ (if (gnugo--move-prop node)
3086 1
3087 0)
3088 (gethash prev mnum 0))
3089 mnum)
3090 (push node
3091 ls))
3092 (prog1
3093 (if (not (seek ?\())
3094 ;; singular
3095 (list ls)
3096 ;; multiple
3097 (loop while (seek ?\()
3098 append (TREE ls mnum)))
3099 (seek-into ?\))))))
3100 (with-temp-buffer
3101 (if (not data-p)
3102 (insert-file-contents file-or-data)
3103 (insert file-or-data)
3104 (goto-char (point-min)))
3105 (loop while (morep)
3106 collect (let* ((mnum (gnugo--mkht :weakness 'key))
3107 (ends (TREE nil mnum))
3108 (root (car (last (car ends)))))
3109 (vector (apply 'vector ends)
3110 mnum
3111 root)))))))
3112
3113 (defun gnugo/sgf-write-file (collection filename)
3114 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
3115 (me (cons "gnugo.el" gnugo-version))
3116 (specs (mapcar (lambda (full)
3117 (cons (intern (format ":%s" (car full)))
3118 (cdddr full)))
3119 gnugo/sgf-*r4-properties*))
3120 p name v spec)
3121 (cl-labels
3122 ((esc (composed fmt arg)
3123 (mapconcat (lambda (c)
3124 (case c
3125 ;; ‘?\[’ is not strictly required
3126 ;; but neither is it forbidden.
3127 ((?\[ ?\] ?\\) (format "\\%c" c))
3128 (?: (concat (if composed "\\" "") ":"))
3129 (t (string c))))
3130 (string-to-list (format fmt arg))
3131 ""))
3132 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
3133 (>>two (v) (insert "["
3134 (esc t "%s" (car v))
3135 ":"
3136 (esc t "%s" (cdr v))
3137 "]"))
3138 (>>nl () (cond ((memq name aft-newline-appreciated)
3139 (insert "\n"))
3140 ((< 60 (current-column))
3141 (save-excursion
3142 (goto-char p)
3143 (insert "\n")))))
3144 (>>prop (prop)
3145 (setq p (point)
3146 name (car prop)
3147 v (cdr prop))
3148 (insert (substring (symbol-name name) 1))
3149 (cond ((not v))
3150 ((and (consp v)
3151 (setq spec (cdr (assq name specs)))
3152 (memq (car spec)
3153 '(list elist)))
3154 (>>nl)
3155 (let ((>> (if (consp (cadr spec))
3156 #'>>two
3157 #'>>one)))
3158 (dolist (little-v v)
3159 (setq p (point))
3160 (funcall >> little-v)
3161 (>>nl))))
3162 ((consp v)
3163 (>>two v) (>>nl))
3164 (t
3165 (>>one v) (>>nl))))
3166 (>>node (node)
3167 (loop initially (insert ";")
3168 for prop in node
3169 do (>>prop prop)))
3170 (>>tree (tree)
3171 (unless (zerop (current-column))
3172 (newline))
3173 (insert "(")
3174 (dolist (x tree)
3175 (funcall (if (gnugo--nodep x)
3176 #'>>node
3177 #'>>tree)
3178 x))
3179 (insert ")")))
3180 (with-temp-buffer
3181 (dolist (tree collection)
3182 ;; take responsibility for our actions
3183 (gnugo--set-root-prop :AP me tree)
3184 ;; write it out
3185 (let ((ht (gnugo--mkht))
3186 (leaves (append (gnugo--tree-ends tree) nil)))
3187 (cl-flet
3188 ((hang (stack)
3189 (loop
3190 with rh ; rectified history
3191 with bp ; branch point
3192 for node in stack
3193 until (setq bp (gethash node ht))
3194 do (puthash node
3195 (push node rh) ; good for now: ½τ
3196 ht)
3197 finally return
3198 (if (not bp)
3199 ;; first run: main line
3200 rh
3201 ;; subsequent runs: grafts (value discarded)
3202 (setcdr bp (nconc
3203 ;; Maintain order of ‘leaves’.
3204 (let ((was (cdr bp)))
3205 (if (gnugo--nodep (car was))
3206 (list was)
3207 was))
3208 (list rh)))))))
3209 (setq tree (hang (pop leaves)))
3210 (mapc #'hang leaves)
3211 (>>tree tree))))
3212 (newline)
3213 (write-file filename)))))
3214
3215 ;;; gnugo.el ends here