Softpanorama
May the source be with you, but remember the KISS principle ;-)

Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

Beautifiers and Pretty Printers

News See also Recommended Links Program Understanding  Programming style Multitarget verifiers Debugging
Multitarget highlighters Multitarget beautifiers C C++ Perl Prettyprinting HTML  
Unix History Admin Horror Stories Software Engineering Language Design and Programming Quotes Humor Random Findings Etc

Beautifiers and pretty printers are essential language tools.  Unfortunately very few programmers use them. If you do not use please start now... that's a real life saver tool. Programmers spend 50% of their time just looking at source code. Formatting source code can make them more productive in this task, saving a significant amount of an time and efforts to find bugs.

What is a beautifier? A language-specific utility that reformats a program to conform to a standard of presentation. For example, blank lines might be inserted after procedure bodies and declarations, indentation might be adjusted to properly reflect nesting levels, excessively long lines might be split into shorter ones, and matching parentheses and braces might be vertically aligned to show program structure. Among the advantages of using a beautifier:

I use beautifiers with each language that I programmed until I get to Perl. When I first started learning Perl, I immediately began looking for a beautifier, and was surprised when I couldn't find one. From this point of view Perl definitely sucks... I became interested and start browsing WEB. And I realized that my efforts can benefit other people. That's how this page was created.  It's not updated often, it's primitive, but still it's better than nothing...

BTW later I found that there are two tools to beatify Perl program: one is pertidy and the second is DzSoft Perl Editor .  Everything is good that ends good. Otherwise I might switch to another scripting language ;-) . See also A Beautifier for the Perl Programming Language

Why do I worry about beautifier?  So one benefit of a good beautifier is that it can highlight, in some distinctive manner, material that might be syntactically acceptable but semantically inappropriate. In this way, a beautifier is a very important debugging aid -- kind of lint for poor people.

Another benefit of beautification comes from its role as a standard was to format programs. This makes it much easier for a programmer to read the code of somebody else as well as his own programs in the future. In this way, a beautifier is a must tool for any team and it's vital for program maintenance. 

A source code formatter accepts a program source file, and generates another equivalent source file which is nicely formatted according to the source language syntax, including indentation, normalized case for identifiers, etc.

A related topic is obfuscators, which are "anti-beautifiers" and are designed to remove meaningful formatting in order to make code more difficult to read and comprehend, to discourage reverse engineering. Their success is another point about tremendous value of a good beautifier.

Many conventional formatting tools use ad hoc string processing methods to implement the reformatting.. This can work pretty well for many sample files. But it might fails for complex cases like comments around incomplete blocks of code or keywords, obscure language features such as escapes in quoted strings, etc., as for example in Perl.  The result of such failure is badly formatted source text, introduced syntax errors, or worse, program source that is still syntactically correct but semantically different then the original. That means that for a new beautifier a lot of tests need to be performed and at least to the initial several weeks the results should be verified using diff (see How can I trust Beautifier programs??!! about this procedure).

The most reliable way to build a beautifier is to lexically parse the source language according to the source language lexical rules. This ensures that the lexems (lexical tokens)  found by formatter are those that corresponds to lexems of the language.

Dr. Nikolai Bezroukov


Top updates

Softpanorama Switchboard
Softpanorama Search


NEWS CONTENTS

Old News ;-)

[Oct 10, 2011] Uncrustify 0.59

Written in

Uncrustify is a source code beautifier that allows you to banish crusty code. It works with C, C++, C#, D, Java, and Pawn and indents (with spaces only, tabs and spaces, and tabs only), adds and removes... newlines, has a high degree of control over operator spacing, aligns code, is extremely configurable, and is easy to modify (more)

prettyprinter.de

This is a Web-based source code beautifier (source code formatter), similiar to indent. Please make a backup before you replace your code!

[Jan 19, 2011] pb

#!/usr/bin/perl

# 'pb' Perl Beautifier

# Written by P. Lutus Ashland, Oregon lutusp@arachnoid.com 5/20/96

# This script processes Perl scripts, cleans up and indents, like cb does for C

# Be careful with this script - it accepts wildcards and processes every text file
# that meets the wildcard criteria. This could be a catastrophe in the hands of the unwary.

$tabstring = "  "; # You may place any tab-stop characters you want here

if($ARGV[0] eq "") {
  print "usage: file1 file2 etc. or wildcards (replaces originals in place)\n";
}
else {
  foreach $filename (@ARGV) {
    if(-T $filename) {
      &process($filename);
    }
  }
}

