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