#!/usr/bin/env perl
use utf8;
# Escape (most of) control characters when pasting, so bracketed-paste becomes
# more reliable.  Escaped characters are converted to CTRL-V and three decimal
# digits, as it is recognised by vim.
#
# Note that by default ^V is control character for lnext which escapes the
# meaning of next character, should it also be control character. This is
# mostly turned off by anything that wants to receive CTRL-V keypress though.

sub on_tt_paste {
	my ($term, $paste) = @_;

	# CTRL-V needs to be first to be escaped
	$paste =~ s/\x16/\x16022/g;  # SYN (synchronous idle)
                     
	$paste =~ s/\x00/\x16000/g;  # NUL '\0'
	$paste =~ s/\x01/\x16001/g;  # SOH (start of heading)
	$paste =~ s/\x02/\x16002/g;  # STX (start of text)
	$paste =~ s/\x03/\x16003/g;  # ETX (end of text)
	$paste =~ s/\x04/\x16004/g;  # EOT (end of transmission)
	$paste =~ s/\x05/\x16005/g;  # ENQ (enquiry)
	$paste =~ s/\x06/\x16006/g;  # ACK (acknowledge)
	$paste =~ s/\x07/\x16007/g;  # BEL '\a' (bell)
	$paste =~ s/\x08/\x16008/g;  # BS  '\b' (backspace)
	$paste =~ s/\x0B/\x16011/g;  # VT  '\v' (vertical tab)
	$paste =~ s/\x0C/\x16012/g;  # FF  '\f' (form feed)
	$paste =~ s/\x0E/\x16014/g;  # SO  (shift out)
	$paste =~ s/\x0F/\x16015/g;  # SI  (shift in)
	$paste =~ s/\x10/\x16016/g;  # DLE (data link escape)
	$paste =~ s/\x11/\x16017/g;  # DC1 (device control 1)
	$paste =~ s/\x12/\x16018/g;  # DC2 (device control 2)
	$paste =~ s/\x13/\x16019/g;  # DC3 (device control 3)
	$paste =~ s/\x14/\x16020/g;  # DC4 (device control 4)
	$paste =~ s/\x15/\x16021/g;  # NAK (negative ack.)
	$paste =~ s/\x17/\x16023/g;  # ETB (end of trans. blk)
	$paste =~ s/\x18/\x16024/g;  # CAN (cancel)
	$paste =~ s/\x19/\x16025/g;  # EM  (end of medium)
	$paste =~ s/\x1A/\x16026/g;  # SUB (substitute)
	$paste =~ s/\x1B/\x16027/g;  # ESC (escape)
	$paste =~ s/\x1C/\x16028/g;  # FS  (file separator)
	$paste =~ s/\x1D/\x16029/g;  # GS  (group separator)
	$paste =~ s/\x1E/\x16030/g;  # RS  (record separator)
	$paste =~ s/\x1F/\x16031/g;  # US  (unit separator)

	# Allowed special characters:
	# $paste =~ s/\x09/\x16009/g;  # HT  '\t' (horizontal tab)
	# $paste =~ s/\x0D/\x16013/g;  # CR  '\r' (carriage ret)
	# $paste =~ s/\x0A/\x16010/g;  # LF  '\n' (new line)
	# $paste =~ s/\x20/\x16032/g;  # SPACE

	$term->tt_paste($paste);

	1
}