sub process {
  $fn = $_[0];
  undef $/; # so we can grab the entire file at once
  undef @infa; # prevent left-overs
  print STDERR "$fn";
  open (INFILE,$fn);
  @infa = split(/\n/,<INFILE>);
  close INFILE;
  
  $/ = "\n"; # restore default
  
  open (OUTFILE,">$fn");
  $tabtotal = 0;
  for (@infa) {
    
    s/^\s*(.*?)\s*$/$1/; # strip leading and trailing spaces
    
    $a = $_; # copy original string
    $q = $a; # i plan to modify this copy for testing
    $q =~ s/\\\#//g; # remove escaped comment tokens
    $q =~ s/\#.*?$//g; # remove Perl-style comments
    $q =~ s{/\*.*?\*/} []gsx; # remove C-style comments
    $q =~ s/\\\{//g; # remove escaped left  braces
    $q =~ s/\\\}//g; # remove escaped right braces
    $q =~ s/\\\(//g; # remove escaped left  parentheses
    $q =~ s/\\\)//g; # remove escaped right parentheses
    
    $q =~ s/\'.*?\'//g; # remove single-quoted lines
    
# now the remaining braces/parentheses should be structural
    
    $delta = -($q =~ s/\}/\}/g); # subtract closing braces
    $delta += ($q =~ s/\{/\{/g); # add opening braces
    
    $delta -= ($q =~ s/\)/\)/g); # subtract closing parens
    $delta += ($q =~ s/\(/\(/g); # add opening parens
    
    $tabtotal += ($delta < 0)?$delta:0; # subtract closing braces/parentheses
    
    $i = ($tabtotal > 0)?$tabtotal:0; # create tab index
    
    $tabtotal += ($delta>0)?$delta:0; # add opening braces/parentheses for next print
    
    if(substr($a,0,1) ne "#") { # don't tab comments
      print OUTFILE $tabstring x $i; # "tab" out to position
    }
    
    print OUTFILE "$a\n"; # print original line
  } # -- for (@infa)
  
  close OUTFILE;
  
  if($tabtotal != 0) {
    print STDERR " Indentation error: $tabtotal\n";
  }
  else {
    print STDERR "\n";
  }
} # sub process

Beautifier freshmeat.net

Beautifier (previously known as PSH, the PHP Syntax Highlighter) highlights and indents source code using highlight configuration files which are similar to Ultraedit highlighting files. It supports C, C#, Java, Perl, PHP, Pascal, Lisp, Mumps, Eiffel, Euphoria, and x86 Assembler, amongst others. It handles line/block comments, keyword highlighting, correct indentation, string highlighting, language contexts (allowing embedded languages), and selection highlighting. It is available in PHP and Perl versions.

[Aug 20, 2008] Pretty Diff - The difference tool by Austin Cheney

A very interesting online tool that provides "pretty diff" feature for HTML and Javascript code. "The Diff View Type option provides two choices. The first choice, Side by Side View, reports the output into two columns that display a side by side comparison of the differences. The second choice, Inline View, displays the output into a single column so that the differences can be seen in a vertical comparison."
Pretty Diff

[Jun 30, 2008] NArrange 0.2.5 by James Nies

About: NArrange is a tool for arranging .NET source code. This code beautifier automatically sorts and organizes class members into groups or regions. Currently, C# and VB code files are supported.

Changes: This release adds support for processing source files with conditional compilation preprocessor directives, and fixes a couple of C# and VB parsing/writing bugs.

[Mar 27, 2008] Highlight 2.6.9 by André Simon

About: Highlight is a universal converter from source code to HTML, XHTML, RTF, TeX, LaTeX, and XML. (X)HTML output is formatted by Cascading Style Sheets. It supports more than 100 programming languages, and includes 40 highlighting color themes. It's possible to easily enhance the parsing database. The converter includes some features to provide a consistent layout of the input code.

Changes: Embedded output instructions specific to the output document format were added. Support for Arc and Lilypond was added.

[Dec 7, 2007] freshmeat.net Project details for perltidy

Perltidy is a Perl script indenter and beautifier. By default it approximately follows the suggestions in perlstyle(1), but the style can be adjusted with command line parameters. Perltidy can also write syntax-colored HTML output.

Release focus: Minor feature enhancements

[Dec 6, 2007] freshmeat.net Project details for JsDecoder

JavascriptDecoder is a tool to easily decode obfuscated Javascript code. Besides decoding, it can also serve as a Javascript code beautifier and colorizer.

[Mar 24, 2007] freshmeat.net Project details for GNU Source-highlight

