Fix my previous commit so that it might even work
[mediawiki.git] / maintenance / parserTests.inc
blob7de93eba30675a37f4bdc6f077b6d06b0683175f
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 # http://www.gnu.org/copyleft/gpl.html
20 /**
21  * @todo Make this more independent of the configuration (and if possible the database)
22  * @todo document
23  * @package MediaWiki
24  * @subpackage Maintenance
25  */
27 /** */
28 $options = array( 'quick', 'color', 'quiet', 'help' );
29 $optionsWithArgs = array( 'regex' );
31 require_once( 'commandLine.inc' );
32 require_once( "$IP/includes/ObjectCache.php" );
33 require_once( "$IP/includes/BagOStuff.php" );
34 require_once( "$IP/languages/LanguageUtf8.php" );
35 require_once( "$IP/includes/Hooks.php" );
36 require_once( "$IP/maintenance/parserTestsParserHook.php" );
37 require_once( "$IP/maintenance/parserTestsParserTime.php" );
39 /**
40  * @package MediaWiki
41  * @subpackage Maintenance
42  */
43 class ParserTest {
44         /**
45          * boolean $color whereas output should be colorized
46          * @access private
47          */
48         var $color;
50         /**
51          * boolean $lightcolor whereas output should use light colors
52          * @access private
53          */
54         var $lightcolor;
56         /**
57          * Sets terminal colorization and diff/quick modes depending on OS and
58          * command-line options (--color and --quick).
59          *
60          * @access public
61          */
62         function ParserTest() {
63                 global $options;
65                 # Only colorize output if stdout is a terminal.
66                 $this->lightcolor = false;
67                 $this->color = !wfIsWindows() && posix_isatty(1);
69                 if( isset( $options['color'] ) ) {
70                         switch( $options['color'] ) {
71                         case 'no':
72                                 $this->color = false;
73                                 break;
74                         case 'light':
75                                 $this->lightcolor = true;
76                                 # Fall through
77                         case 'yes':
78                         default:
79                                 $this->color = true;
80                                 break;
81                         }
82                 }
84                 $this->showDiffs = !isset( $options['quick'] );
86                 $this->quiet = isset( $options['quiet'] );
88                 if (isset($options['regex'])) {
89                         $this->regex = $options['regex'];
90                 } else {
91                         # Matches anything
92                         $this->regex = '';
93                 }
94         }
96         /**
97          * Remove last character if it is a newline
98          * @access private
99          */
100         function chomp($s) {
101                 if (substr($s, -1) === "\n") {
102                         return substr($s, 0, -1);
103                 }
104                 else {
105                         return $s;
106                 }
107         }
109         /**
110          * Run a series of tests listed in the given text file.
111          * Each test consists of a brief description, wikitext input,
112          * and the expected HTML output.
113          *
114          * Prints status updates on stdout and counts up the total
115          * number and percentage of passed tests.
116          *
117          * @param string $filename
118          * @return bool True if passed all tests, false if any tests failed.
119          * @access public
120          */
121         function runTestsFromFile( $filename ) {
122                 $infile = fopen( $filename, 'rt' );
123                 if( !$infile ) {
124                         wfDie( "Couldn't open parserTests.txt\n" );
125                 }
127                 $data = array();
128                 $section = null;
129                 $success = 0;
130                 $total = 0;
131                 $n = 0;
132                 while( false !== ($line = fgets( $infile ) ) ) {
133                         $n++;
134                         if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
135                                 $section = strtolower( $matches[1] );
136                                 if( $section == 'endarticle') {
137                                         if( !isset( $data['text'] ) ) {
138                                                 wfDie( "'endarticle' without 'text' at line $n\n" );
139                                         }
140                                         if( !isset( $data['article'] ) ) {
141                                                 wfDie( "'endarticle' without 'article' at line $n\n" );
142                                         }
143                                         $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
144                                         $data = array();
145                                         $section = null;
146                                         continue;
147                                 }
148                                 if( $section == 'end' ) {
149                                         if( !isset( $data['test'] ) ) {
150                                                 wfDie( "'end' without 'test' at line $n\n" );
151                                         }
152                                         if( !isset( $data['input'] ) ) {
153                                                 wfDie( "'end' without 'input' at line $n\n" );
154                                         }
155                                         if( !isset( $data['result'] ) ) {
156                                                 wfDie( "'end' without 'result' at line $n\n" );
157                                         }
158                                         if( !isset( $data['options'] ) ) {
159                                                 $data['options'] = '';
160                                         }
161                                         else {
162                                                 $data['options'] = $this->chomp( $data['options'] );
163                                         }
164                                         if (preg_match('/\\bdisabled\\b/i', $data['options'])
165                                                 || !preg_match("/{$this->regex}/i", $data['test'])) {
166                                                 # disabled test
167                                                 $data = array();
168                                                 $section = null;
169                                                 continue;
170                                         }
171                                         if( $this->runTest(
172                                                 $this->chomp( $data['test'] ),
173                                                 $this->chomp( $data['input'] ),
174                                                 $this->chomp( $data['result'] ),
175                                                 $this->chomp( $data['options'] ) ) ) {
176                                                 $success++;
177                                         }
178                                         $total++;
179                                         $data = array();
180                                         $section = null;
181                                         continue;
182                                 }
183                                 if ( isset ($data[$section] ) ) {
184                                         wfDie( "duplicate section '$section' at line $n\n" );
185                                 }
186                                 $data[$section] = '';
187                                 continue;
188                         }
189                         if( $section ) {
190                                 $data[$section] .= $line;
191                         }
192                 }
193                 if( $total > 0 ) {
194                         $ratio = wfPercent( 100 * $success / $total );
195                         print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio) ";
196                         if( $success == $total ) {
197                                 print $this->termColor( 32 ) . "PASSED!";
198                         } else {
199                                 print $this->termColor( 31 ) . "FAILED!";
200                         }
201                         print $this->termReset() . "\n";
202                         return ($success == $total);
203                 } else {
204                         wfDie( "No tests found.\n" );
205                 }
206         }
208         /**
209          * Run a given wikitext input through a freshly-constructed wiki parser,
210          * and compare the output against the expected results.
211          * Prints status and explanatory messages to stdout.
212          *
213          * @param string $input Wikitext to try rendering
214          * @param string $result Result to output
215          * @return bool
216          */
217         function runTest( $desc, $input, $result, $opts ) {
218                 if( !$this->quiet ) {
219                         $this->showTesting( $desc );
220                 }
222                 $this->setupGlobals($opts);
224                 $user =& new User();
225                 $options = ParserOptions::newFromUser( $user );
227                 if (preg_match('/\\bmath\\b/i', $opts)) {
228                         # XXX this should probably be done by the ParserOptions
229                         require_once('Math.php');
231                         $options->setUseTex(true);
232                 }
234                 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
235                         $titleText = $m[1];
236                 }
237                 else {
238                         $titleText = 'Parser test';
239                 }
241                 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
243                 $parser =& new Parser();
244                 wfRunHooks( 'ParserTestParser', array( &$parser ) );
245                 
246                 $title =& Title::makeTitle( NS_MAIN, $titleText );
248                 if (preg_match('/\\bpst\\b/i', $opts)) {
249                         $out = $parser->preSaveTransform( $input, $title, $user, $options );
250                 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
251                         $out = $parser->transformMsg( $input, $options );
252                 } else {
253                         $output = $parser->parse( $input, $title, $options, true, true, 1337 );
254                         $out = $output->getText();
256                         if (preg_match('/\\bill\\b/i', $opts)) {
257                                 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
258                         } else if (preg_match('/\\bcat\\b/i', $opts)) {
259                                 $out = $this->tidy ( implode( ' ', $output->getCategoryLinks() ) );
260                         }
262                         $result = $this->tidy($result);
263                 }
265                 $this->teardownGlobals();
267                 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
268                         return $this->showSuccess( $desc );
269                 } else {
270                         return $this->showFailure( $desc, $result, $out );
271                 }
272         }
274         /**
275          * Set up the global variables for a consistent environment for each test.
276          * Ideally this should replace the global configuration entirely.
277          *
278          * @access private
279          */
280         function setupGlobals($opts = '') {
281                 # Save the prefixed / quoted table names for later use when we make the temporaries.
282                 $db =& wfGetDB( DB_READ );
283                 $this->oldTableNames = array();
284                 foreach( $this->listTables() as $table ) {
285                         $this->oldTableNames[$table] = $db->tableName( $table );
286                 }
287                 if( !isset( $this->uploadDir ) ) {
288                         $this->uploadDir = $this->setupUploadDir();
289                 }
291                 $settings = array(
292                         'wgServer' => 'http://localhost',
293                         'wgScript' => '/index.php',
294                         'wgScriptPath' => '/',
295                         'wgArticlePath' => '/wiki/$1',
296                         'wgActionPaths' => array(),
297                         'wgUploadPath' => 'http://example.com/images',
298                         'wgUploadDirectory' => $this->uploadDir,
299                         'wgStyleSheetPath' => '/skins',
300                         'wgSitename' => 'MediaWiki',
301                         'wgServerName' => 'Britney Spears',
302                         'wgLanguageCode' => 'en',
303                         'wgContLanguageCode' => 'en',
304                         'wgDBprefix' => 'parsertest_',
305                         'wgDefaultUserOptions' => array(),
307                         'wgLang' => new LanguageUtf8(),
308                         'wgContLang' => new LanguageUtf8(),
309                         'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
310                         'wgMaxTocLevel' => 999,
311                         'wgCapitalLinks' => true,
312                         'wgDefaultUserOptions' => array(),
313                         'wgNoFollowLinks' => true,
314                         'wgThumbnailScriptPath' => false,
315                         'wgUseTeX' => false,
316                         'wgLocaltimezone' => 'UTC',
317                         );
318                 $this->savedGlobals = array();
319                 foreach( $settings as $var => $val ) {
320                         $this->savedGlobals[$var] = $GLOBALS[$var];
321                         $GLOBALS[$var] = $val;
322                 }
323                 $GLOBALS['wgLoadBalancer']->loadMasterPos();
324                 $GLOBALS['wgMessageCache']->initialise( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
325                 $this->setupDatabase();
327                 global $wgUser;
328                 $wgUser = new User();
329         }
331         # List of temporary tables to create, without prefix
332         # Some of these probably aren't necessary
333         function listTables() {
334                 $tables = array('user', 'page', 'revision', 'text',
335                         'pagelinks', 'imagelinks', 'categorylinks', 'templatelinks', 'externallinks',
336                         'site_stats', 'hitcounter',
337                         'ipblocks', 'image', 'oldimage',
338                         'recentchanges',
339                         'watchlist', 'math', 'searchindex',
340                         'interwiki', 'querycache',
341                         'objectcache', 'job'
342                 );
344                 // FIXME manually adding additional table for the tasks extension
345                 // we probably need a better software wide system to register new
346                 // tables.
347                 global $wgExtensionFunctions;
348                 if( in_array('wfTasksExtension' , $wgExtensionFunctions ) ) {
349                         $tables[] = 'tasks';
350                 }
352                 return $tables;
353         }
355         /**
356          * Set up a temporary set of wiki tables to work with for the tests.
357          * Currently this will only be done once per run, and any changes to
358          * the db will be visible to later tests in the run.
359          *
360          * @access private
361          */
362         function setupDatabase() {
363                 static $setupDB = false;
364                 global $wgDBprefix;
366                 # Make sure we don't mess with the live DB
367                 if (!$setupDB && $wgDBprefix === 'parsertest_') {
368                         # oh teh horror
369                         $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
370                         $db =& wfGetDB( DB_MASTER );
372                         $tables = $this->listTables();
374                         if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
375                                 # Database that supports CREATE TABLE ... LIKE
376                                 global $wgDBtype;
377                                 if( $wgDBtype == 'PostgreSQL' ) {
378                                         $def = 'INCLUDING DEFAULTS';
379                                 } else {
380                                         $def = '';
381                                 }
382                                 foreach ($tables as $tbl) {
383                                         $newTableName = $db->tableName( $tbl );
384                                         $tableName = $this->oldTableNames[$tbl];
385                                         $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
386                                 }
387                         } else {
388                                 # Hack for MySQL versions < 4.1, which don't support
389                                 # "CREATE TABLE ... LIKE". Note that
390                                 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
391                                 # would not create the indexes we need....
392                                 foreach ($tables as $tbl) {
393                                         $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
394                                         $row = $db->fetchRow($res);
395                                         $create = $row[1];
396                                         $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
397                                                 . $wgDBprefix . $tbl .'`', $create);
398                                         if ($create === $create_tmp) {
399                                                 # Couldn't do replacement
400                                                 wfDie("could not create temporary table $tbl");
401                                         }
402                                         $db->query($create_tmp);
403                                 }
405                         }
407                         # Hack: insert a few Wikipedia in-project interwiki prefixes,
408                         # for testing inter-language links
409                         $db->insert( 'interwiki', array(
410                                 array( 'iw_prefix' => 'Wikipedia',
411                                        'iw_url'    => 'http://en.wikipedia.org/wiki/$1',
412                                        'iw_local'  => 0 ),
413                                 array( 'iw_prefix' => 'MeatBall',
414                                        'iw_url'    => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
415                                        'iw_local'  => 0 ),
416                                 array( 'iw_prefix' => 'zh',
417                                        'iw_url'    => 'http://zh.wikipedia.org/wiki/$1',
418                                        'iw_local'  => 1 ),
419                                 array( 'iw_prefix' => 'es',
420                                        'iw_url'    => 'http://es.wikipedia.org/wiki/$1',
421                                        'iw_local'  => 1 ),
422                                 array( 'iw_prefix' => 'fr',
423                                        'iw_url'    => 'http://fr.wikipedia.org/wiki/$1',
424                                        'iw_local'  => 1 ),
425                                 array( 'iw_prefix' => 'ru',
426                                        'iw_url'    => 'http://ru.wikipedia.org/wiki/$1',
427                                        'iw_local'  => 1 ),
428                                 ) );
430                         # Hack: Insert an image to work with
431                         $db->insert( 'image', array(
432                                 'img_name'        => 'Foobar.jpg',
433                                 'img_size'        => 12345,
434                                 'img_description' => 'Some lame file',
435                                 'img_user'        => 1,
436                                 'img_user_text'   => 'WikiSysop',
437                                 'img_timestamp'   => $db->timestamp( '20010115123500' ),
438                                 'img_width'       => 1941,
439                                 'img_height'      => 220,
440                                 'img_bits'        => 24,
441                                 'img_media_type'  => MEDIATYPE_BITMAP,
442                                 'img_major_mime'  => "image",
443                                 'img_minor_mime'  => "jpeg",
444                                 ) );
446                         $setupDB = true;
447                 }
448         }
450         /**
451          * Create a dummy uploads directory which will contain a couple
452          * of files in order to pass existence tests.
453          * @return string The directory
454          * @access private
455          */
456         function setupUploadDir() {
457                 global $IP;
459                 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
460                 mkdir( $dir );
461                 mkdir( $dir . '/3' );
462                 mkdir( $dir . '/3/3a' );
464                 $img = "$IP/skins/monobook/headbg.jpg";
465                 $h = fopen($img, 'r');
466                 $c = fread($h, filesize($img));
467                 fclose($h);
469                 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
470                 fwrite( $f, $c );
471                 fclose( $f );
472                 return $dir;
473         }
475         /**
476          * Restore default values and perform any necessary clean-up
477          * after each test runs.
478          *
479          * @access private
480          */
481         function teardownGlobals() {
482                 foreach( $this->savedGlobals as $var => $val ) {
483                         $GLOBALS[$var] = $val;
484                 }
485                 if( isset( $this->uploadDir ) ) {
486                         $this->teardownUploadDir( $this->uploadDir );
487                         unset( $this->uploadDir );
488                 }
489         }
491         /**
492          * Remove the dummy uploads directory
493          * @access private
494          */
495         function teardownUploadDir( $dir ) {
496                 unlink( "$dir/3/3a/Foobar.jpg" );
497                 rmdir( "$dir/3/3a" );
498                 rmdir( "$dir/3" );
500                 @unlink( "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg" );
501                 @rmdir( "$dir/thumb/3/3a/Foobar.jpg" );
502                 @rmdir( "$dir/thumb/3/3a" );
503                 @rmdir( "$dir/thumb/3/39" ); # wtf?
504                 @rmdir( "$dir/thumb/3" );
505                 @rmdir( "$dir/thumb" );
506                 rmdir( "$dir" );
507         }
509         /**
510          * "Running test $desc..."
511          * @access private
512          */
513         function showTesting( $desc ) {
514                 print "Running test $desc... ";
515         }
517         /**
518          * Print a happy success message.
519          *
520          * @param string $desc The test name
521          * @return bool
522          * @access private
523          */
524         function showSuccess( $desc ) {
525                 if( !$this->quiet ) {
526                         print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
527                 }
528                 return true;
529         }
531         /**
532          * Print a failure message and provide some explanatory output
533          * about what went wrong if so configured.
534          *
535          * @param string $desc The test name
536          * @param string $result Expected HTML output
537          * @param string $html Actual HTML output
538          * @return bool
539          * @access private
540          */
541         function showFailure( $desc, $result, $html ) {
542                 if( $this->quiet ) {
543                         # In quiet mode we didn't show the 'Testing' message before the
544                         # test, in case it succeeded. Show it now:
545                         $this->showTesting( $desc );
546                 }
547                 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
548                 if( $this->showDiffs ) {
549                         print $this->quickDiff( $result, $html );
550                         if( !$this->wellFormed( $html ) ) {
551                                 print "XML error: $this->mXmlError\n";
552                         }
553                 }
554                 return false;
555         }
557         /**
558          * Run given strings through a diff and return the (colorized) output.
559          * Requires writable /tmp directory and a 'diff' command in the PATH.
560          *
561          * @param string $input
562          * @param string $output
563          * @param string $inFileTail Tailing for the input file name
564          * @param string $outFileTail Tailing for the output file name
565          * @return string
566          * @access private
567          */
568         function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
569                 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
571                 $infile = "$prefix-$inFileTail";
572                 $this->dumpToFile( $input, $infile );
574                 $outfile = "$prefix-$outFileTail";
575                 $this->dumpToFile( $output, $outfile );
577                 $diff = `diff -au $infile $outfile`;
578                 unlink( $infile );
579                 unlink( $outfile );
581                 return $this->colorDiff( $diff );
582         }
584         /**
585          * Write the given string to a file, adding a final newline.
586          *
587          * @param string $data
588          * @param string $filename
589          * @access private
590          */
591         function dumpToFile( $data, $filename ) {
592                 $file = fopen( $filename, "wt" );
593                 fwrite( $file, $data . "\n" );
594                 fclose( $file );
595         }
597         /**
598          * Return ANSI terminal escape code for changing text attribs/color,
599          * or empty string if color output is disabled.
600          *
601          * @param string $color Semicolon-separated list of attribute/color codes
602          * @return string
603          * @access private
604          */
605         function termColor( $color ) {
606                 if($this->lightcolor) {
607                         return $this->color ? "\x1b[1;{$color}m" : '';
608                 } else {
609                         return $this->color ? "\x1b[{$color}m" : '';
610                 }
611         }
613         /**
614          * Return ANSI terminal escape code for restoring default text attributes,
615          * or empty string if color output is disabled.
616          *
617          * @return string
618          * @access private
619          */
620         function termReset() {
621                 return $this->color ? "\x1b[0m" : '';
622         }
624         /**
625          * Colorize unified diff output if set for ANSI color output.
626          * Subtractions are colored blue, additions red.
627          *
628          * @param string $text
629          * @return string
630          * @access private
631          */
632         function colorDiff( $text ) {
633                 return preg_replace(
634                         array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
635                         array( $this->termColor( 34 ) . '$1' . $this->termReset(),
636                                $this->termColor( 31 ) . '$1' . $this->termReset() ),
637                         $text );
638         }
640         /**
641          * Insert a temporary test article
642          * @param string $name the title, including any prefix
643          * @param string $text the article text
644          * @param int $line the input line number, for reporting errors
645          * @static
646          * @access private
647          */
648         function addArticle($name, $text, $line) {
649                 $this->setupGlobals();
650                 $title = Title::newFromText( $name );
651                 if ( is_null($title) ) {
652                         wfDie( "invalid title at line $line\n" );
653                 }
655                 $aid = $title->getArticleID( GAID_FOR_UPDATE );
656                 if ($aid != 0) {
657                         wfDie( "duplicate article at line $line\n" );
658                 }
660                 $art = new Article($title);
661                 $art->insertNewArticle($text, '', false, false );
662                 $this->teardownGlobals();
663         }
665         /*
666          * Run the "tidy" command on text if the $wgUseTidy
667          * global is true
668          *
669          * @param string $text the text to tidy
670          * @return string
671          * @static
672          * @access private
673          */
674         function tidy( $text ) {
675                 global $wgUseTidy;
676                 if ($wgUseTidy) {
677                         $text = Parser::tidy($text);
678                 }
679                 return $text;
680         }
682         function wellFormed( $text ) {
683                 $html =
684                         Sanitizer::hackDocType() .
685                         '<html>' .
686                         $text .
687                         '</html>';
689                 $parser = xml_parser_create( "UTF-8" );
691                 # case folding violates XML standard, turn it off
692                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
694                 if( !xml_parse( $parser, $html, true ) ) {
695                         $err = xml_error_string( xml_get_error_code( $parser ) );
696                         $position = xml_get_current_byte_index( $parser );
697                         $fragment = $this->extractFragment( $html, $position );
698                         $this->mXmlError = "$err at byte $position:\n$fragment";
699                         xml_parser_free( $parser );
700                         return false;
701                 }
702                 xml_parser_free( $parser );
703                 return true;
704         }
706         function extractFragment( $text, $position ) {
707                 $start = max( 0, $position - 10 );
708                 $before = $position - $start;
709                 $fragment = '...' .
710                         $this->termColor( 34 ) .
711                         substr( $text, $start, $before ) .
712                         $this->termColor( 0 ) .
713                         $this->termColor( 31 ) .
714                         $this->termColor( 1 ) .
715                         substr( $text, $position, 1 ) .
716                         $this->termColor( 0 ) .
717                         $this->termColor( 34 ) .
718                         substr( $text, $position + 1, 9 ) .
719                         $this->termColor( 0 ) .
720                         '...';
721                 $display = str_replace( "\n", ' ', $fragment );
722                 $caret = '   ' .
723                         str_repeat( ' ', $before ) .
724                         $this->termColor( 31 ) .
725                         '^' .
726                         $this->termColor( 0 );
727                 return "$display\n$caret";
728         }