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