About:
GNU Source-highlight produces a document with syntax highlighting when given a source file. It handles many languages, e.g., Java, C/C++, Prolog, Perl, PHP3, Python, Flex, HTML, and other formats, e.g., ChangeLog and log files, as source languages and HTML, XHTML, DocBook, ANSI color escapes, LaTeX, and Texinfo as output formats. Input and output formats can be specified with a regular expression-oriented syntax.

Release focus: Major feature enhancements

Changes:
Language definitions for makefiles, CSS files, and m4 files were added. The --quiet option was added to show no progress information. Direct color specifications in double quotes in style files are allowed. In style files, one can specify formatting options for more than one element on the same line. CSS files can be specified as style files (with limited support). Background colors for single elements and the entire document are now handled.

[Nov 25, 2006] freshmeat.net Project details for Uncrustify

Uncrustify is a source code beautifier that allows you to banish crusty code. It works with C, C++, C#, D, Java, and Pawn and indents (with spaces only, tabs and spaces, and tabs only), adds and removes newlines, has a high degree of control over operator spacing, aligns code, is extremely configurable, and is easy to modify.

PL-SQL, Java, and Javascript Code 'Beautifiers'

PL/SQL, Java, and Javascript 'Beautifiers'
Charles Roth 21 July 2003
Last revised 21 July 2003

I. Introduction
In my first major foray into the source code for CAPS, I had the dubious pleasure of modifying largely unindented and unformatted PL/SQL and Javascript. As I am a big fan (one might say evangelist) of readable code, this situation was untenable (see thedance.net/~roth/writing.html).

But what to do? Manually reformatting the code was out of the question. But plenty of tools exist that will automatically reformat code; the problem reduces to one of basic research. Google to the rescue!

II. PL/SQL
There's one clear "winner" for formatting PL/SQL: Formatter Plus (aka F+) from Quest. (Thanks to Erika for the initial lead.) The good news is that F+ is compatible with (can be launched from) both SQL Navigator and Toad. The bad news is that F+ is commercial and proprietary: a single license is $200. The good news (see a pattern?) is that 30-day trial versions are downloadable from the link above. The even better news is that a single copy, put on our network, might suffice for our needs.

F+ has a large array of formatting options, which are pretty logically arranged in the collapsible menu shown on the right. My favorite options are:

The installation was trivial; download the 30-day trial, and run the installer.

The operation was also pretty easy. In SQL Navigator, click on "Tools", "Formatter Tools", "Launch Formatter Plus". Once in F+ (it gets its own independent window), open your PL/SQL file and click on "Text Editor", then "Format Text" (or just press F2).

The 30-day trial version apparently does not allow you to save the results (it hung when I tried). But it's easy enough to cut-and-paste the formatted text window contents into Notepad, and go from there. (I wouldn't want to do that every day, but for just reformatting old code, it's well worth the little bit of effort.)

Note: This did cause me one nuisance when I went to use the reformatted code in an implementation checklist: the MKS "diff" result was huge and useless. The solution was to reformat the "version checked-out" code, and do a diff against that with my new code.

