]> code.delx.au - gnu-emacs/blob - lisp/play/decipher.el
Convert consecutive FSF copyright years to ranges.
[gnu-emacs] / lisp / play / decipher.el
1 ;;; decipher.el --- cryptanalyze monoalphabetic substitution ciphers
2 ;;
3 ;; Copyright (C) 1995-1996, 2001-2011 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 ?\ )) ;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 ?\ )
370 ;; We are clearing the association (if any):
371 (if (/= ?\ (setq b (cdr (assoc a decipher-alphabet))))
372 (decipher-set-map b ?\ ))
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 ?\ plain-char)
436 cipher-map)
437 ((equal cipher-char (cdr plain-map))
438 nil) ;We aren't changing anything
439 ((equal ?\ (cdr plain-map))
440 (or cipher-map (cons ?\ 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 ?\ )
470 (search-forward-regexp (concat "^([a-z]*"
471 (char-to-string (car mapping))))
472 (decipher-insert ?\ )
473 (beginning-of-line)))
474 (if (setq mapping (assoc plain-char decipher-alphabet))
475 (progn
476 (if (/= ?\ (cdr mapping))
477 (decipher-set-map (cdr mapping) ?\ 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 mapping)
532 (goto-char (point-min))
533 (re-search-forward "^)")
534 (move-to-column 27 t)
535 (setq alphabet (buffer-substring-no-properties (- (point) 26) (point)))
536 (if (re-search-forward "^%![A-Z ]+!" nil 'end)
537 nil ; Add new checkpoint with others
538 (if (re-search-backward "^% *Local Variables:" nil t)
539 ;; Add checkpoints before local variables list:
540 (progn (forward-line -1)
541 (or (looking-at "^ *$")
542 (progn (forward-line) (insert ?\n) (forward-line -1)))))
543 (insert "\n%" (make-string 69 ?\-)
544 "\n% Checkpoints:\n% abcdefghijklmnopqrstuvwxyz\n"))
545 (beginning-of-line)
546 (insert "%!" alphabet "! " desc ?\n)))
547
548 (defun decipher-restore-checkpoint ()
549 "Restore the cipher alphabet from a checkpoint.
550 If point is not on a checkpoint line, moves to the first checkpoint line.
551 If point is on a checkpoint, restores that checkpoint.
552
553 Type `\\[decipher-make-checkpoint]' to make a checkpoint."
554 (interactive)
555 (beginning-of-line)
556 (if (looking-at "%!\\([A-Z ]+\\)!")
557 ;; Restore this checkpoint:
558 (let ((alphabet (match-string 1))
559 buffer-read-only) ;Make buffer writable
560 (goto-char (point-min))
561 (re-search-forward "^)")
562 (or (eolp)
563 (delete-region (point) (progn (end-of-line) (point))))
564 (insert alphabet)
565 (decipher-resync))
566 ;; Move to the first checkpoint:
567 (goto-char (point-min))
568 (if (re-search-forward "^%![A-Z ]+!" nil t)
569 (message "Select the checkpoint to restore and type `%s'"
570 (substitute-command-keys "\\[decipher-restore-checkpoint]"))
571 (error "No checkpoints in this buffer"))))
572
573 ;;--------------------------------------------------------------------
574 ;; Miscellaneous commands:
575 ;;--------------------------------------------------------------------
576
577 (defun decipher-complete-alphabet ()
578 "Complete the cipher alphabet.
579 This fills any blanks in the cipher alphabet with the unused letters
580 in alphabetical order. Use this when you have a keyword cipher and
581 you have determined the keyword."
582 (interactive)
583 (let ((cipher-char ?A)
584 (ptr decipher-alphabet)
585 buffer-read-only ;Make buffer writable
586 plain-map undo-rec)
587 (while (setq plain-map (pop ptr))
588 (if (equal ?\ (cdr plain-map))
589 (progn
590 (while (rassoc cipher-char decipher-alphabet)
591 ;; Find the next unused letter
592 (incf cipher-char))
593 (push (cons ?\ cipher-char) undo-rec)
594 (decipher-set-map cipher-char (car plain-map) t))))
595 (decipher-add-undo undo-rec)))
596
597 (defun decipher-show-alphabet ()
598 "Display the current cipher alphabet in the message line."
599 (interactive)
600 (message "%s"
601 (mapconcat (lambda (a)
602 (concat
603 (char-to-string (car a))
604 (char-to-string (cdr a))))
605 decipher-alphabet
606 "")))
607
608 (defun decipher-resync ()
609 "Reprocess the buffer using the alphabet from the top.
610 This regenerates all deciphered plaintext and clears the undo list.
611 You should use this if you edit the ciphertext."
612 (interactive)
613 (message "Reprocessing buffer...")
614 (let (alphabet
615 buffer-read-only ;Make buffer writable
616 mapping)
617 (save-excursion
618 (decipher-read-alphabet)
619 (setq alphabet decipher-alphabet)
620 (goto-char (point-min))
621 (and (re-search-forward "^).+" nil t)
622 (replace-match ")" nil nil))
623 (while (re-search-forward "^>.+" nil t)
624 (replace-match ">" nil nil))
625 (decipher-read-alphabet)
626 (while (setq mapping (pop alphabet))
627 (or (equal ?\ (cdr mapping))
628 (decipher-set-map (cdr mapping) (car mapping))))))
629 (setq decipher-undo-list nil
630 decipher-undo-list-size 0)
631 (message "Reprocessing buffer...done"))
632
633 ;;--------------------------------------------------------------------
634 ;; Miscellaneous functions:
635 ;;--------------------------------------------------------------------
636
637 (defun decipher-read-alphabet ()
638 "Build the decipher-alphabet from the alphabet line in the buffer."
639 (save-excursion
640 (goto-char (point-min))
641 (search-forward-regexp "^)")
642 (move-to-column 27 t)
643 (setq decipher-alphabet nil)
644 (let ((plain-char ?z))
645 (while (>= plain-char ?a)
646 (backward-char)
647 (push (cons plain-char (following-char)) decipher-alphabet)
648 (decf plain-char)))))
649
650 ;;;===================================================================
651 ;;; Analyzing ciphertext:
652 ;;;===================================================================
653
654 (defun decipher-frequency-count ()
655 "Display the frequency count in the statistics buffer."
656 (interactive)
657 (decipher-analyze)
658 (decipher-display-regexp "^A" "^[A-Z][A-Z]"))
659
660 (defun decipher-digram-list ()
661 "Display the list of digrams in the statistics buffer."
662 (interactive)
663 (decipher-analyze)
664 (decipher-display-regexp "[A-Z][A-Z] +[0-9]" "^$"))
665
666 (defun decipher-adjacency-list (cipher-char)
667 "Display the adjacency list for the letter at point.
668 The adjacency list shows all letters which come next to CIPHER-CHAR.
669
670 An adjacency list (for the letter X) looks like this:
671 1 1 1 1 1 3 2 1 3 8
672 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%
673 1 1 1 2 1 1 2 5 7
674 This says that X comes before D once, and after B once. X begins 5
675 words, and ends 3 words (`*' represents a space). X comes before 8
676 different letters, after 7 differerent letters, and is next to a total
677 of 11 different letters. It occurs 14 times, making up 9% of the
678 ciphertext."
679 (interactive (list (upcase (following-char))))
680 (decipher-analyze)
681 (let (start end)
682 (with-current-buffer (decipher-stats-buffer)
683 (goto-char (point-min))
684 (or (re-search-forward (format "^%c: " cipher-char) nil t)
685 (error "Character `%c' is not used in ciphertext" cipher-char))
686 (forward-line -1)
687 (setq start (point))
688 (forward-line 3)
689 (setq end (point)))
690 (decipher-display-range start end)))
691
692 ;;--------------------------------------------------------------------
693 (defun decipher-analyze ()
694 "Perform frequency analysis on the current buffer if necessary."
695 (cond
696 ;; If this is the statistics buffer, do nothing:
697 ((eq major-mode 'decipher-stats-mode))
698 ;; If this is the Decipher buffer, see if the stats buffer exists:
699 ((eq major-mode 'decipher-mode)
700 (or (and (bufferp decipher-stats-buffer)
701 (buffer-name decipher-stats-buffer))
702 (decipher-analyze-buffer)))
703 ;; Otherwise:
704 (t (error "This buffer is not in Decipher mode"))))
705
706 ;;--------------------------------------------------------------------
707 (defun decipher-display-range (start end)
708 "Display text between START and END in the statistics buffer.
709 START and END are positions in the statistics buffer. Makes the
710 statistics buffer visible and sizes the window to just fit the
711 displayed text, but leaves the current window selected."
712 (let ((stats-buffer (decipher-stats-buffer))
713 (current-window (selected-window))
714 (pop-up-windows t))
715 (or (eq (current-buffer) stats-buffer)
716 (pop-to-buffer stats-buffer))
717 (goto-char start)
718 (or (one-window-p t)
719 (enlarge-window (- (1+ (count-lines start end)) (window-height))))
720 (recenter 0)
721 (select-window current-window)))
722
723 (defun decipher-display-regexp (start-regexp end-regexp)
724 "Display text between two regexps in the statistics buffer.
725
726 START-REGEXP matches the first line to display.
727 END-REGEXP matches the line after that which ends the display.
728 The ending line is included in the display unless it is blank."
729 (let (start end)
730 (with-current-buffer (decipher-stats-buffer)
731 (goto-char (point-min))
732 (re-search-forward start-regexp)
733 (beginning-of-line)
734 (setq start (point))
735 (re-search-forward end-regexp)
736 (beginning-of-line)
737 (or (looking-at "^ *$")
738 (forward-line 1))
739 (setq end (point)))
740 (decipher-display-range start end)))
741
742 ;;--------------------------------------------------------------------
743 (defun decipher-loop-with-breaks (func)
744 "Loop through ciphertext, calling FUNC once for each letter & word division.
745
746 FUNC is called with no arguments, and its return value is unimportant.
747 It may examine `decipher-char' to see the current ciphertext
748 character. `decipher-char' contains either an uppercase letter or a space.
749
750 FUNC is called exactly once between words, with `decipher-char' set to
751 a space.
752
753 See `decipher-loop-no-breaks' if you do not care about word divisions."
754 (let ((decipher-char ?\ )
755 (decipher--loop-prev-char ?\ ))
756 (save-excursion
757 (goto-char (point-min))
758 (funcall func) ;Space marks beginning of first word
759 (while (search-forward-regexp "^:" nil t)
760 (while (not (eolp))
761 (setq decipher-char (upcase (following-char)))
762 (or (and (>= decipher-char ?A) (<= decipher-char ?Z))
763 (setq decipher-char ?\ ))
764 (or (and (equal decipher-char ?\ )
765 (equal decipher--loop-prev-char ?\ ))
766 (funcall func))
767 (setq decipher--loop-prev-char decipher-char)
768 (forward-char))
769 (or (equal decipher-char ?\ )
770 (progn
771 (setq decipher-char ?\s
772 decipher--loop-prev-char ?\ )
773 (funcall func)))))))
774
775 (defun decipher-loop-no-breaks (func)
776 "Loop through ciphertext, calling FUNC once for each letter.
777
778 FUNC is called with no arguments, and its return value is unimportant.
779 It may examine `decipher-char' to see the current ciphertext letter.
780 `decipher-char' contains an uppercase letter.
781
782 Punctuation and spacing in the ciphertext are ignored.
783 See `decipher-loop-with-breaks' if you care about word divisions."
784 (let (decipher-char)
785 (save-excursion
786 (goto-char (point-min))
787 (while (search-forward-regexp "^:" nil t)
788 (while (not (eolp))
789 (setq decipher-char (upcase (following-char)))
790 (and (>= decipher-char ?A)
791 (<= decipher-char ?Z)
792 (funcall func))
793 (forward-char))))))
794
795 ;;--------------------------------------------------------------------
796 ;; Perform the analysis:
797 ;;--------------------------------------------------------------------
798
799 (defun decipher-insert-frequency-counts (freq-list total)
800 "Insert frequency counts in current buffer.
801 Each element of FREQ-LIST is a list (LETTER FREQ ...).
802 TOTAL is the total number of letters in the ciphertext."
803 (let ((i 4) temp-list)
804 (while (> i 0)
805 (setq temp-list freq-list)
806 (while temp-list
807 (insert (caar temp-list)
808 (format "%4d%3d%% "
809 (cadar temp-list)
810 (/ (* 100 (cadar temp-list)) total)))
811 (setq temp-list (nthcdr 4 temp-list)))
812 (insert ?\n)
813 (setq freq-list (cdr freq-list)
814 i (1- i)))))
815
816 (defun decipher--analyze ()
817 ;; Perform frequency analysis on ciphertext.
818 ;;
819 ;; This function is called repeatedly with decipher-char set to each
820 ;; character of ciphertext. It uses decipher--prev-char to remember
821 ;; the previous ciphertext character.
822 ;;
823 ;; It builds several data structures, which must be initialized
824 ;; before the first call to decipher--analyze. The arrays are
825 ;; indexed with A = 0, B = 1, ..., Z = 25, SPC = 26 (if used).
826 ;; decipher--after: (initialize to zeros)
827 ;; A vector of 26 vectors of 27 integers. The first vector
828 ;; represents the number of times A follows each character, the
829 ;; second vector represents B, and so on.
830 ;; decipher--before: (initialize to zeros)
831 ;; The same as decipher--after, but representing the number of
832 ;; times the character precedes each other character.
833 ;; decipher--digram-list: (initialize to nil)
834 ;; An alist with an entry for each digram (2-character sequence)
835 ;; encountered. Each element is a cons cell (DIGRAM . FREQ),
836 ;; where DIGRAM is a 2 character string and FREQ is the number
837 ;; of times it occurs.
838 ;; decipher--freqs: (initialize to zeros)
839 ;; A vector of 26 integers, counting the number of occurrences
840 ;; of the corresponding characters.
841 (setq decipher--digram (format "%c%c" decipher--prev-char decipher-char))
842 (incf (cdr (or (assoc decipher--digram decipher--digram-list)
843 (car (push (cons decipher--digram 0)
844 decipher--digram-list)))))
845 (and (>= decipher--prev-char ?A)
846 (incf (aref (aref decipher--before (- decipher--prev-char ?A))
847 (if (equal decipher-char ?\ )
848 26
849 (- decipher-char ?A)))))
850 (and (>= decipher-char ?A)
851 (incf (aref decipher--freqs (- decipher-char ?A)))
852 (incf (aref (aref decipher--after (- decipher-char ?A))
853 (if (equal decipher--prev-char ?\ )
854 26
855 (- decipher--prev-char ?A)))))
856 (setq decipher--prev-char decipher-char))
857
858 (defun decipher--digram-counts (counts)
859 "Generate the counts for an adjacency list."
860 (let ((total 0))
861 (concat
862 (mapconcat (lambda (x)
863 (cond ((> x 99) (incf total) "XX")
864 ((> x 0) (incf total) (format "%2d" x))
865 (t " ")))
866 counts
867 "")
868 (format "%4d" (if (> (aref counts 26) 0)
869 (1- total) ;Don't count space
870 total)))))
871
872 (defun decipher--digram-total (before-count after-count)
873 "Count the number of different letters a letter appears next to."
874 ;; We do not include spaces (word divisions) in this count.
875 (let ((total 0)
876 (i 26))
877 (while (>= (decf i) 0)
878 (if (or (> (aref before-count i) 0)
879 (> (aref after-count i) 0))
880 (incf total)))
881 total))
882
883 (defun decipher-analyze-buffer ()
884 "Perform frequency analysis and store results in statistics buffer.
885 Creates the statistics buffer if it doesn't exist."
886 (let ((decipher--prev-char (if decipher-ignore-spaces ?\ ?\*))
887 (decipher--before (make-vector 26 nil))
888 (decipher--after (make-vector 26 nil))
889 (decipher--freqs (make-vector 26 0))
890 (total-chars 0)
891 decipher--digram decipher--digram-list freq-list)
892 (message "Scanning buffer...")
893 (let ((i 26))
894 (while (>= (decf i) 0)
895 (aset decipher--before i (make-vector 27 0))
896 (aset decipher--after i (make-vector 27 0))))
897 (if decipher-ignore-spaces
898 (progn
899 (decipher-loop-no-breaks 'decipher--analyze)
900 ;; The first character of ciphertext was marked as following a space:
901 (let ((i 26))
902 (while (>= (decf i) 0)
903 (aset (aref decipher--after i) 26 0))))
904 (decipher-loop-with-breaks 'decipher--analyze))
905 (message "Processing results...")
906 (setcdr (last decipher--digram-list 2) nil) ;Delete the phony "* " digram
907 ;; Sort the digram list by frequency and alphabetical order:
908 (setq decipher--digram-list (sort (sort decipher--digram-list
909 (lambda (a b) (string< (car a) (car b))))
910 (lambda (a b) (> (cdr a) (cdr b)))))
911 ;; Generate the frequency list:
912 ;; Each element is a list of 3 elements (LETTER FREQ DIFFERENT),
913 ;; where LETTER is the ciphertext character, FREQ is the number
914 ;; of times it occurs, and DIFFERENT is the number of different
915 ;; letters it appears next to.
916 (let ((i 26))
917 (while (>= (decf i) 0)
918 (setq freq-list
919 (cons (list (+ i ?A)
920 (aref decipher--freqs i)
921 (decipher--digram-total (aref decipher--before i)
922 (aref decipher--after i)))
923 freq-list)
924 total-chars (+ total-chars (aref decipher--freqs i)))))
925 ;; Switch to statistics buffer, creating it if necessary:
926 (with-current-buffer (decipher-stats-buffer t)
927 ;; This can't happen, but it never hurts to double-check:
928 (or (eq major-mode 'decipher-stats-mode)
929 (error "Buffer %s is not in Decipher-Stats mode" (buffer-name)))
930 (setq buffer-read-only nil)
931 (erase-buffer)
932 ;; Display frequency counts for letters A-Z:
933 (decipher-insert-frequency-counts freq-list total-chars)
934 (insert ?\n)
935 ;; Display frequency counts for letters in order of frequency:
936 (setq freq-list (sort freq-list
937 (lambda (a b) (> (second a) (second b)))))
938 (decipher-insert-frequency-counts freq-list total-chars)
939 ;; Display letters in order of frequency:
940 (insert ?\n (mapconcat (lambda (a) (char-to-string (car a)))
941 freq-list nil)
942 "\n\n")
943 ;; Display list of digrams in order of frequency:
944 (let* ((rows (floor (+ (length decipher--digram-list) 9) 10))
945 (i rows)
946 temp-list)
947 (while (> i 0)
948 (setq temp-list decipher--digram-list)
949 (while temp-list
950 (insert (caar temp-list)
951 (format "%3d "
952 (cdar temp-list)))
953 (setq temp-list (nthcdr rows temp-list)))
954 (delete-horizontal-space)
955 (insert ?\n)
956 (setq decipher--digram-list (cdr decipher--digram-list)
957 i (1- i))))
958 ;; Display adjacency list for each letter, sorted in descending
959 ;; order of the number of adjacent letters:
960 (setq freq-list (sort freq-list
961 (lambda (a b) (> (third a) (third b)))))
962 (let ((temp-list freq-list)
963 entry i)
964 (while (setq entry (pop temp-list))
965 (if (equal 0 (second entry))
966 nil ;This letter was not used
967 (setq i (- (car entry) ?A))
968 (insert ?\n " "
969 (decipher--digram-counts (aref decipher--before i)) ?\n
970 (car entry)
971 ": 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 *"
972 (format "%4d %4d %3d%%\n "
973 (third entry) (second entry)
974 (/ (* 100 (second entry)) total-chars))
975 (decipher--digram-counts (aref decipher--after i)) ?\n))))
976 (setq buffer-read-only t)
977 (set-buffer-modified-p nil)
978 ))
979 (message nil))
980
981 ;;====================================================================
982 ;; Statistics Buffer:
983 ;;====================================================================
984
985 (defun decipher-stats-mode ()
986 "Major mode for displaying ciphertext statistics."
987 (interactive)
988 (kill-all-local-variables)
989 (setq buffer-read-only t
990 buffer-undo-list t ;Disable undo
991 case-fold-search nil ;Case is significant when searching
992 indent-tabs-mode nil ;Do not use tab characters
993 major-mode 'decipher-stats-mode
994 mode-name "Decipher-Stats")
995 (use-local-map decipher-stats-mode-map)
996 (run-mode-hooks 'decipher-stats-mode-hook))
997 (put 'decipher-stats-mode 'mode-class 'special)
998
999 ;;--------------------------------------------------------------------
1000
1001 (defun decipher-display-stats-buffer ()
1002 "Make the statistics buffer visible, but do not select it."
1003 (let ((stats-buffer (decipher-stats-buffer))
1004 (current-window (selected-window)))
1005 (or (eq (current-buffer) stats-buffer)
1006 (progn
1007 (pop-to-buffer stats-buffer)
1008 (select-window current-window)))))
1009
1010 (defun decipher-stats-buffer (&optional create)
1011 "Return the buffer used for decipher statistics.
1012 If CREATE is non-nil, create the buffer if it doesn't exist.
1013 This is guaranteed to return a buffer in Decipher-Stats mode;
1014 if it can't, it signals an error."
1015 (cond
1016 ;; We may already be in the statistics buffer:
1017 ((eq major-mode 'decipher-stats-mode)
1018 (current-buffer))
1019 ;; See if decipher-stats-buffer exists:
1020 ((and (bufferp decipher-stats-buffer)
1021 (buffer-name decipher-stats-buffer))
1022 (or (with-current-buffer decipher-stats-buffer
1023 (eq major-mode 'decipher-stats-mode))
1024 (error "Buffer %s is not in Decipher-Stats mode"
1025 (buffer-name decipher-stats-buffer)))
1026 decipher-stats-buffer)
1027 ;; Create a new buffer if requested:
1028 (create
1029 (let ((stats-name (concat "*" (buffer-name) "*")))
1030 (setq decipher-stats-buffer
1031 (if (eq 'decipher-stats-mode
1032 (cdr-safe (assoc 'major-mode
1033 (buffer-local-variables
1034 (get-buffer stats-name)))))
1035 ;; We just lost track of the statistics buffer:
1036 (get-buffer stats-name)
1037 (generate-new-buffer stats-name))))
1038 (with-current-buffer decipher-stats-buffer
1039 (decipher-stats-mode))
1040 decipher-stats-buffer)
1041 ;; Give up:
1042 (t (error "No statistics buffer"))))
1043
1044 ;;====================================================================
1045
1046 (provide 'decipher)
1047
1048 ;;(defun decipher-show-undo-list ()
1049 ;; "Display the undo list (for debugging purposes)."
1050 ;; (interactive)
1051 ;; (with-output-to-temp-buffer "*Decipher Undo*"
1052 ;; (let ((undo-list decipher-undo-list)
1053 ;; undo-rec undo-map)
1054 ;; (with-current-buffer "*Decipher Undo*"
1055 ;; (while (setq undo-rec (pop undo-list))
1056 ;; (or (consp (car undo-rec))
1057 ;; (setq undo-rec (list undo-rec)))
1058 ;; (insert ?\()
1059 ;; (while (setq undo-map (pop undo-rec))
1060 ;; (insert (cdr undo-map) (car undo-map) ?\ ))
1061 ;; (delete-char -1)
1062 ;; (insert ")\n"))))))
1063
1064 ;;; decipher.el ends here