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