(Nov 2004 -- I just received word of a new entry, from Semantic Designs.

III. Javascript

Not surprisingly, there are a wide variety of Javascript formatters available -- there's a (probably) larger and (definitely) more varied audience of Javascript developers, compared to PL/SQL.

I found two that seemed "best of breed", one commercial, one free. The winners were Trita (commercial) and Javascript Code Improver (free) -- although you may also want to look at the Semantic Designs family of code formatters, and the free Arachnophilia, which has many HTML-improver capabilities as well.

Trita has some excellent ease-of-use aspects. It has three different ways of specifying your formatting preferences, the easiest of which is a code sample! You simply modify their standard code sample to look the way you like Javascript to look, and it uses that as a template. Also, to reformat a file under Windows, just right-click on it in Windows Explorer.

Trita costs all of $35, and offers a free download, with pretty much the same limitations as F+ (cut-and-paste from formatting window, etc.)

The Javascript Code Improver is extremely simple, and has just a very few options (indent size, open brace on same vs. next line). It's trivial to use, and is, after all, free.

IV. Java
Java also has a clear winner:
Jalopy. It's both very powerful and Open-Source, and thus free. It even has a page that lists related tools, if you want to pursue other options.

I found Jalopy somewhat tricky to install and configure for use from the shell (command line). It does have a ton of "plug-ins", i.e. ways to plug Jalopy in to existing Java IDE's (integrated development environments), which is all to the good.

V. Notes on Coding Style
When you think about code format, think beyond just indentation. I have been working with, and in some cases rewriting, code formatters for over 20 years, starting with FLECS, a structured Fortran preprocessor. In that time I have synthesized my experience into a few simple rules:

  1. Use automatic formatters. Adding more code to existing unindented code, without reformatting it, verges on unethical and unprofessional behavior. There's no excuse for making a mess worse.

  2. Always indent blocks by 3 spaces. Never use tabs. (Less than 3 is to small to see; more than 3 takes up too much horizontal space. Keep your lines to less than 100 characters, ideally less than 80.)
  3. Put block openers (e.g. "{", "THEN", etc.) on the same line as the statement that started the block (e.g. "IF").

    Block openers are purely "syntactic sugar". They add absolutely no semantic value to the code. As you read the code, your eye should follow the indentation, not the tiny "}"s or "END"s. The notion of putting the block openers on the next line simply wastes vertical space -- which means you can see (and thus understand) less code.

  4. Don't use ALL UPPER CASE unless there's a particular naming convention -- e.g. putting all SQL keywords in upper case. Your eye is well trained to see upper case letters as "stops" -- indicating the beginning of one sentence (and thus the end of the previous.) Using all upper case is forcing your eye to stutter.

  5. Use horizontal whitespace and parentheses to make small chunks of code easier to read. Compare:
       for (i=0, j=15; i < 37 && j <52; ++i, ++j)
    
       for (i=0, j=15;    (i < 37) && (j < 52);    ++i, ++j)
    
    Which is easier to read? Why?

  6. Use horizontal whitespace to align vertical chunks of code. When code must wrap across multiple lines, use whitespace to made the associations between the lines more obvious. This is useful in declarations of many variables, in long parameters lists to functional calls... even in groups of related assignments, e.g.
       x  = (y -c ) * (y -b ) + a;
       x1 = (y1-c1) * (y1-b1) + a1;

    You may think it's a lot of work -- but it's less work in the end than reading code character by character. It also helps if you find and consistently use, a powerful editor. It doesn't matter what it is, but find one that does the things you most need for you. At the very least it should do brace or block open/close matching for you, or verify the matches. Otherwise you might as well be punching 80 column cards!

  7. Simplify code that generates code. For example, in PL/SQL, replace:
       htp.p ('function do_something (x) {');
       htp.p ('   var y = 2 * x;');
    with
       htp.p ('
          function do_something (x)
             var y = 2 * x;
       ')
    (Thanks to Srini B for pointing this one out.)

  8. Develop and use a standard header comment. In particular, that header must describe the purpose of the code, and the context in which it is used. (Imagine reading vehicle driving instructions without knowing if you were in a Lamborghini, a VW bug, or a shopping cart.) The purpose description should be no less than three lines!

    Or see my extended rant on the subject at thedance.net/~roth/writing.html.

NONAGS Command Line Tools - Freeware

GC! GreatCode 1.095 for Win9x/NT4/ME/Win2k (50 kb)
From NonagsPLUS (Members) (50 kb)
Updated: Sep 19, 2000
Homepage
Author: christophe beaudet
Description: Very powerfull C/C++ source code beautifier.

freshmeat.net Project details for Beautifier

Beautifier (previously known as PSH, the PHP Syntax Highlighter) highlights and indents source code using highlight configuration files which are similar to Ultraedit highlighting files. It supports C, C#, Java, Perl, PHP, Pascal, Lisp, Mumps, Eiffel, Euphoria, and x86 Assembler, amongst others. It handles line/block comments, keyword highlighting, correct indentation, string highlighting, language contexts (allowing embedded languages), and selection highlighting. It is available in PHP and Perl versions.

C-C++ Beautifier HOW-TO

(The latest version of this document is at "http://www.milkywaygalaxy.freeservers.com" . You may want to check there for changes).

Coding standards for C/C++ or any language is required in order to make the programs more readable/understandable by programmers. There are C/C++ beautifiers (formating tools) to accomplish this goal. Formatted (beautified) code improves the productivity of programmers by 2 times !!

On Linux/Unixes there is a command called "indent" and "cb" . Refer to 'man indent' and 'man cb'. Note that indent and cb work for only "C" programs. For "C++" programs use "bcpp" .

Important NOTE: To compile bcpp under unix, unpack bcpp.tar.gz and you MUST change directory to "code" and give a make. Do not change to "unix" directory and give a make. That will give lots of errors.

Download the beautifier program from one of the following

I used BCPP to format the C++ programs and it worked fine for me. You may want to check other tools and use the one which you may like the most.

BCPP was written by Steven De Toni at steve@alpha.ocbbs.gen.nz

Info Node (cookbook.info)Prettyprint Text

Outputting Text with Language Highlighting
------------------------------------------

The `enscript' tool currently recognizes the formatting of more than
forty languages and formats, from the Perl and C programming languages
to HTML, email, and Usenet news articles; `enscript' can highlight
portions of the text based on its syntax. In Unix-speak, this is called
"pretty-printing".

The following table lists the names of some of the language filters
that are available at the time of this writing and describes the
languages or formats they're used for.

FILTER LANGUAGE OR FORMAT
`ada' Ada95 programming language.
`asm' Assembler listings.
`awk' AWK programming language.
`bash' Bourne-Again shell programming language.
`c' C programming language.
`changelog' ChangeLog files.
`cpp' C++ programming language.
`csh' C-Shell script language.
`delphi' Delphi programming language.
`diff' Normal "difference reports" made from `diff'.
`diffu' Unified "difference reports" made from `diff'.
`elisp' Emacs Lisp programming language.
`fortran' Fortran77 programming language.
`haskell' Haskell programming language.
`html' HyperText Markup Language (HTML).
`idl' IDL (CORBA Interface Definition Language).
`java' Java programming language.
`javascript' JavaScript programming language.
`ksh' Korn shell programming language.
`m4' M4 macro processor programming language.
`mail' Electronic mail and Usenet news articles.
`makefile' Rule files for `make'.
`nroff' Manual pages formatted with `nroff'.
`objc' Objective-C programming language.
`pascal' Pascal programming language.
`perl' Perl programming language.
`postscript' PostScript programming language.
`python' Python programming language.
`scheme' Scheme programming language.
`sh' Bourne shell programming language.
`skill' Cadence Design Systems Lisp-like language.
`sql' Sybase 11 SQL.
`states' Definition files for `states'.
`synopsys' Synopsys `dc' shell scripting language.
`tcl' Tcl programming language.
`tcsh' TC-Shell script language.
`vba' Visual Basic (for Applications).
`verilog' Verilog hardware description language.
`vhdl' VHSIC Hardware Description Language (VHDL).
`vrml' Virtual Reality Modeling Language (VRML97).
`zsh' Z-shell programming language.

To pretty-print a file, give the name of the filter to use as an
argument to the `-E' option, without any whitespace between the option
and argument.

* To pretty-print the HTML file `index.html', type:

$ enscript -Ehtml index.html <RET>

* To pretty-print an email message saved to the file
`important-mail', and output it with no headers to a file named
`important-mail.ps', type:

$ enscript -B -Email -p important-mail.ps important-mail <RET>

Use the special `--help-pretty-print' option to list the languages
supported by the copy of `enscript' you have.

* To peruse a list of currently supported languages, type:

$ enscript --help-pretty-print | less <RET>

www.bitterberg.de -- Tilmanns Corner -- diff HTML beautifier

GNU Source-highlight - GNU Project - Free Software Foundation (FSF) v1.6 by Lorenzo Bettini

This program, given a source file, produces a document with syntax highlighting.

At the moment this package can handle

as source languages, and

as output format.

NOTICE: now the name of the program is source-highlight: there are no two separate programs, namely java2html and cpp2html, anymore. However there are two shell scripts with the same name in order to facilitate the migration (however their use is not advised).

GNU Source-highlight is free software. Please see the file COPYING for details. For documentation, please read this file.

GNU Source-highlight is a GNU program and its main home page is at GNU site:
http://www.gnu.org/software/src-highlite/source-highlight.html

You can download it from GNU's ftp site:
ftp://ftp.gnu.org/gnu/source-highlight/ or from one of its mirrors (see http://www.gnu.org/prep/ftp.html).

I do not distribute Windows binaries anymore; since, they can be easily built by using Cygnus C/C++ compiler, available at http://www.cygwin.com/. However, if you don't feel like downloading such compiler, you can request such binaries directly to me, by e-mail (bettini@gnu.org) and I can send them to you.
An MS-Windows port of Source-highlight is available from http://gnuwin32.sourceforge.net/.

You may also want to check the md5sum of the archives, which are also digitally signed by me (Lorenzo Bettini) with GNU gpg (http://www.gnupg.org). My GPG public key can be found at my home page (see at the end of this doc).

You can also get the patches, if they are available for a particular release (see below for patching from a previous version).

BS Repository

[July 19, 2002] Mangle 3.0.6

About: Mangle is a source de-formatter/de-commentor. It will remove all comments and/or formatting from C/C++ source code leaving only what is required.

Changes: Some bugfixes, cleanups, and new features.

designed for HTML, Java, and Perl programming. WinTidy is easily
customized, handles huge files, and includes powerful validation and
beautification tools. Integrated browser, Java support, DOS, Unix,
Mac file formats. Print options include 'two-up' printing, syntax
coloring, and line numbers. It's easy to take advantage of WinTidy's
many features. WinTidy's design is intuitive, allowing you to avoid
the pitfalls of learning a new program. Its slick, simple interface
includes customizable menus, toolbars, and keyboard settings. WinTidy
includes powerful editing features including column blocks, drag and
drop editing, bookmarks, split-file editing, and global search and
replace. WinTidy is built for programmers with features like brace
matching, configurable color-syntax highlighting, and custom tool
support. Compilers and other tools are launched on separate threads,
and can be controlled without leaving WinTidy, allowing complete
automation of the compile, build and debug sequence.

Special requirements: 16MB RAM

Adware. Uploaded by the authorized Distributor.

Dave Collins, SharewarePromotions
dave@Sharewarepromotions.com
WinEdit Software Co.
sales@wintidy.com
http://www.wintidy.com/

www.simtel.net wde21.zip (Win32 Pretty Printer for C-code. Free w-C src)

Category: WinME / Win98 / Win95 / Programming Utilities

Publisher: Herman Oosthuysen

Website: http://www.AerospaceSoftware.com/

File Name: wdent121.zip

Also works from the command line and can be called from a batch file. Indent up to 256 files in one go. Freeware with C source code.

Special requirements: None

Freeware. Uploaded by the author.

Herman Oosthuysen, Aerospace Software Ltd.
aerosoft@AerospaceSoftware.com
http://www.AerospaceSoftware.com/

Pprint home page

PPRINT generates source code listings in postscript. It italicizes comments, boldfaces typedefs, and bold-italicizes keywords. It generates line numbers and a cross reference of all typedefs, static and global functions, listing both definitions and references. Definitions are in bold.

PPRINT manages print-outs of multiple files by producing both global and local page numbers. At the end of the run, it prints out a table of contents, and index, and a reference of all globally accessible typedefs and classes.

PPRINT works with C files, C++ files, Verilog files, and text files. It figures out which language based on extension:

From Advanced programming in Perl: Data structures pretty-printing

2.5 Pretty-Printing

In building complicated data structures, it is always nice to have a pretty-printer handy for debugging. There are at least two options for pretty-printing data structures. The first is the Perl debugger itself. It uses a function called dumpValue in a file called dumpvar.pl, which can be found in the standard library directory. We can help ourselves to it, with the caveat that it is an unadvertised function and could change someday. To pretty-print this structure, for example:

  @sample = (11.233,{3 => 4, "hello" => [6,7]});

we write the following:

require 'dumpvar.pl';
dumpValue(\@sample); # always pass by reference

This prints something like this:

0  11.233
1  HASH(0xb75dc0)
   3 => 4
   'hello' => ARRAY(0xc70858)
      0  6
      1  7

We will cover the require statement in Chapter 6, Modules. Meanwhile, just think of it as a fancy #include (which doesn't load the file if it is already loaded).

The Data::Dumper module available from CPAN is another viable alternative for pretty-printing. Chapter 10, Persistence, covers this module in some detail, so we will not say any more about it here. Both modules detect circular references and handle subroutine and glob references.

It is fun and instructive to write a pretty-printer ourselves. Example 2.5 illustrates a simple effort, which accounts for circular references but doesn't follow typeglobs or subroutine references. This example is used as follows:

pretty_print(@sample); # Doesn't need a reference

This prints

11.233
{ # HASH(0xb78b00)
:  3 => 4
:  hello =>
:  :  [ # ARRAY(0xc70858)
:  :  :  6
:  :  :  7
:  :  ]
}

The following code contains specialized procedures (print_array, print_hash, or print_scalar) that know how to print specific data types. print_ref, charged with the task of pretty-printing a reference, simply dispatches control to one of the above procedures depending upon the type of argument given to it. In turn, these procedures may call print_ref recursively if the data types that they handle contain one or more references.

Whenever a reference is encountered, it is also checked with a hash %already_seen to determine whether the reference has been printed before. This prevents the routine from going into an infinite loop in the presence of circular references. All functions manipulate the global variable $level and call print_indented, which appropriately indents and prints the string given to it.

Example 2.5: Pretty-Printing

$level = -1; # Level of indentation

sub pretty_print {
    my $var;
    foreach $var (@_) {
        if (ref ($var)) {
            print_ref($var);
        } else {
            print_scalar($var);
        }
    }
}

sub print_scalar {
    ++$level;
    my $var = shift;
    print_indented ($var);
    --$level;
}

sub print_ref {
    my $r = shift;
    if (exists ($already_seen{$r})) {
        print_indented ("$r (Seen earlier)");
        return;
    } else {
        $already_seen{$r}=1;
    }
    my $ref_type = ref($r);
    if ($ref_type eq "ARRAY") {
        print_array($r);
    } elsif ($ref_type eq "SCALAR") {
        print "Ref -> $r";
        print_scalar($$r);
    } elsif ($ref_type eq "HASH") {
        print_hash($r);
    } elsif ($ref_type eq "REF") {
        ++$level;
        print_indented("Ref -> ($r)");
        print_ref($$r);
        --$level;
    } else {
        print_indented ("$ref_type (not supported)");
    }
}

sub print_array {
    my ($r_array) = @_;
    ++$level;
    print_indented ("[ # $r_array");
    foreach $var (@$r_array) {
        if (ref ($var)) {
            print_ref($var);
        } else {
            print_scalar($var);
        }
    }
    print_indented ("]");
    --$level;
}

sub print_hash {
    my($r_hash) = @_;
    my($key, $val);
    ++$level;
    print_indented ("{ # $r_hash");
    while (($key, $val) = each %$r_hash) {
        $val = ($val ? $val : '""');
        ++$level;
        if (ref ($val)) {
            print_indented ("$key => ");
            print_ref($val);
        } else {
            print_indented ("$key => $val");
        }
        --$level;
    }
    print_indented ("}");
    --$level;
}

sub print_indented {
    $spaces = ":  " x $level;
    print "${spaces}$_[0]\n";
}

print_ref simply prints its argument (a reference) and returns if it has already seen this reference. If you were to read the output produced by this code, you would find it hard to imagine which reference points to which structure. As an exercise, you might try producing a better pretty-printer, which identifies appropriate structures by easily identifiable numeric labels like this:

:  hello =>
:  :  [          # 10
:  :  :  6
:  :  :  7
:  :  ]
:  foobar => array-ref # 10
}

The number 10 is an automatically generated label, which is more easily identifiable than something like ARRAY(0xc70858).


Recommended Links

Softpanorama hot topic of the month

Softpanorama Recommended

www.simtel.net - Search Results

C Programming

Beautifiers for other Languages

To create presentation of codes to display using HTML -

 


Multitarget highllighters

GNU Source-highlight - GNU Project - Free Software Foundation (FSF)  v1.6 by Lorenzo Bettini

This program, given a source file, produces a document with syntax highlighting.

At the moment this package can handle

as source languages, and

as output format.

NOTICE: now the name of the program is source-highlight: there are no two separate programs, namely java2html and cpp2html, anymore.  However there are two shell scripts with the same name in order to facilitate the migration (however their use is not advised).

GNU Source-highlight is free software. Please see the file COPYING for details. For documentation, please read this file.

GNU Source-highlight is a GNU program and its main home page is at GNU site:
http://www.gnu.org/software/src-highlite/source-highlight.html

You can download it from GNU's ftp site:
ftp://ftp.gnu.org/gnu/source-highlight/ or from one of its mirrors (see http://www.gnu.org/prep/ftp.html).

I do not distribute Windows binaries anymore; since, they can be easily built by using Cygnus C/C++ compiler, available at http://www.cygwin.com/. However, if you don't feel like downloading such compiler, you can request such binaries directly to me, by e-mail (bettini@gnu.org) and I can send them to you.
An MS-Windows port of Source-highlight is available from http://gnuwin32.sourceforge.net/.

You may also want to check the md5sum of the archives, which are also digitally signed by me (Lorenzo Bettini) with GNU gpg (http://www.gnupg.org). My GPG public key can be found at my home page (see at the end of this doc).

You can also get the patches, if they are available for a particular release (see below for patching from a previous version).


Multitarget verifiers

www.simtel.net wintid10.zip (Powerful validating HTML,Java,Perl ed. Adware)


Multitarget beautifiers

ASBeautifier 0.8.0
ASBeautifier is a C++ port of JSBeautifier. It automatically reindents C++, C, and Java source files, i.e. beautifies them. ABeautifier is small, fast, and distributed as open-software (under the 'Artistic License'). ASBeautifier was created following interest from users of the jstyle family of source code filters.

C beautifiers

indent - GNU Project - Free Software Foundation (FSF)

Indent -- This is the home page for the GNU indent tool.

Artistic Style 1.2.0
Artistic Style is a fast and small open-source(TM) indenter and reformatter of C, C++ and Java source codes.

Version 1.2.0 contains numerous serious bug fixes, and a new formatting option for special treatment of mono-line blocks of code.

Tal Davidson @ 12/19/98 - 15:49 EST
ASBeautifier 0.8.0
ASBeautifier is a C++ port of JSBeautifier. It automatically reindents C++, C, and Java source files, i.e. beautifies them. ABeautifier is small, fast, and distributed as open-software (under the 'Artistic License'). ASBeautifier was created following interest from users of the jstyle family of source code filters.

C++

[36] Miscellaneous environmental issues, C++ FAQ Lite

In alphabetical order:

Finally, you might consider lgrind which is another C++ to LaTeX translator (check for the closest mirror site of the ctan archive). The following is a grind definition for C++ (but this one doesn't recognize some new keywords such as bool or wchar_t, and it doesn't recognize a file ending with .cpp as C++):

 

 C++|c++|CC:\
    :pb=\p\d?\(:cf:np=\)\d?;:bb={:be=}:\
    :cb=/*:ce=*/:ab=//:ae=$:sb=":se=\e":lb=':\
    :zb=@:ze=@:tb=%%:te=%%:mb=%\$:me=\$%:vb=%\|:ve=\|%:\
    :le=\e':tl:id=_~\::\
    :kw=asm auto break case cdecl char continue default do double else\
    enum extern far float for fortran goto huge if int interrupt long\
    near pascal register return short signed sizeof static struct\
    switch typedef union unsigned while void\
    #define #else #endif #if #ifdef #ifndef #include #undef # define\
    endif ifdef ifndef include undef defined #pragma\
    class const delete friend inline new operator overload private\
    protected public template this virtual:

Random Findings

A Fortran Pretty Printer

The prettyp package

Consists of a suite of program that generates "pretty" PostScript source code listings using TeX. For a given language, comments are rendered in Times Roman italics, keywords in bold, strings in Courier; line-numbers, every 10 lines in a tiny font, and function/subroutine/procedure definitions, in a larger font, are displayed along the right margin. HISTORY prettyp (a new addition to the tgrind package) uses tfontedpr, written by Van Jacobson, which was originally based on BSD 4.2 vfontedpr, written by Bill Joy & Dave Presotto, which used troff. All the contents of the original tgrind package are included for backwards compatibility. This release was ported to build under GNU/Linux (there was a variable called _start that was messing with the compiler's idea of reality), and Solaris with TeX (Web2C 7.2) 3.14159 by Luis Fernandes & Jason Naughton. The major feature of prettyp (w.r.t. tgrind) is its automatic language detection capabilities that enables one to grind source code without specifying the -l (language) option. prettyp uses a combination of filename extensions and interpreter (#! magic) to deduce the language. LANGUAGE SUPPORT Languages supported by this release are: C, C++ (new), FORTRAN77, ISP, Icon, Java (new), LDL, Emacs Mock Lisp, Model, Modula2, Pascal, Perl (new), Python (new), RATFOR, Russell, sh/csh, Tcl (new) and yacc grammer. Support for additional languages can be easily added, see EXTENDING LANGUAGE SUPPORT below. REQUIREMENTS You will need TeX to be installed on your system for this program to work. You will need perl to use the prettyp front-end (specifically, the script "lang", that performs automatic language detection). PLATFORMS tfontedpr, the program that does all the actual work, has been successfully built on i586 GNU/Linux 2.0.34, SPARC Solaris 2.5.1, and SunOS 4.1.4. It should compile without problem for most other platforms. EXAMPLE To grind a C source-code file and a shell script, type: prettyp vgrindefs.c prettyp to generate vgrindefs.c.ps and prettyp.ps which may be viewed with ghostview or printed on a PostScript printer. You can visit the prettyp home page at www.ee.ryerson.ca/~elf/prettyp/ and view the "pretty" PostScript output for a shell script, a perl script, C code and Tcl/Tk code. EXTENDING LANGUAGE SUPPORT To add pretty print capabilities for other languages, add the language definition to the vgrindefs database and modify the alist in the lang perl script adding a file-extension/interpreter to language mapping. - -- This article has been digitally signed by the moderator, using PGP. http://www.iki.fi/mjr/cola-public-key.asc has PGP key for validating signature. Send submissions for comp.os.linux.announce to: linux-announce@news.ornl.gov PLEASE remember a short description of the software and the LOCATION. This group is archived at http://www.iki.fi/mjr/linux/cola.html



Etc

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit exclusivly for research and educational purposes.   If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner. 

ABUSE: IPs or network segments from which we detect a stream of probes might be blocked for no less then 90 days. Multiple types of probes increase this period.  

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least


Copyright © 1996-2016 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License.

The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

Last modified: June, 04, 2016