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