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