(defvar flow-control-c-s-replacement ?\034
"Character that replaces C-s, when flow control handling is enabled.")
(defvar flow-control-c-q-replacement ?\036
"Character that replaces C-q, when flow control handling is enabled.")
(put 'keyboard-translate-table 'char-table-extra-slots 0)
(defun enable-flow-control (&optional argument)
"Toggle flow control handling.
When handling is enabled, user can type C-s as C-\\, and C-q as C-^.
With arg, enable flow control mode if arg is positive, otherwise disable."
(interactive "P")
(if (if argument
(<= (prefix-numeric-value argument) 0)
(nth 1 (current-input-mode)))
(progn
(set-input-mode t nil (nth 2 (current-input-mode)))
(if keyboard-translate-table
(progn
(aset keyboard-translate-table flow-control-c-s-replacement nil)
(aset keyboard-translate-table ?\^s nil)
(aset keyboard-translate-table flow-control-c-q-replacement nil)
(aset keyboard-translate-table ?\^q nil))))
(set-input-mode nil t (nth 2 (current-input-mode)))
(cond ((null keyboard-translate-table)
(setq keyboard-translate-table
(make-char-table 'keyboard-translate-table nil)))
((char-table-p keyboard-translate-table)
(setq keyboard-translate-table
(copy-sequence keyboard-translate-table)))
(t
(let ((the-table (make-char-table 'keyboard-translate-table nil)))
(let ((i 0)
(j (length keyboard-translate-table)))
(while (< i j)
(aset the-table i (elt keyboard-translate-table i))
(setq i (1+ i))))
(setq keyboard-translate-table the-table))))
(aset keyboard-translate-table flow-control-c-s-replacement ?\^s)
(aset keyboard-translate-table ?\^s flow-control-c-s-replacement)
(aset keyboard-translate-table flow-control-c-q-replacement ?\^q)
(aset keyboard-translate-table ?\^q flow-control-c-q-replacement)
(message "XON/XOFF adjustment for %s: use %s for C-s, and use %s for C-q"
(getenv "TERM")
(single-key-description flow-control-c-s-replacement)
(single-key-description flow-control-c-q-replacement))
(sleep-for 2)))
(defun enable-flow-control-on (&rest losing-terminal-types)
"Enable flow control if using one of a specified set of terminal types.
Use `(enable-flow-control-on \"vt100\" \"h19\")' to enable flow control
on VT-100 and H19 terminals. When flow control is enabled,
you must type C-\\ to get the effect of a C-s, and type C-^
to get the effect of a C-q."
(let ((term (getenv "TERM"))
hyphend)
(while (and term (not (member term losing-terminal-types)))
(if (setq hyphend (string-match "[-_][^-_]+$" term))
(setq term (substring term 0 hyphend))
(setq term nil)))
(if term
(enable-flow-control))))
(provide 'flow-ctrl)