Eine kleine Probleme

Sometimes you’ll want to view some output in less, the default PAGER, and you’ll realize that the output was colorized with ANSI escape sequences.

To demonstrate the issue, I’ll run a ruby file (example taken from docopt) through pygmentize:

1
$ pygmentize -l ruby naval.rb | less

which produces:

ESC[36mrequireESC[39;49;00m ESC[39;49;00mESC[33m"ESC[39;49;00mESC[33mdocoptESC[39;49;00mESC[33m"ESC[39;49;00m
docESC[39;49;00m ESC[39;49;00m=ESC[39;49;00m ESC[39;49;00m<...ESC[39;49;00m
ESC[33m  #{__FILE__} ship  move   [--speed=]ESC[39;49;00m
ESC[33m  #{__FILE__} ship shoot  ESC[39;49;00m
ESC[33m  #{__FILE__} mine (set|remove)   [--moored|--drifting]ESC[39;49;00m
ESC[33m  #{__FILE__} -h | --helpESC[39;49;00m
ESC[33m  #{__FILE__} --versionESC[39;49;00m

ESC[33mOptions:ESC[39;49;00m
ESC[33m  -h --help     Show this screen.ESC[39;49;00m
ESC[33m  --version     Show version.ESC[39;49;00m
ESC[33m  --speed=  Speed in knots [default: 10].ESC[39;49;00m
ESC[33m  --moored      Moored (anchored) mine.ESC[39;49;00m
ESC[33m  --drifting    Drifting mine.ESC[39;49;00m

ESC[31mDOCOPTESC[39;49;00m

ESC[34mbeginESC[39;49;00m
  ESC[39;49;00mESC[36mrequireESC[39;49;00m ESC[39;49;00mESC[33m"ESC[39;49;00mESC[33mppESC[39;49;00mESC[33m"ESC[39;49;00m
    ESC[39;49;00mppESC[39;49;00m ESC[39;49;00mESC[33mDocoptESC[39;49;00m:ESC[39;49;00mESC[33m:docoptESC[39;49;00m(ESC[39;49;00mdocESC[39;49;00m)ESC[39;49;00m
    ESC[34mrescueESC[39;49;00m ESC[39;49;00mESC[33mDocoptESC[39;49;00m:ESC[39;49;00mESC[33m:ExitESC[39;49;00m ESC[39;49;00m=ESC[39;49;00m>ESC[39;49;00m ESC[39;49;00meESC[39;49;00m
      ESC[39;49;00mESC[36mputsESC[39;49;00m ESC[39;49;00meESC[39;49;00m.ESC[39;49;00mmessageESC[39;49;00m
      ESC[34mendESC[39;49;00m
      (END)]]]]]]]]]]]]]]]]]]]]]]]]])]]]]]]]]]"]]]]"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]"]]]]"]]]]

Keine Probleme!

Of course, you could have invoked less with -r: display raw control characters, but what to do after the fact, when you’ve got a steaming pile of escape sequences staring back at you?

Less supports entering flags from the : prompt. So just type the following literal key sequence to enter raw character mode:

:--r

That’s colon, dash, dash, r.

Now your less output looks like:

require "docopt"
doc = <<DOCOPT
Naval Fate.

Usage:
  #{__FILE__} ship new <name>...
  #{__FILE__} ship <name> move <x> <y> [--speed=<kn>]
  #{__FILE__} ship shoot <x> <y>
  #{__FILE__} mine (set|remove) <x> <y> [--moored|--drifting]
  #{__FILE__} -h | --help
  #{__FILE__} --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

DOCOPT

begin
  require "pp"
  pp Docopt::docopt(doc)
rescue Docopt::Exit => e
  puts e.message
end