322
APPENDIX D
INTEGRATING
CODE
GENERATION
D.6
VIM
Vi-Improved (vim) is a fully customizable free editor that runs on all major platforms.
Vim does not directly support external tools, though it does provide a robust scripting
mechanism that allows you to create new commands that invoke external processes.
Writing these commands is a simple process. For more information, check the Vim
documentation at www.vim.org/docs.php.
D.6.1
Filtering
Vim allows for easy text filtering using an external command. To run an external filter,
type a colon to get to the command prompt and then type a command using the fol-
lowing syntax:
[range]![command]
This command runs the entire current file through the Unix sort command:
%!sort
D.7
E
MACS
Emacs is an editor of legendary power and complexity. If you are a long-term Emacs
user, you will have your own workflow for the external command integration path.
Let’s look at the technique for filtering a buffer.
Begin by marking the region you wish to filter. Then, press Ctrl+U+Esc to run a
shell command and replace the specified region with the results.
Figure D.12
Komodo’s Run Command 
dialog box with the filter 
settings spcified
Pdf change page size - Compress reduce PDF size in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
C# Code & .NET API to Compress & Decompress PDF Document
pdf edit text size; batch pdf compression
Pdf change page size - VB.NET PDF File Compress Library: Compress reduce PDF size in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
VB.NET PDF Document Compression and Decompression Control SDK
pdf file size; 300 dpi pdf file size
323
A
P
P E N
D
I X
E
Simple templating
Text templating is a critical utility when developing a generator. However, you don’t
always need the most complex and feature-rich template tool. In this appendix, we
examine some very simple text-template code in Ruby.
E.1
S
TRING
FORMATTING
Ruby has its own text templating built in. It uses the double-quote string format, as
shown in the following code:
name = "Jack"                                                      
cost = "$20"
str = "Dear #{name}, You owe us #{cost}"                      
print "#{str}\n"                                              
q
Ruby supports the #{expression} syntax in the double-quoted string and specifies
the results as text. In this case, the str variable is equal to "Dear Jack, You owe
us $20" because we inserted the name and cost values inserted in the #{expres-
sion} sections.
E.1.1
Delayed string formatting
If you want to store a string format in a file, you have to force Ruby to evaluate it using
the eval keyword, as shown here:
name = "Jack"                                                                        
cost = "$20"
format = 'Dear #{name}, You owe us #{cost}'                 
Initializes the 
data variables
Prints the output
Runs the formatting
q
Formats as if it were 
read from a file
VB.NET Image: How to Create Visual Basic .NET Windows Image Viewer
formats, including png, jpeg, gif, tiff, bmp, PDF, and Word can get a basic idea of the page layout from from that, you are entitled to change the orientation
advanced pdf compressor; adjust file size of pdf
C# PDF insert text Library: insert text into PDF content in C#.net
formatted text and plain text to PDF page using .NET NET PDF edit control allows modify existing scanned PDF text. Ability to change text font, color, size and
reader pdf reduce file size; pdf change font size in textbox
324
APPENDIX E
S
IMPLE
TEMPLATING
str = eval( '"'+format+'"' )                              
print 
"#{str}\n"
q
By using eval you force Ruby to run the #{expression} replacement syntax. You
must add the quotes around the format string to properly evaluate the string. If you
don’t include the quotes, the string is evaluated as a Ruby statement.
E.2
R
EGULAR
EXPRESSION
TEMPLATES
Ruby is powerful enough to create a simple text-template syntax in a small amount of
code with the use of regular expressions. This is demonstrated in the code shown here:
name = 'Jack'
cost = '$20'
template = 'Dear <name>, You owe us <cost>'          
output = template                                 
output.gsub!( /<(.*?)>/ ) {                               
eval( $1 )                                              
}
print "#{output}\n"
q
This code uses the global substitution regular expression function to replace all of the
<variable> sections with the variable’s value. Each time a <variable> item is
found, the block is evaluated. The name of the variable is in $1 because of the group-
ing in the regular expression. Using the eval keyword, you get the value of the
variable with the name specified by $1. The result of the evaluation is returned from
the block, which substitutes the <variable> text with the value from the block.
E.2.1
Regular expression templates with ERb syntax
The following code shows the same technique but uses the ERb syntax for expression
replacement:
name = 'Jack'
cost = '$20'
template = 'Dear <%= name %>, You owe us <%= cost %>'      
output = template
output.gsub!( /<%=\s*(.*?)\s*%>/ ) {                      
eval( $1 )
}
print "#{output}\n"
Runs the string 
replacement code
q
Shows the template string
Makes a copy of the template
Replaces the <variable> sections 
with the contents of the variable
q
New 
template
Updated regular expression
C# PDF Convert: How to Convert Word, Excel, PowerPoint, Tiff
Support conversion to PDF from other documents, keeping original document page size. Support rendering image to a PDF document page, no change for image size.
change font size pdf text box; pdf custom paper size
C# PDF Annotate Library: Draw, edit PDF annotation, markups in C#.
Able to edit and change PDF annotation properties such as font size or color. Perform Various annotations on PDF Page using C#.NET Demo Codes.
pdf compression; change font size in pdf fillable form
325
A
P
P E N
D
I X
F
Patterns for regular 
expressions 
This book demonstrates generators written using Ruby. We understand that for a num-
ber of reasons Ruby may not be your language of choice for writing a generator.
Because regular expressions are such an instrumental part of code generation, this
appendix shows how you can use regular expressions in a variety of languages.
F.1
T
HE
EXAMPLES
Each language implements up to four of the following examples:
• Checking a string—In this example, we check the string file.txt to see if it
has the .txt extension.
• Reading key/value pairs—This example reads the key and value pairs from the
string a:1;b:2;c:3. The correct output is a = 1, b = 2, and  c = 3.
• Replacing tabs with commas—This example turns the string jack\td\ther-
rington into jack,d,herrington.
• Replacing values in a format string—This example parses the format string "Dear
<name>, You owe us <cost>", where <name> is Jack and cost is
$20. The correct output is Dear Jack, You owe us $20.
We believe these four examples show a set of use cases sufficient for you to get a good
feel for how each language handles regular expressions.
C# PDF Thumbnail Create SDK: Draw thumbnail images for PDF in C#.
public override Bitmap ConvertToImage(Size targetSize). Description: Convert the PDF page to bitmap with specified size. Parameters:
change font size pdf fillable form; best pdf compression
C# PDF File Split Library: Split, seperate PDF into multiple files
Divide PDF file into multiple files by outputting PDF file size. control, C# developers can easily and accurately disassemble multi-page PDF document into two
pdf change page size; adjust size of pdf file
326
APPENDIX F
P
ATTERNS
FOR
REGULAR
EXPRESSIONS
F.1.1
Ruby
The following code sections show the examples implemented in Ruby.
if ( "file.txt" =~ /[.]txt$/ )                               
print "File name matched\n"
else
print "File name did not match\n"
end
"a=1;b=2;c=3;".scan( /(.*?)=(.*?);/ ) { |key,value|        
print "#{key} : #{value}\n"                               
}
str = "jack\td\therrington".gsub( /\t/, "," )              
print "#{str}\n" 
str = "Dear <name>, You owe us <cost>"                     
str.gsub!( /<(.*?)>/ ) {                                   
if ( $1 == "name" )                                     
"jack"                                             
elsif ( $1 == "cost" )                                  
"$20"                                             
else                                                    
""                                                
end                                                     
}
print "#{str}\n"
F.1.2
Python
The following code sections show the examples implemented in Python.
import re
str = "field.txt"                                  
if re.search( ".txt$", str ):                      
print "File name matched\n"
else:
print "File name doesn't match\n"
Checking a string
Checks string for .txt at the end
Reading key/value pairs
Scans a string 
for the key/
value pairs
Prints the pairs
Replacing tabs with commas
Replace tabs 
with commas
Replacing values in a format string
Returns the 
value of the 
key
Outputs format
Replaces <keys> with their values
Checking a string
Checks the filename 
against the expression
Creates the example filename
VB.NET PDF File Split Library: Split, seperate PDF into multiple
Separate source PDF document file by defined page range in VB.NET class application. Divide PDF file into multiple files by outputting PDF file size.
best pdf compressor online; change font size pdf form reader
Create Thumbnail Winforms | Online Tutorials
editor: Click "Add" to add new items in thumbnail; Click "Swap" to change two items Multi-page Tiff Processing; RasterEdge OCR Engine; PDF Reading; Encode &
change font size in pdf form field; change page size pdf
T
HE
EXAMPLES
327
import re
myre = re.compile( "(.*?)=(.*?);" )                   
for item in myre.findall( "a=1;b=2;c=3;" ):           
print item[0], ":", item[1]                         
import re
print re.sub( "\t", ",", "jack\td\therrington" )       
import re
def rep( match ):                             
name = match.group( 1 )              
if ( name == "name" ):                
return "Jack"                 
if ( name == "cost" ):                
return "$20"                  
return ""
print re.sub( "<(.*?)>", rep, "Dear <name>, You owe us <cost>." )   
F.1.3
Perl
The following code sections show the examples implemented in Perl.
if ( "file.txt" =~ /[.]txt$/ )                  
{
print "File name matched\n" 
}
else
{
print "File name did not match\n"
}
$input = "a=1;b=2;c=3;";                            
while( $input =~ /(.*?)=(.*?);/g )                 
{
print "$1 : $2\n";                               
}
Reading key/value pairs
Finds and prints key/value 
pairs in the string
Creates the expression object
Replacing tabs with commas
Replaces tabs 
with commas
Replacing values in a format string
Returns the 
value of any 
key
Replaces key
items in the
string using
rep()
Checking a string
Checks the file name against 
the regular expression
Reading key/value pairs
Creates the data string
Runs the expression 
across the data string
Prints any 
groups it finds
328
APPENDIX F
P
ATTERNS
FOR
REGULAR
EXPRESSIONS
$str = "jack\td\therrington";
$str =~ s/\t/,/g;                             
print "$str\n";
sub value($)                               
                                         
