More tweaks of skeleton documentation wrt \n behavior at bol/eol.
[bpt/emacs.git] / lisp / play / decipher.el
CommitLineData
6e44da43 1;;; decipher.el --- cryptanalyze monoalphabetic substitution ciphers
c10902fb 2;;
ba318903 3;; Copyright (C) 1995-1996, 2001-2014 Free Software Foundation, Inc.
c10902fb 4;;
bb10be4c 5;; Author: Christopher J. Madsen <chris_madsen@geocities.com>
c10902fb
RS
6;; Keywords: games
7;;
8;; This file is part of GNU Emacs.
9;;
b1fc2b50 10;; GNU Emacs is free software: you can redistribute it and/or modify
c10902fb 11;; it under the terms of the GNU General Public License as published by
b1fc2b50
GM
12;; the Free Software Foundation, either version 3 of the License, or
13;; (at your option) any later version.
14
c10902fb
RS
15;; GNU Emacs 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.
b1fc2b50 19
c10902fb 20;; You should have received a copy of the GNU General Public License
b1fc2b50 21;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
c10902fb 22
9f56503b
DL
23;;; Commentary:
24;;
c10902fb
RS
25;;; Quick Start:
26;;
27;; To decipher a message, type or load it into a buffer and type
28;; `M-x decipher'. This will format the buffer and place it into
29;; Decipher mode. You can save your work to a file with the normal
30;; Emacs save commands; when you reload the file it will automatically
31;; enter Decipher mode.
32;;
33;; I'm not going to discuss how to go about breaking a cipher; try
34;; your local library for a book on cryptanalysis. One book you might
35;; find is:
36;; Cryptanalysis: A study of ciphers and their solution
37;; Helen Fouche Gaines
38;; ISBN 0-486-20097-3
39
c10902fb
RS
40;; This package is designed to help you crack simple substitution
41;; ciphers where one letter stands for another. It works for ciphers
42;; with or without word divisions. (You must set the variable
43;; decipher-ignore-spaces for ciphers without word divisions.)
44;;
45;; First, some quick definitions:
46;; ciphertext The encrypted message (what you start with)
47;; plaintext The decrypted message (what you are trying to get)
48;;
49;; Decipher mode displays ciphertext in uppercase and plaintext in
50;; lowercase. You must enter the plaintext in lowercase; uppercase
51;; letters are interpreted as commands. The ciphertext may be entered
52;; in mixed case; `M-x decipher' will convert it to uppercase.
53;;
54;; Decipher mode depends on special characters in the first column of
55;; each line. The command `M-x decipher' inserts these characters for
56;; you. The characters and their meanings are:
57;; ( The plaintext & ciphertext alphabets on the first line
58;; ) The ciphertext & plaintext alphabets on the second line
59;; : A line of ciphertext (with plaintext below)
60;; > A line of plaintext (with ciphertext above)
61;; % A comment
62;; Each line in the buffer MUST begin with one of these characters (or
63;; be left blank). In addition, comments beginning with `%!' are reserved
64;; for checkpoints; see decipher-make-checkpoint & decipher-restore-checkpoint
65;; for more information.
66;;
67;; While the cipher message may contain digits or punctuation, Decipher
68;; mode will ignore these characters.
69;;
70;; The buffer is made read-only so it can't be modified by normal
71;; Emacs commands.
40600c94
RS
72;;
73;; Decipher supports Font Lock mode. To use it, you can also add
74;; (add-hook 'decipher-mode-hook 'turn-on-font-lock)
75;; See the variable `decipher-font-lock-keywords' if you want to customize
76;; the faces used. I'd like to thank Simon Marshall for his help in making
77;; Decipher work well with Font Lock.
c10902fb
RS
78
79;;; Things To Do:
80;;
ddfb0a34
KH
81;; Email me if you have any suggestions or would like to help.
82;; But be aware that I work on Decipher only sporadically.
83;;
84;; 1. The consonant-line shortcut
85;; 2. More functions for analyzing ciphertext
c10902fb
RS
86
87;;;===================================================================
88;;; Variables:
89;;;===================================================================
90
a464a6c7 91(eval-when-compile (require 'cl-lib))
c10902fb 92
323f7c49
SE
93(defgroup decipher nil
94 "Cryptanalyze monoalphabetic substitution ciphers."
95 :prefix "decipher-"
96 :group 'games)
97
98(defcustom decipher-force-uppercase t
67d110f1 99 "Non-nil means to convert ciphertext to uppercase.
f0529b5b 100nil means the case of the ciphertext is preserved.
323f7c49
SE
101This variable must be set before typing `\\[decipher]'."
102 :type 'boolean
103 :group 'decipher)
104
c10902fb 105
323f7c49 106(defcustom decipher-ignore-spaces nil
67d110f1 107 "Non-nil means to ignore spaces and punctuation when counting digrams.
e7f32a75
JB
108You should set this to nil if the cipher message is divided into words,
109or t if it is not.
323f7c49
SE
110This variable is buffer-local."
111 :type 'boolean
112 :group 'decipher)
c10902fb
RS
113(make-variable-buffer-local 'decipher-ignore-spaces)
114
323f7c49 115(defcustom decipher-undo-limit 5000
c10902fb
RS
116 "The maximum number of entries in the undo list.
117When the undo list exceeds this number, 100 entries are deleted from
323f7c49
SE
118the tail of the list."
119 :type 'integer
120 :group 'decipher)
121
122(defcustom decipher-mode-hook nil
123 "Hook to run upon entry to decipher."
124 :type 'hook
125 :group 'decipher)
c10902fb
RS
126
127;; End of user modifiable variables
128;;--------------------------------------------------------------------
129
a378799a 130(defvar decipher-font-lock-keywords
40600c94
RS
131 '(("^:.*" . font-lock-keyword-face)
132 ("^>.*" . font-lock-string-face)
883212ce 133 ("^%!.*" . font-lock-constant-face)
40600c94
RS
134 ("^%.*" . font-lock-comment-face)
135 ("\\`(\\([a-z]+\\) +\\([A-Z]+\\)"
a378799a 136 (1 font-lock-string-face)
40600c94
RS
137 (2 font-lock-keyword-face))
138 ("^)\\([A-Z ]+\\)\\([a-z ]+\\)"
139 (1 font-lock-keyword-face)
140 (2 font-lock-string-face)))
865fe16f 141 "Font Lock keywords for Decipher mode.")
40600c94 142
a0310a6c
DN
143(defvar decipher-mode-map
144 (let ((map (make-keymap)))
145 (suppress-keymap map)
146 (define-key map "A" 'decipher-show-alphabet)
147 (define-key map "C" 'decipher-complete-alphabet)
148 (define-key map "D" 'decipher-digram-list)
149 (define-key map "F" 'decipher-frequency-count)
150 (define-key map "M" 'decipher-make-checkpoint)
151 (define-key map "N" 'decipher-adjacency-list)
152 (define-key map "R" 'decipher-restore-checkpoint)
153 (define-key map "U" 'decipher-undo)
154 (define-key map " " 'decipher-keypress)
155 (define-key map [remap undo] 'decipher-undo)
156 (define-key map [remap advertised-undo] 'decipher-undo)
157 (let ((key ?a))
158 (while (<= key ?z)
159 (define-key map (vector key) 'decipher-keypress)
a464a6c7 160 (cl-incf key)))
a0310a6c 161 map)
c10902fb 162 "Keymap for Decipher mode.")
a0310a6c
DN
163
164
165(defvar decipher-stats-mode-map
166 (let ((map (make-keymap)))
167 (suppress-keymap map)
168 (define-key map "D" 'decipher-digram-list)
169 (define-key map "F" 'decipher-frequency-count)
170 (define-key map "N" 'decipher-adjacency-list)
171 map)
172"Keymap for Decipher-Stats mode.")
173
c10902fb
RS
174
175(defvar decipher-mode-syntax-table nil
176 "Decipher mode syntax table")
177
178(if decipher-mode-syntax-table
179 ()
180 (let ((table (make-syntax-table))
181 (c ?0))
182 (while (<= c ?9)
183 (modify-syntax-entry c "_" table) ;Digits are not part of words
a464a6c7 184 (cl-incf c))
c10902fb
RS
185 (setq decipher-mode-syntax-table table)))
186
187(defvar decipher-alphabet nil)
188;; This is an alist containing entries (PLAIN-CHAR . CIPHER-CHAR),
189;; where PLAIN-CHAR runs from ?a to ?z and CIPHER-CHAR is an uppercase
190;; letter or space (which means no mapping is known for that letter).
191;; This *must* contain entries for all lowercase characters.
192(make-variable-buffer-local 'decipher-alphabet)
193
194(defvar decipher-stats-buffer nil
195 "The buffer which displays statistics for this ciphertext.
196Do not access this variable directly, use the function
197`decipher-stats-buffer' instead.")
198(make-variable-buffer-local 'decipher-stats-buffer)
199
200(defvar decipher-undo-list-size 0
201 "The number of entries in the undo list.")
202(make-variable-buffer-local 'decipher-undo-list-size)
203
204(defvar decipher-undo-list nil
205 "The undo list for this buffer.
206Each element is either a cons cell (PLAIN-CHAR . CIPHER-CHAR) or a
207list of such cons cells.")
208(make-variable-buffer-local 'decipher-undo-list)
209
210(defvar decipher-pending-undo-list nil)
211
ddfb0a34
KH
212;; The following variables are used by the analysis functions
213;; and are defined here to avoid byte-compiler warnings.
214;; Don't mess with them unless you know what you're doing.
215(defvar decipher-char nil
216 "See the functions decipher-loop-with-breaks and decipher-loop-no-breaks.")
217(defvar decipher--prev-char)
218(defvar decipher--digram)
219(defvar decipher--digram-list)
220(defvar decipher--before)
221(defvar decipher--after)
222(defvar decipher--freqs)
223
c10902fb
RS
224;;;===================================================================
225;;; Code:
226;;;===================================================================
227;; Main entry points:
228;;--------------------------------------------------------------------
229
230;;;###autoload
231(defun decipher ()
232 "Format a buffer of ciphertext for cryptanalysis and enter Decipher mode."
233 (interactive)
234 ;; Make sure the buffer ends in a newline:
235 (goto-char (point-max))
236 (or (bolp)
237 (insert "\n"))
238 ;; See if it's already in decipher format:
239 (goto-char (point-min))
240 (if (looking-at "^(abcdefghijklmnopqrstuvwxyz \
241ABCDEFGHIJKLMNOPQRSTUVWXYZ -\\*-decipher-\\*-\n)")
242 (message "Buffer is already formatted, entering Decipher mode...")
243 ;; Add the alphabet at the beginning of the file
244 (insert "(abcdefghijklmnopqrstuvwxyz \
245ABCDEFGHIJKLMNOPQRSTUVWXYZ -*-decipher-*-\n)\n\n")
246 ;; Add lines for the solution:
247 (let (begin)
248 (while (not (eobp))
249 (if (looking-at "^%")
250 (forward-line) ;Leave comments alone
251 (delete-horizontal-space)
252 (if (eolp)
253 (forward-line) ;Just leave blank lines alone
254 (insert ":") ;Mark ciphertext line
255 (setq begin (point))
256 (forward-line)
257 (if decipher-force-uppercase
258 (upcase-region begin (point))) ;Convert ciphertext to uppercase
259 (insert ">\n"))))) ;Mark plaintext line
260 (delete-blank-lines) ;Remove any blank lines
261 (delete-blank-lines)) ; at end of buffer
9b4c5ecd
GM
262 (goto-char (point-min))
263 (forward-line 3)
c10902fb
RS
264 (decipher-mode))
265
266;;;###autoload
267(defun decipher-mode ()
268 "Major mode for decrypting monoalphabetic substitution ciphers.
269Lower-case letters enter plaintext.
270Upper-case letters are commands.
271
272The buffer is made read-only so that normal Emacs commands cannot
273modify it.
274
275The most useful commands are:
276\\<decipher-mode-map>
277\\[decipher-digram-list] Display a list of all digrams & their frequency
278\\[decipher-frequency-count] Display the frequency of each ciphertext letter
279\\[decipher-adjacency-list]\
280 Show adjacency list for current letter (lists letters appearing next to it)
281\\[decipher-make-checkpoint] Save the current cipher alphabet (checkpoint)
282\\[decipher-restore-checkpoint] Restore a saved cipher alphabet (checkpoint)"
283 (interactive)
284 (kill-all-local-variables)
285 (setq buffer-undo-list t ;Disable undo
286 indent-tabs-mode nil ;Do not use tab characters
287 major-mode 'decipher-mode
288 mode-name "Decipher")
289 (if decipher-force-uppercase
290 (setq case-fold-search nil)) ;Case is significant when searching
291 (use-local-map decipher-mode-map)
292 (set-syntax-table decipher-mode-syntax-table)
b64e4650
RS
293 (unless (= (point-min) (point-max))
294 (decipher-read-alphabet))
a378799a
KH
295 (set (make-local-variable 'font-lock-defaults)
296 '(decipher-font-lock-keywords t))
c10902fb 297 ;; Make the buffer writable when we exit Decipher mode:
c10902fb
RS
298 (add-hook 'change-major-mode-hook
299 (lambda () (setq buffer-read-only nil
300 buffer-undo-list nil))
301 nil t)
c83c9654 302 (run-mode-hooks 'decipher-mode-hook)
c10902fb
RS
303 (setq buffer-read-only t))
304(put 'decipher-mode 'mode-class 'special)
305
306;;--------------------------------------------------------------------
307;; Normal key handling:
308;;--------------------------------------------------------------------
309
310(defmacro decipher-last-command-char ()
311 ;; Return the char which ran this command (for compatibility with XEmacs)
312 (if (fboundp 'event-to-character)
313 '(event-to-character last-command-event)
314 'last-command-event))
315
316(defun decipher-keypress ()
317 "Enter a plaintext or ciphertext character."
318 (interactive)
319 (let ((decipher-function 'decipher-set-map)
320 buffer-read-only) ;Make buffer writable
321 (save-excursion
322 (or (save-excursion
323 (beginning-of-line)
324 (let ((first-char (following-char)))
325 (cond
326 ((= ?: first-char)
327 t)
328 ((= ?> first-char)
329 nil)
330 ((= ?\( first-char)
331 (setq decipher-function 'decipher-alphabet-keypress)
332 t)
333 ((= ?\) first-char)
334 (setq decipher-function 'decipher-alphabet-keypress)
335 nil)
336 (t
337 (error "Bad location")))))
338 (let (goal-column)
d5d1f5fd 339 (forward-line -1)))
c10902fb
RS
340 (let ((char-a (following-char))
341 (char-b (decipher-last-command-char)))
342 (or (and (not (= ?w (char-syntax char-a)))
121656e9 343 (= char-b ?\s)) ;Spacebar just advances on non-letters
c10902fb
RS
344 (funcall decipher-function char-a char-b)))))
345 (forward-char))
346
347(defun decipher-alphabet-keypress (a b)
348 ;; Handle keypresses in the alphabet lines.
349 ;; A is the character in the alphabet row (which starts with '(')
350 ;; B is the character pressed
351 (cond ((and (>= a ?A) (<= a ?Z))
352 ;; If A is uppercase, then it is in the ciphertext alphabet:
353 (decipher-set-map a b))
354 ((and (>= a ?a) (<= a ?z))
355 ;; If A is lowercase, then it is in the plaintext alphabet:
121656e9 356 (if (= b ?\s)
c10902fb 357 ;; We are clearing the association (if any):
121656e9
JB
358 (if (/= ?\s (setq b (cdr (assoc a decipher-alphabet))))
359 (decipher-set-map b ?\s))
c10902fb
RS
360 ;; Associate the plaintext char with the char pressed:
361 (decipher-set-map b a)))
362 (t
363 ;; If A is not a letter, that's a problem:
364 (error "Bad character"))))
365
366;;--------------------------------------------------------------------
367;; Undo:
368;;--------------------------------------------------------------------
369
370(defun decipher-undo ()
371 "Undo a change in Decipher mode."
372 (interactive)
373 ;; If we don't get all the way thru, make last-command indicate that
374 ;; for the following command.
375 (setq this-command t)
376 (or (eq major-mode 'decipher-mode)
377 (error "This buffer is not in Decipher mode"))
378 (or (eq last-command 'decipher-undo)
379 (setq decipher-pending-undo-list decipher-undo-list))
380 (or decipher-pending-undo-list
381 (error "No further undo information"))
382 (let ((undo-rec (pop decipher-pending-undo-list))
383 buffer-read-only ;Make buffer writable
384 redo-map redo-rec undo-map)
385 (or (consp (car undo-rec))
386 (setq undo-rec (list undo-rec)))
387 (while (setq undo-map (pop undo-rec))
388 (setq redo-map (decipher-get-undo (cdr undo-map) (car undo-map)))
389 (if redo-map
390 (setq redo-rec
391 (if (consp (car redo-map))
392 (append redo-map redo-rec)
393 (cons redo-map redo-rec))))
394 (decipher-set-map (cdr undo-map) (car undo-map) t))
395 (decipher-add-undo redo-rec))
396 (setq this-command 'decipher-undo)
397 (message "Undo!"))
398
399(defun decipher-add-undo (undo-rec)
400 "Add UNDO-REC to the undo list."
401 (if undo-rec
402 (progn
403 (push undo-rec decipher-undo-list)
a464a6c7 404 (cl-incf decipher-undo-list-size)
c10902fb
RS
405 (if (> decipher-undo-list-size decipher-undo-limit)
406 (let ((new-size (- decipher-undo-limit 100)))
407 ;; Truncate undo list to NEW-SIZE elements:
408 (setcdr (nthcdr (1- new-size) decipher-undo-list) nil)
409 (setq decipher-undo-list-size new-size))))))
410
93ce34bf 411(defun decipher-copy-cons (cons)
4f2c8fbb
RS
412 (if cons
413 (cons (car cons) (cdr cons))))
414
c10902fb
RS
415(defun decipher-get-undo (cipher-char plain-char)
416 ;; Return an undo record that will undo the result of
417 ;; (decipher-set-map CIPHER-CHAR PLAIN-CHAR)
4f2c8fbb 418 ;; We must copy the cons cell because the original cons cells will be
c10902fb 419 ;; modified using setcdr.
93ce34bf
RS
420 (let ((cipher-map (decipher-copy-cons (rassoc cipher-char decipher-alphabet)))
421 (plain-map (decipher-copy-cons (assoc plain-char decipher-alphabet))))
121656e9 422 (cond ((equal ?\s plain-char)
c10902fb
RS
423 cipher-map)
424 ((equal cipher-char (cdr plain-map))
425 nil) ;We aren't changing anything
121656e9
JB
426 ((equal ?\s (cdr plain-map))
427 (or cipher-map (cons ?\s cipher-char)))
c10902fb
RS
428 (cipher-map
429 (list plain-map cipher-map))
430 (t
431 plain-map))))
432
433;;--------------------------------------------------------------------
434;; Mapping ciphertext and plaintext:
435;;--------------------------------------------------------------------
436
437(defun decipher-set-map (cipher-char plain-char &optional no-undo)
438 ;; Associate a ciphertext letter with a plaintext letter
439 ;; CIPHER-CHAR must be an uppercase or lowercase letter
440 ;; PLAIN-CHAR must be a lowercase letter (or a space)
441 ;; NO-UNDO if non-nil means do not record undo information
442 ;; Any existing associations for CIPHER-CHAR or PLAIN-CHAR will be erased.
443 (setq cipher-char (upcase cipher-char))
444 (or (and (>= cipher-char ?A) (<= cipher-char ?Z))
445 (error "Bad character")) ;Cipher char must be uppercase letter
446 (or no-undo
447 (decipher-add-undo (decipher-get-undo cipher-char plain-char)))
448 (let ((cipher-string (char-to-string cipher-char))
449 (plain-string (char-to-string plain-char))
450 case-fold-search ;Case is significant
451 mapping bound)
452 (save-excursion
453 (goto-char (point-min))
454 (if (setq mapping (rassoc cipher-char decipher-alphabet))
455 (progn
121656e9 456 (setcdr mapping ?\s)
c10902fb
RS
457 (search-forward-regexp (concat "^([a-z]*"
458 (char-to-string (car mapping))))
121656e9 459 (decipher-insert ?\s)
c10902fb
RS
460 (beginning-of-line)))
461 (if (setq mapping (assoc plain-char decipher-alphabet))
462 (progn
121656e9
JB
463 (if (/= ?\s (cdr mapping))
464 (decipher-set-map (cdr mapping) ?\s t))
c10902fb
RS
465 (setcdr mapping cipher-char)
466 (search-forward-regexp (concat "^([a-z]*" plain-string))
40600c94 467 (decipher-insert cipher-char)
c10902fb
RS
468 (beginning-of-line)))
469 (search-forward-regexp (concat "^([a-z]+ [A-Z]*" cipher-string))
40600c94 470 (decipher-insert plain-char)
c10902fb
RS
471 (setq case-fold-search t ;Case is not significant
472 cipher-string (downcase cipher-string))
40600c94
RS
473 (let ((font-lock-fontify-region-function 'ignore))
474 ;; insert-and-inherit will pick the right face automatically
475 (while (search-forward-regexp "^:" nil t)
e180ab9f 476 (setq bound (point-at-eol))
40600c94
RS
477 (while (search-forward cipher-string bound 'end)
478 (decipher-insert plain-char)))))))
c10902fb
RS
479
480(defun decipher-insert (char)
481 ;; Insert CHAR in the row below point. It replaces any existing
482 ;; character in that position.
483 (let ((col (1- (current-column))))
484 (save-excursion
485 (forward-line)
486 (or (= ?\> (following-char))
487 (= ?\) (following-char))
488 (error "Bad location"))
489 (move-to-column col t)
490 (or (eolp)
491 (delete-char 1))
a378799a 492 (insert-and-inherit char))))
c10902fb
RS
493
494;;--------------------------------------------------------------------
495;; Checkpoints:
496;;--------------------------------------------------------------------
497;; A checkpoint is a comment of the form:
498;; %!ABCDEFGHIJKLMNOPQRSTUVWXYZ! Description
499;; Such comments are usually placed at the end of the buffer following
500;; this header (which is inserted by decipher-make-checkpoint):
501;; %---------------------------
502;; % Checkpoints:
503;; % abcdefghijklmnopqrstuvwxyz
504;; but this is not required; checkpoints can be placed anywhere.
505;;
506;; The description is optional; all that is required is the alphabet.
507
508(defun decipher-make-checkpoint (desc)
509 "Checkpoint the current cipher alphabet.
510This records the current alphabet so you can return to it later.
511You may have any number of checkpoints.
512Type `\\[decipher-restore-checkpoint]' to restore a checkpoint."
513 (interactive "sCheckpoint description: ")
514 (or (stringp desc)
515 (setq desc ""))
516 (let (alphabet
121656e9 517 buffer-read-only) ;Make buffer writable
c10902fb
RS
518 (goto-char (point-min))
519 (re-search-forward "^)")
520 (move-to-column 27 t)
521 (setq alphabet (buffer-substring-no-properties (- (point) 26) (point)))
522 (if (re-search-forward "^%![A-Z ]+!" nil 'end)
523 nil ; Add new checkpoint with others
524 (if (re-search-backward "^% *Local Variables:" nil t)
525 ;; Add checkpoints before local variables list:
526 (progn (forward-line -1)
527 (or (looking-at "^ *$")
528 (progn (forward-line) (insert ?\n) (forward-line -1)))))
529 (insert "\n%" (make-string 69 ?\-)
530 "\n% Checkpoints:\n% abcdefghijklmnopqrstuvwxyz\n"))
531 (beginning-of-line)
40600c94 532 (insert "%!" alphabet "! " desc ?\n)))
c10902fb
RS
533
534(defun decipher-restore-checkpoint ()
535 "Restore the cipher alphabet from a checkpoint.
536If point is not on a checkpoint line, moves to the first checkpoint line.
537If point is on a checkpoint, restores that checkpoint.
538
539Type `\\[decipher-make-checkpoint]' to make a checkpoint."
540 (interactive)
541 (beginning-of-line)
542 (if (looking-at "%!\\([A-Z ]+\\)!")
543 ;; Restore this checkpoint:
544 (let ((alphabet (match-string 1))
545 buffer-read-only) ;Make buffer writable
546 (goto-char (point-min))
547 (re-search-forward "^)")
548 (or (eolp)
549 (delete-region (point) (progn (end-of-line) (point))))
550 (insert alphabet)
551 (decipher-resync))
552 ;; Move to the first checkpoint:
553 (goto-char (point-min))
554 (if (re-search-forward "^%![A-Z ]+!" nil t)
555 (message "Select the checkpoint to restore and type `%s'"
556 (substitute-command-keys "\\[decipher-restore-checkpoint]"))
557 (error "No checkpoints in this buffer"))))
558
559;;--------------------------------------------------------------------
560;; Miscellaneous commands:
561;;--------------------------------------------------------------------
562
563(defun decipher-complete-alphabet ()
564 "Complete the cipher alphabet.
565This fills any blanks in the cipher alphabet with the unused letters
566in alphabetical order. Use this when you have a keyword cipher and
567you have determined the keyword."
568 (interactive)
569 (let ((cipher-char ?A)
570 (ptr decipher-alphabet)
571 buffer-read-only ;Make buffer writable
572 plain-map undo-rec)
573 (while (setq plain-map (pop ptr))
121656e9 574 (if (equal ?\s (cdr plain-map))
c10902fb
RS
575 (progn
576 (while (rassoc cipher-char decipher-alphabet)
577 ;; Find the next unused letter
a464a6c7 578 (cl-incf cipher-char))
121656e9 579 (push (cons ?\s cipher-char) undo-rec)
c10902fb
RS
580 (decipher-set-map cipher-char (car plain-map) t))))
581 (decipher-add-undo undo-rec)))
582
583(defun decipher-show-alphabet ()
584 "Display the current cipher alphabet in the message line."
585 (interactive)
8c307e0f 586 (message "%s"
c10902fb
RS
587 (mapconcat (lambda (a)
588 (concat
589 (char-to-string (car a))
590 (char-to-string (cdr a))))
591 decipher-alphabet
592 "")))
593
594(defun decipher-resync ()
595 "Reprocess the buffer using the alphabet from the top.
596This regenerates all deciphered plaintext and clears the undo list.
597You should use this if you edit the ciphertext."
598 (interactive)
599 (message "Reprocessing buffer...")
600 (let (alphabet
601 buffer-read-only ;Make buffer writable
602 mapping)
603 (save-excursion
604 (decipher-read-alphabet)
605 (setq alphabet decipher-alphabet)
606 (goto-char (point-min))
40600c94 607 (and (re-search-forward "^).+" nil t)
c10902fb 608 (replace-match ")" nil nil))
40600c94 609 (while (re-search-forward "^>.+" nil t)
c10902fb
RS
610 (replace-match ">" nil nil))
611 (decipher-read-alphabet)
612 (while (setq mapping (pop alphabet))
121656e9 613 (or (equal ?\s (cdr mapping))
c10902fb
RS
614 (decipher-set-map (cdr mapping) (car mapping))))))
615 (setq decipher-undo-list nil
616 decipher-undo-list-size 0)
617 (message "Reprocessing buffer...done"))
618
619;;--------------------------------------------------------------------
620;; Miscellaneous functions:
621;;--------------------------------------------------------------------
622
623(defun decipher-read-alphabet ()
624 "Build the decipher-alphabet from the alphabet line in the buffer."
625 (save-excursion
626 (goto-char (point-min))
627 (search-forward-regexp "^)")
628 (move-to-column 27 t)
629 (setq decipher-alphabet nil)
630 (let ((plain-char ?z))
631 (while (>= plain-char ?a)
632 (backward-char)
633 (push (cons plain-char (following-char)) decipher-alphabet)
a464a6c7 634 (cl-decf plain-char)))))
c10902fb
RS
635
636;;;===================================================================
637;;; Analyzing ciphertext:
638;;;===================================================================
639
640(defun decipher-frequency-count ()
641 "Display the frequency count in the statistics buffer."
642 (interactive)
643 (decipher-analyze)
644 (decipher-display-regexp "^A" "^[A-Z][A-Z]"))
645
646(defun decipher-digram-list ()
647 "Display the list of digrams in the statistics buffer."
648 (interactive)
649 (decipher-analyze)
650 (decipher-display-regexp "[A-Z][A-Z] +[0-9]" "^$"))
651
652(defun decipher-adjacency-list (cipher-char)
653 "Display the adjacency list for the letter at point.
654The adjacency list shows all letters which come next to CIPHER-CHAR.
655
656An adjacency list (for the letter X) looks like this:
657 1 1 1 1 1 3 2 1 3 8
658X: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z * 11 14 9%
659 1 1 1 2 1 1 2 5 7
660This says that X comes before D once, and after B once. X begins 5
661words, and ends 3 words (`*' represents a space). X comes before 8
4c36be58 662different letters, after 7 different letters, and is next to a total
c10902fb
RS
663of 11 different letters. It occurs 14 times, making up 9% of the
664ciphertext."
665 (interactive (list (upcase (following-char))))
666 (decipher-analyze)
667 (let (start end)
937e6a56 668 (with-current-buffer (decipher-stats-buffer)
c10902fb
RS
669 (goto-char (point-min))
670 (or (re-search-forward (format "^%c: " cipher-char) nil t)
6e44da43 671 (error "Character `%c' is not used in ciphertext" cipher-char))
c10902fb
RS
672 (forward-line -1)
673 (setq start (point))
674 (forward-line 3)
675 (setq end (point)))
676 (decipher-display-range start end)))
677
678;;--------------------------------------------------------------------
679(defun decipher-analyze ()
680 "Perform frequency analysis on the current buffer if necessary."
681 (cond
682 ;; If this is the statistics buffer, do nothing:
683 ((eq major-mode 'decipher-stats-mode))
684 ;; If this is the Decipher buffer, see if the stats buffer exists:
685 ((eq major-mode 'decipher-mode)
686 (or (and (bufferp decipher-stats-buffer)
687 (buffer-name decipher-stats-buffer))
688 (decipher-analyze-buffer)))
689 ;; Otherwise:
690 (t (error "This buffer is not in Decipher mode"))))
691
692;;--------------------------------------------------------------------
693(defun decipher-display-range (start end)
694 "Display text between START and END in the statistics buffer.
695START and END are positions in the statistics buffer. Makes the
696statistics buffer visible and sizes the window to just fit the
697displayed text, but leaves the current window selected."
698 (let ((stats-buffer (decipher-stats-buffer))
699 (current-window (selected-window))
700 (pop-up-windows t))
701 (or (eq (current-buffer) stats-buffer)
702 (pop-to-buffer stats-buffer))
703 (goto-char start)
704 (or (one-window-p t)
705 (enlarge-window (- (1+ (count-lines start end)) (window-height))))
706 (recenter 0)
707 (select-window current-window)))
708
709(defun decipher-display-regexp (start-regexp end-regexp)
710 "Display text between two regexps in the statistics buffer.
711
712START-REGEXP matches the first line to display.
713END-REGEXP matches the line after that which ends the display.
714The ending line is included in the display unless it is blank."
715 (let (start end)
937e6a56 716 (with-current-buffer (decipher-stats-buffer)
c10902fb
RS
717 (goto-char (point-min))
718 (re-search-forward start-regexp)
719 (beginning-of-line)
720 (setq start (point))
721 (re-search-forward end-regexp)
722 (beginning-of-line)
723 (or (looking-at "^ *$")
724 (forward-line 1))
725 (setq end (point)))
726 (decipher-display-range start end)))
727
728;;--------------------------------------------------------------------
729(defun decipher-loop-with-breaks (func)
730 "Loop through ciphertext, calling FUNC once for each letter & word division.
731
732FUNC is called with no arguments, and its return value is unimportant.
733It may examine `decipher-char' to see the current ciphertext
734character. `decipher-char' contains either an uppercase letter or a space.
735
736FUNC is called exactly once between words, with `decipher-char' set to
737a space.
738
739See `decipher-loop-no-breaks' if you do not care about word divisions."
121656e9
JB
740 (let ((decipher-char ?\s)
741 (decipher--loop-prev-char ?\s))
c10902fb
RS
742 (save-excursion
743 (goto-char (point-min))
744 (funcall func) ;Space marks beginning of first word
745 (while (search-forward-regexp "^:" nil t)
746 (while (not (eolp))
747 (setq decipher-char (upcase (following-char)))
748 (or (and (>= decipher-char ?A) (<= decipher-char ?Z))
121656e9
JB
749 (setq decipher-char ?\s))
750 (or (and (equal decipher-char ?\s)
751 (equal decipher--loop-prev-char ?\s))
c10902fb
RS
752 (funcall func))
753 (setq decipher--loop-prev-char decipher-char)
754 (forward-char))
121656e9 755 (or (equal decipher-char ?\s)
c10902fb 756 (progn
e0b3c2b9 757 (setq decipher-char ?\s
121656e9 758 decipher--loop-prev-char ?\s)
c10902fb
RS
759 (funcall func)))))))
760
761(defun decipher-loop-no-breaks (func)
762 "Loop through ciphertext, calling FUNC once for each letter.
763
764FUNC is called with no arguments, and its return value is unimportant.
765It may examine `decipher-char' to see the current ciphertext letter.
766`decipher-char' contains an uppercase letter.
767
768Punctuation and spacing in the ciphertext are ignored.
769See `decipher-loop-with-breaks' if you care about word divisions."
770 (let (decipher-char)
771 (save-excursion
772 (goto-char (point-min))
773 (while (search-forward-regexp "^:" nil t)
774 (while (not (eolp))
775 (setq decipher-char (upcase (following-char)))
776 (and (>= decipher-char ?A)
777 (<= decipher-char ?Z)
778 (funcall func))
779 (forward-char))))))
780
781;;--------------------------------------------------------------------
782;; Perform the analysis:
783;;--------------------------------------------------------------------
784
785(defun decipher-insert-frequency-counts (freq-list total)
786 "Insert frequency counts in current buffer.
787Each element of FREQ-LIST is a list (LETTER FREQ ...).
788TOTAL is the total number of letters in the ciphertext."
789 (let ((i 4) temp-list)
790 (while (> i 0)
791 (setq temp-list freq-list)
792 (while temp-list
793 (insert (caar temp-list)
794 (format "%4d%3d%% "
a464a6c7
SM
795 (cl-cadar temp-list)
796 (/ (* 100 (cl-cadar temp-list)) total)))
c10902fb
RS
797 (setq temp-list (nthcdr 4 temp-list)))
798 (insert ?\n)
799 (setq freq-list (cdr freq-list)
800 i (1- i)))))
801
802(defun decipher--analyze ()
803 ;; Perform frequency analysis on ciphertext.
804 ;;
805 ;; This function is called repeatedly with decipher-char set to each
ddfb0a34 806 ;; character of ciphertext. It uses decipher--prev-char to remember
c10902fb
RS
807 ;; the previous ciphertext character.
808 ;;
809 ;; It builds several data structures, which must be initialized
810 ;; before the first call to decipher--analyze. The arrays are
811 ;; indexed with A = 0, B = 1, ..., Z = 25, SPC = 26 (if used).
ddfb0a34 812 ;; decipher--after: (initialize to zeros)
c10902fb
RS
813 ;; A vector of 26 vectors of 27 integers. The first vector
814 ;; represents the number of times A follows each character, the
815 ;; second vector represents B, and so on.
ddfb0a34
KH
816 ;; decipher--before: (initialize to zeros)
817 ;; The same as decipher--after, but representing the number of
818 ;; times the character precedes each other character.
819 ;; decipher--digram-list: (initialize to nil)
c10902fb
RS
820 ;; An alist with an entry for each digram (2-character sequence)
821 ;; encountered. Each element is a cons cell (DIGRAM . FREQ),
822 ;; where DIGRAM is a 2 character string and FREQ is the number
823 ;; of times it occurs.
ddfb0a34 824 ;; decipher--freqs: (initialize to zeros)
c10902fb
RS
825 ;; A vector of 26 integers, counting the number of occurrences
826 ;; of the corresponding characters.
ddfb0a34 827 (setq decipher--digram (format "%c%c" decipher--prev-char decipher-char))
a464a6c7 828 (cl-incf (cdr (or (assoc decipher--digram decipher--digram-list)
ddfb0a34
KH
829 (car (push (cons decipher--digram 0)
830 decipher--digram-list)))))
831 (and (>= decipher--prev-char ?A)
a464a6c7 832 (cl-incf (aref (aref decipher--before (- decipher--prev-char ?A))
121656e9 833 (if (equal decipher-char ?\s)
c10902fb
RS
834 26
835 (- decipher-char ?A)))))
836 (and (>= decipher-char ?A)
a464a6c7
SM
837 (cl-incf (aref decipher--freqs (- decipher-char ?A)))
838 (cl-incf (aref (aref decipher--after (- decipher-char ?A))
121656e9 839 (if (equal decipher--prev-char ?\s)
c10902fb 840 26
ddfb0a34
KH
841 (- decipher--prev-char ?A)))))
842 (setq decipher--prev-char decipher-char))
c10902fb
RS
843
844(defun decipher--digram-counts (counts)
845 "Generate the counts for an adjacency list."
846 (let ((total 0))
847 (concat
848 (mapconcat (lambda (x)
a464a6c7
SM
849 (cond ((> x 99) (cl-incf total) "XX")
850 ((> x 0) (cl-incf total) (format "%2d" x))
c10902fb
RS
851 (t " ")))
852 counts
853 "")
854 (format "%4d" (if (> (aref counts 26) 0)
855 (1- total) ;Don't count space
856 total)))))
857
858(defun decipher--digram-total (before-count after-count)
859 "Count the number of different letters a letter appears next to."
860 ;; We do not include spaces (word divisions) in this count.
861 (let ((total 0)
862 (i 26))
a464a6c7 863 (while (>= (cl-decf i) 0)
c10902fb
RS
864 (if (or (> (aref before-count i) 0)
865 (> (aref after-count i) 0))
a464a6c7 866 (cl-incf total)))
c10902fb
RS
867 total))
868
869(defun decipher-analyze-buffer ()
870 "Perform frequency analysis and store results in statistics buffer.
871Creates the statistics buffer if it doesn't exist."
121656e9 872 (let ((decipher--prev-char (if decipher-ignore-spaces ?\s ?\*))
ddfb0a34
KH
873 (decipher--before (make-vector 26 nil))
874 (decipher--after (make-vector 26 nil))
875 (decipher--freqs (make-vector 26 0))
c10902fb 876 (total-chars 0)
ddfb0a34 877 decipher--digram decipher--digram-list freq-list)
c10902fb
RS
878 (message "Scanning buffer...")
879 (let ((i 26))
a464a6c7 880 (while (>= (cl-decf i) 0)
ddfb0a34
KH
881 (aset decipher--before i (make-vector 27 0))
882 (aset decipher--after i (make-vector 27 0))))
c10902fb
RS
883 (if decipher-ignore-spaces
884 (progn
885 (decipher-loop-no-breaks 'decipher--analyze)
886 ;; The first character of ciphertext was marked as following a space:
887 (let ((i 26))
a464a6c7 888 (while (>= (cl-decf i) 0)
ddfb0a34 889 (aset (aref decipher--after i) 26 0))))
c10902fb
RS
890 (decipher-loop-with-breaks 'decipher--analyze))
891 (message "Processing results...")
ddfb0a34 892 (setcdr (last decipher--digram-list 2) nil) ;Delete the phony "* " digram
c10902fb 893 ;; Sort the digram list by frequency and alphabetical order:
ddfb0a34 894 (setq decipher--digram-list (sort (sort decipher--digram-list
c10902fb
RS
895 (lambda (a b) (string< (car a) (car b))))
896 (lambda (a b) (> (cdr a) (cdr b)))))
897 ;; Generate the frequency list:
898 ;; Each element is a list of 3 elements (LETTER FREQ DIFFERENT),
899 ;; where LETTER is the ciphertext character, FREQ is the number
900 ;; of times it occurs, and DIFFERENT is the number of different
901 ;; letters it appears next to.
902 (let ((i 26))
a464a6c7 903 (while (>= (cl-decf i) 0)
c10902fb
RS
904 (setq freq-list
905 (cons (list (+ i ?A)
ddfb0a34
KH
906 (aref decipher--freqs i)
907 (decipher--digram-total (aref decipher--before i)
908 (aref decipher--after i)))
c10902fb 909 freq-list)
ddfb0a34 910 total-chars (+ total-chars (aref decipher--freqs i)))))
937e6a56
SM
911 ;; Switch to statistics buffer, creating it if necessary:
912 (with-current-buffer (decipher-stats-buffer t)
c10902fb
RS
913 ;; This can't happen, but it never hurts to double-check:
914 (or (eq major-mode 'decipher-stats-mode)
915 (error "Buffer %s is not in Decipher-Stats mode" (buffer-name)))
916 (setq buffer-read-only nil)
917 (erase-buffer)
918 ;; Display frequency counts for letters A-Z:
919 (decipher-insert-frequency-counts freq-list total-chars)
920 (insert ?\n)
921 ;; Display frequency counts for letters in order of frequency:
922 (setq freq-list (sort freq-list
a464a6c7 923 (lambda (a b) (> (cl-second a) (cl-second b)))))
c10902fb
RS
924 (decipher-insert-frequency-counts freq-list total-chars)
925 ;; Display letters in order of frequency:
926 (insert ?\n (mapconcat (lambda (a) (char-to-string (car a)))
927 freq-list nil)
928 "\n\n")
929 ;; Display list of digrams in order of frequency:
ddfb0a34 930 (let* ((rows (floor (+ (length decipher--digram-list) 9) 10))
c10902fb
RS
931 (i rows)
932 temp-list)
933 (while (> i 0)
ddfb0a34 934 (setq temp-list decipher--digram-list)
c10902fb
RS
935 (while temp-list
936 (insert (caar temp-list)
937 (format "%3d "
938 (cdar temp-list)))
939 (setq temp-list (nthcdr rows temp-list)))
940 (delete-horizontal-space)
941 (insert ?\n)
ddfb0a34 942 (setq decipher--digram-list (cdr decipher--digram-list)
c10902fb
RS
943 i (1- i))))
944 ;; Display adjacency list for each letter, sorted in descending
945 ;; order of the number of adjacent letters:
946 (setq freq-list (sort freq-list
a464a6c7 947 (lambda (a b) (> (cl-third a) (cl-third b)))))
c10902fb
RS
948 (let ((temp-list freq-list)
949 entry i)
950 (while (setq entry (pop temp-list))
a464a6c7 951 (if (equal 0 (cl-second entry))
c10902fb
RS
952 nil ;This letter was not used
953 (setq i (- (car entry) ?A))
954 (insert ?\n " "
ddfb0a34 955 (decipher--digram-counts (aref decipher--before i)) ?\n
c10902fb
RS
956 (car entry)
957 ": A B C D E F G H I J K L M N O P Q R S T U V W X Y Z *"
958 (format "%4d %4d %3d%%\n "
a464a6c7
SM
959 (cl-third entry) (cl-second entry)
960 (/ (* 100 (cl-second entry)) total-chars))
ddfb0a34 961 (decipher--digram-counts (aref decipher--after i)) ?\n))))
c10902fb
RS
962 (setq buffer-read-only t)
963 (set-buffer-modified-p nil)
964 ))
965 (message nil))
966
967;;====================================================================
968;; Statistics Buffer:
969;;====================================================================
970
971(defun decipher-stats-mode ()
972 "Major mode for displaying ciphertext statistics."
973 (interactive)
974 (kill-all-local-variables)
975 (setq buffer-read-only t
976 buffer-undo-list t ;Disable undo
977 case-fold-search nil ;Case is significant when searching
978 indent-tabs-mode nil ;Do not use tab characters
979 major-mode 'decipher-stats-mode
980 mode-name "Decipher-Stats")
981 (use-local-map decipher-stats-mode-map)
c83c9654 982 (run-mode-hooks 'decipher-stats-mode-hook))
c10902fb
RS
983(put 'decipher-stats-mode 'mode-class 'special)
984
985;;--------------------------------------------------------------------
986
987(defun decipher-display-stats-buffer ()
988 "Make the statistics buffer visible, but do not select it."
989 (let ((stats-buffer (decipher-stats-buffer))
990 (current-window (selected-window)))
991 (or (eq (current-buffer) stats-buffer)
992 (progn
993 (pop-to-buffer stats-buffer)
994 (select-window current-window)))))
995
996(defun decipher-stats-buffer (&optional create)
997 "Return the buffer used for decipher statistics.
998If CREATE is non-nil, create the buffer if it doesn't exist.
999This is guaranteed to return a buffer in Decipher-Stats mode;
1000if it can't, it signals an error."
1001 (cond
1002 ;; We may already be in the statistics buffer:
1003 ((eq major-mode 'decipher-stats-mode)
1004 (current-buffer))
1005 ;; See if decipher-stats-buffer exists:
1006 ((and (bufferp decipher-stats-buffer)
1007 (buffer-name decipher-stats-buffer))
937e6a56 1008 (or (with-current-buffer decipher-stats-buffer
c10902fb
RS
1009 (eq major-mode 'decipher-stats-mode))
1010 (error "Buffer %s is not in Decipher-Stats mode"
1011 (buffer-name decipher-stats-buffer)))
1012 decipher-stats-buffer)
1013 ;; Create a new buffer if requested:
1014 (create
1015 (let ((stats-name (concat "*" (buffer-name) "*")))
1016 (setq decipher-stats-buffer
1017 (if (eq 'decipher-stats-mode
1018 (cdr-safe (assoc 'major-mode
1019 (buffer-local-variables
1020 (get-buffer stats-name)))))
1021 ;; We just lost track of the statistics buffer:
1022 (get-buffer stats-name)
1023 (generate-new-buffer stats-name))))
937e6a56 1024 (with-current-buffer decipher-stats-buffer
c10902fb
RS
1025 (decipher-stats-mode))
1026 decipher-stats-buffer)
1027 ;; Give up:
1028 (t (error "No statistics buffer"))))
1029
1030;;====================================================================
1031
1032(provide 'decipher)
1033
937e6a56
SM
1034;;(defun decipher-show-undo-list ()
1035;; "Display the undo list (for debugging purposes)."
1036;; (interactive)
1037;; (with-output-to-temp-buffer "*Decipher Undo*"
1038;; (let ((undo-list decipher-undo-list)
1039;; undo-rec undo-map)
1040;; (with-current-buffer "*Decipher Undo*"
1041;; (while (setq undo-rec (pop undo-list))
1042;; (or (consp (car undo-rec))
1043;; (setq undo-rec (list undo-rec)))
1044;; (insert ?\()
1045;; (while (setq undo-map (pop undo-rec))
121656e9 1046;; (insert (cdr undo-map) (car undo-map) ?\s))
d355a0b7 1047;; (delete-char -1)
937e6a56 1048;; (insert ")\n"))))))
c10902fb
RS
1049
1050;;; decipher.el ends here