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