my ( $key ) = @_;                        
return 'Jack' if ( $key eq 'name' );
return '$20' if ( $key eq 'cost' );
return '';
}
$str = 'Dear <name>, You owe us <cost>'; 
$str =~ s/<(.*?)>/value($1)/eg;               
print "$str\n"; 
F.1.4
Java
The following code sections show the examples implemented in Java. These examples
use the java.util.regex library from the 1.4 release of the JDK.
import java.util.regex.*;
class Regex1
{
public static void main( String args[] )
{
Pattern pat = Pattern.compile( "\\S*.txt$" );          
Matcher mat = pat.matcher( "file.txt" );              
if ( mat.matches() ) {                                
System.out.println( "File matches" );
} else {
System.out.println( "File does not match" );
}
}
}
import java.util.regex.*;
class Regex2
{
public static void main( String args[] )
{
Pattern pat = Pattern.compile( "(.*?)=(.*?);" );     
Matcher mat = pat.matcher( "a=1;b=2;c=3;" );         
Replacing tabs with commas
Replaces tabs with commas
Replacing values in a format string
Returns the value 
for a particular key
Scans and replaces 
keys with value()
Checking a string
Checks for matches
Runs the object 
against the string
Creates the 
expression object
Reading key/value pairs
Runs the object 
against the string
Creates the 
expression object
T
HE
EXAMPLES
329
while( mat.find() )
{
System.out.println( mat.group(1) + " : " + mat.group( 2 ) );    
}
}
}
import java.util.regex.*;
class Regex3
{
public static void main( String args[] )
{
String out = new String( "jack\td\therrington" );            
Pattern pat = Pattern.compile( "\\t" );                      
out = (pat.matcher( out )).replaceAll( "," );                
System.out.println( out );
}
}
import java.util.regex.*;
class Regex4
{
public static void main( String args[] )
{
String str = new String( "Dear <name>, You owe us <cost>" );    
Pattern pat = Pattern.compile( "<(.*?)>" );                     
Matcher mat = pat.matcher( str );                               
while( mat.find() )
{
String key = mat.group(1);                          
if ( key.compareTo( "name" ) == 0 )                
str = mat.replaceFirst( "jack" );                 
else if ( key.compareTo( "cost" ) == 0 )            
str = mat.replaceFirst( "\\$20" );                
else                                                
str = mat.replaceFirst( "" );                     
mat = pat.matcher( str );                           
}
System.out.println( str );
}
}
Prints the
groups
Replacing tabs with commas
Original string
Code that replaces 
tabs with commas
Expression object
Replacing values in a format string
Replaces the 
found group
Reruns the match
Runs the 
initial match
Creates the 
expression object
Contains the
original string
330
APPENDIX F
P
ATTERNS
FOR
REGULAR
EXPRESSIONS
F.1.5
C#
The following code sections show the examples implemented in C#.
using System;
using System.Text.RegularExpressions;
class Regex1
{
static void Main()
{
Regex r = new Regex( "[.]txt$" );                              
if ( r.Match( "file.txt" ).Success ) {                          
Console.WriteLine( "File name matched" );
} else {
Console.WriteLine( "File name did not match" );
}
}
}
using System;
using System.Text.RegularExpressions;
class Regex2
{
static void Main()
{
Regex r = new Regex( "(?<key>.*?)=(?<value>.*?);" );            
MatchCollection matches = r.Matches( "a=1;b=2;c=3;" );         
foreach ( Match match in matches )                             
{
Console.WriteLine(                                            
match.Groups["key"] + " : " + match.Groups["value"]         
);
}
}
}
using System;
using System.Text.RegularExpressions;
class Regex3
{
static void Main()
{
Checking a string
Checks the object 
against the string
Creates the 
expression object
Reading key/value pairs
Prints out key 
and value groups
Creates the 
expression 
object
Runs the 
expression 
against the 
string
Loops through 
matches found
Replacing tabs with commas
T
HE
EXAMPLES
331
Regex r = new Regex( "\t" );                                    
String str = r.Replace( "jack\td\therrington", "," );           
Console.WriteLine( str );
}
}
using System;
using System.Text.RegularExpressions;
class Regex4
{
public static String myEval( Match mat )                          
                                                                     
if ( mat.Groups[ "key" ].ToString() == "name" )                      
return "Jack";
if ( mat.Groups[ "key" ].ToString() == "cost" )
return "$20";
return "";
}
static void Main()
{
Regex r = new Regex( "<(?<key>.*?)>" );                              
String str = r.Replace(                                              
"Dear <name>, You owe us <cost>",                
new MatchEvaluator( myEval ) );
Console.WriteLine( str );
}
}
F.1.6
C
The following code sections show two of the four examples implemented in C. We
excluded the substitution examples because they were too large. This code uses the Perl
Compatible Regular Expression library (pcre).
#include <stdio.h>
#include <pcre.h>
int main( int argc, char *argv[] )
{
pcre *re;
const char *error;
int erroffset, rc, ovector[30];
char *str = "file.txt";
re = pcre_compile( "[.]txt$", 0, &error, &erroffset, NULL );        
Replaces tabs 
with commas
Creates the expression object
Replacing values in a format string
Is called each time a 
match is found; returns 
value inserted into text
Builds the regular 
expression object
Replaces keys dynamically
Checking a string
Compiles the
expression
Documents you may be interested
Documents you may be interested