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