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