Hudson Lacerda (2004)
@@LEIA-ME
@@
$
Este documento apresenta os elementos bsicos da linguagem PostScript.

Por enquanto, apenas transcrevem-se trechos de um documento em HTML
escritos por Peter Weingartner. O original pode ser encontrado em:

http://www.cs.indiana.edu/docproject/programming/postscript/postscript.html

Posteriormente ser preparada uma verso em portugus.

----

Neste documento, os operadores so descritos da seguinte maneira:

arg-1 arg-2 ... arg-n operador res-1 res-2 ... res-n

Isso significa que o operador utiliza os argumentos listados  sua
esquerda e retorna os resultados indicados  direita.

Se um operador no utiliza argumentos ou no retorna resultados,
um trao (-)  utilizado para indicar isso.

Exemplo:

coord-x coord-y moveto -

O operador moveto toma dois argumentos (coord-x e coord-y) e
realiza uma tarefa sem retornar valores como resultado.

$

@@PostScript
$
PostScript is a programming language optimized for printing graphics
and text (whether on paper, film, or CRT is immaterial). In the jargon
of the day, it is a page description language. It was introduced by
Adobe in 1985 and first (to my knowledge) appeared in the
Apple LaserWriter. The main purpose of PostScript was to provide a
convenient language in which to describe images in a device independent
manner. This device independence means that the image is described
without reference to any specific device features (e.g. printer
resolution) so that the same description could be used on any
PostScript printer (say, a LaserWriter or a Linotron) without
modification. In practice, some PostScript files do make assumptions
about the target device (such as its resolution or the number of paper
trays it has), but this is bad practice and limits portability. 

The language itself, which is typically interpreted, is stack-based in
the same manner as an RPN calculator. A program pushes arguments
to an operator onto a stack and then invokes the operator.
Typically, the operator will have some result which is left at the
top of the stack. As an example, let us say we want to multiply
12 and 134. We would use the following PostScript code:


12 134 mul

The first two words '12' and '134' push the numbers 12 and 134 onto
the stack. 'mul' invokes the multiply operator which pops two values
off the stack, multiplies them, and then pushes the result back
onto the stack. The resulting value can be left there to be used by
another operator later in the program. 

To follow the conventions used by Adobe in their manuals, I will
synopsize operators using the following scheme:
arg-1 arg-2 ... operator result.
This scheme means that, to use operator, you must push arguments
arg-1, arg-2, and so on before invoking the operator. operator
will return the result: result. Many operators return no result
(they have some side-effect); these will be shown as returning '-'.
$









PostScript Operators


-----------------------------------------------------------------------

@@add
$
Operator: add

num1 num2 add num3

This operator returns the addition of the two arguments.


Errors:
	stackunderflow
	typecheck
	undefinedresult 

See also: 
	div
	mul
	sub 
$



-----------------------------------------------------------------------

@@arc
$
Operator: arc

x-coord y-coord r ang1 ang2 arc - 

This operator adds an arc to the current path. The arc is generated by
sweeping a line segment of length r, and tied at the point (x-coord
y-coord), in a counter-clockwise direction from an angle ang1 to an
angle ang2. Note: a straight line segment will connect the current
point to the first point of the arc, if they are not the same.

Errors:
	limitcheck
	stackunderflow
	typecheck 
$
-----------------------------------------------------------------------

@@begin
$
Operator: begin

dict begin - 

This operator pushes the dictionary dict onto the dictionary stack.
Where it can be used for def and name lookup. This operator allows an
operator to set up a dictionary for its own use (e.g. for local
variables). 

Errors: 
	dictstackoverflow
	invalidaccess
	stackunderflow
	typecheck 
$

-----------------------------------------------------------------------

@@bind
$
Operator: bind

procedure1 bind procedure2 

The bind operator goes through procedure1 and replaces any operator
names with their associate operators. Names which do not refer to
operators are left alone. Operators within procedure1 which have
unrestricted access will have bind called on themselves before they
are inserted into the procedure. The new procedure with operators
instead of operator names is returned on the stack as procedure2. 

The main effect and use of this operator is to reduce the amount of
name lookup done by the interpreter. This speeds up execution and ties
down the behavior of operators.

Errors: 
	typecheck 
$



-----------------------------------------------------------------------

@@clip
$
Operator: clip

- clip - 

This operator intersects the current clipping path with the current
path and sets the current clipping path to the results. Any part of a
path drawn after calling this operator which extends outside this new
clipping area will simply not be drawn. If the given path is open,
clip will treat it as if it were closed. Also, clip does not destroy
the current path when it is finished... it may be used for other
activities.

It is important to note that there is no easy way to restore the clip
path to a larger size once it has been set. The best way to set the
clip path is to wrap it in a gsave and grestore pair.

Errors: 
	limitcheck 
$
-----------------------------------------------------------------------

@@closepath
$
Operator: closepath

- closepath - 

This operator adds a line segment to the current path from the current
point to the first point in the path. This closes the path so that it
may be filled. 

Errors:
	limitcheck 

Also see the following operators: 
	newpath
	moveto
	lineto 
$
-----------------------------------------------------------------------


@@charpath
$
Operator: charpath

string bool charpath -

This operator takes the given string and appends the path which the
characters define to the current path. The result is can be used as
any other path for stroking, filling, or clipping.

The boolean argument informs charpath what to do if the font was not
designed to be stoked. If the boolean is true, the path will be
modified to be filled and clipped (but not stroked). If the boolean is
false, the path will be suitable to be stroked (but not filled or
clipped). 


Errors:
	limitcheck
	nocurrentpoint
	stackunderflow
	typecheck 

See also: 
	clip
	fill
	show
	stroke 
$
-----------------------------------------------------------------------

@@curveto
$
Operator: curveto

x1 y1 x2 y2 x3 y3 curveto -

This operator draws a curve from the current point to the point
(x3, y3) using points (x1, y1) and (x2, y2) as control points. The
curve is a Bzier cubic curve. In such a curve, the tangent of
the curve at the current point will be a line segment running from
the current point to (x1, y1) and the tangent at (x3, y3) is the line
running from (x3, y3) to (x2, y2).

Errors:
	limitcheck
	nocurrentpoint
	stackunderflow
	typecheck 

See also: 
	arc
	lineto
	moveto 
$



-----------------------------------------------------------------------

@@def
$
Operator: def

name value def - 

This operator associates the name with value in the dictionary at the
top of the dictionary stack. This operator essentially defines names
to have values in the dictionary and is used to define variables and
operators. 

Errors: 
	dictfull
	invalidaccess
	limitcheck
	stackunderflow
	typecheck
	VMerror 
$
-----------------------------------------------------------------------

@@div
$
Operator: div

num1 num2 div num3

This operator returns the result of dividing num1 by num2. The result
is always a real.

Errors:

	stackunderflow
	typecheck
	undefinedresult 

See also: 
	add
	mul
	sub 
$
-----------------------------------------------------------------------

@@dup
$
Operator: dup

object dup object object 

This operate pushes a second copy of the topmost object on the operand
stack. If the object is a reference to an array, string, or similar
composite object, only the reference is duplicated; both references
will still refer to the same object.

Errors: 
	stackoverflow
	stackunderflow

See also: 
	exch
	index
	pop 
$


-----------------------------------------------------------------------

@@end
$
Operator: end

- end - 

This operator pops the topmost dictionary off of the dictionary stack.
The dictionary below it becomes the new current dictionary.

Errors: 
	dictstackunderflow 
$



-----------------------------------------------------------------------

@@exch
$
Operator: exch

value1 value2 exch value2 value1

This operator simply exchanges the top two items on the operand stack.
It does not matter what the operands are.

Errors: 
	stackunderflow 

See also: 
	dup
	index
	pop 

$



-----------------------------------------------------------------------

@@fill
$
Operator: fill

- fill - 

This operator closes and fills the current path with the current color.
Any ink within the path is obliterated. Note that fill blanks out the
current path as if it had called newpath. If you want the current path
preserved, you should use gsave and grestore to preserve the path.

Errors: 
	limitcheck 
$
-----------------------------------------------------------------------

@@findfont
$
Operator: findfont

name findfont font 

This operator looks for the named font in the font dictionary. If it
finds the font, it pushes the font on the stack for later processing.
It signals an error if the font can not be found.

Errors: 
	invalidfont
	stackunderflow
	typecheck 

Also see the following operators: 
	scalefont
	setfont 
$

-----------------------------------------------------------------------

@@for
$
Operator: for

initial increment limit proc for -

This operator will execute proc repeatedly. The first time proc is
executed, it will be given initial as the top operand. Each time it is
executed after that, the top operand will be incremented by increment.
This process will continue until the argument would have exceeded
limit. 

Errors:
	stackoverflow
	stackunderflow
	typecheck 

See also: 
	if
	ifelse 
$


----------------------------------------------------------------------

@@grestore
$
Operator: grestore

- grestore - 

Sets the current graphics state to the topmost graphics state on
graphics state stack and pops that state off the stack. This operator
is almost always used in conjunction with gsave.

See also:
	gsave
$

-----------------------------------------------------------------------

@@gsave
$
Operator: gsave

- gsave - 

This operator pushes a copy of the current graphics state onto the
graphics state stack. The graphics state consists of (among other
things): 
	Current Transformation Matrix
	Current Path
	Clip Path
	Current Color
	Current Font
	Current Gray Value 

gsave is typically used with grestore whenever you need to change the
graphics state temporarily and return to the original.

Errors: 
	limitcheck 

See also:
	grestore
$
-----------------------------------------------------------------------

@@if
$
Operator: if

bool proc if -

This operator will execute proc if bool is true. 

Errors:
	stackunderflow
	typecheck 
$



-----------------------------------------------------------------------

@@ifelse
$
Operator: ifelse

bool proc1 proc2 ifelse -

This operator will execute proc1 if bool is true and proc2 otherwise.

Errors:
	stackunderflow
	typecheck 
$
-----------------------------------------------------------------------

@@index
$
Operator: index

value_n ... value_0 n index value_n ... value_0 value_n

This operator grabs the nth item off the operand stack (item 0 is the
one just under the index you push on the stack for the operator) and
pushes it on top of the stack.

Errors: 
	rangecheck
	stackunderflow
	typecheck 

See also: 
	dup
	exch
	pop 
$



-----------------------------------------------------------------------

@@lineto
$
Operator: lineto

x-coord y-coord lineto - 

This operator adds a line into the path. The line is from the current
point to the point (x-coord y-coord). After the line is added to the
path, the current point is set to (x-coord y-coord). It is an error to
call lineto without having a current point.

Errors: 
	limitcheck
	nocurrentpoint
	stackunderflow
	typecheck 

Also see the following operators: 
	rlineto
	moveto
	rmoveto
	curveto
	arc
	closepath 
$
-----------------------------------------------------------------------

@@moveto
$
Operator: moveto

x-coord y-coord moveto - 

This operator moves the current point of the current path to the given
point in user space. If a moveto operator immediately follows another
moveto operator, the previous one is erased. 

Errors: 
	limitcheck
	stackunderflow
	typecheck 

Also see the following operators: 
	rmoveto
	lineto
	curveto
	arc
	closepath 
$


----------------------------------------------------------------------

@@mul
$
Operator: mul

value1 value2 mul product 

This operator multiplies the first two operands on the stack and pushes
the result back onto the stack. The result is an integer if both
operands are integers and the product is not out of range. If the
product is too big, or one of the operands is a real, the result will
be a real. 

Errors: 
	stackunderflow
	typecheck
	undefinedresult 
$
-----------------------------------------------------------------------

@@newpath
$
Operator: newpath

- newpath - 

The newpath operator clears out the current path and prepares the
system to start a new current path. This operator should be called
before starting any new path, even though some operators call it
implicitly.
$
-----------------------------------------------------------------------

@@pop
$
Operator: pop

value pop -

This operator just removes the top-most item off of the operand stack.

Errors: 
	stackunderflow

See also: 
	dup
	exch
	index 
$
-----------------------------------------------------------------------

@@restore
$
Operator: restore

state restore - 

This restores the total state of the PostScript system to the state
saved in state.

Errors: 
	invalidrestore
	stackunderflow
	typecheck 

See also:
	save 
$
-----------------------------------------------------------------------

@@rlineto
$
Operator: rlineto

dx dy rlineto - 

This operator adds a line into the path. The line is from the current
point to a point found by adding dx to the current x and dy to the
current y. After line is added to the path, the current point is set
to the new point. It is an error to call lineto without having a
current point. 

Errors: 
	limitcheck
	nocurrentpoint
	stackunderflow
	typecheck 

Also see the following operators: 
	lineto
	moveto
	rmoveto
	curveto
	arc
	closepath 
$
-----------------------------------------------------------------------

@@rmoveto
$
Operator: rmoveto

dx dy rmoveto - 

This operator moves the current point of the current path by adding dx
to the current x and dy to the current y.

Errors: 
	limitcheck
	stackunderflow
	typecheck 

Also see the following operators: 
	moveto
	lineto
	curveto
	arc
	closepath 
$
----------------------------------------------------------------------

@@rotate
$
Operator: rotate

angle rotate -

This operator has the effect of rotating the user space
counter-clockwise by angle degrees (negative angles rotate clockwise).
The rotation occurs around the current origin.

Errors:
	rangecheck
	stackunderflow
	typecheck 

See also: 
	scale
	translate 
$
-----------------------------------------------------------------------

@@save
$
Operator: save

- save state 

This operator gathers up the complete state of the PostScript system
and saves it in state.

Errors:
	limitcheck
	stackoverflow 

See Also: 
	restore 
$
-----------------------------------------------------------------------

@@scale
$
Operator: scale

sx sy scale -

This operator has the effect of scaling the user coordinates. All
coordinates will be multiplied by sx in the horizontal direction, and
sy in the vertical.

The origin will not be affected by this operation.

Errors:
	rangecheck
	stackunderflow
	typecheck 

See also: 
	rotate
	translate 
$


----------------------------------------------------------------------

@@scalefont
$
Operator: scalefont

font size scalefont font 

This operator takes the given font and scales it by the given scale
factor. The resulting scaled font is pushed onto the stack. A size of
one produces the same sized characters as the original font, 0.5
produces half-size characters, and so on.

Errors: 
	invalidfont
	stackunderflow
	typecheck
	undefined 

Also see the following operators: 
	findfont
	setfont 
$
-----------------------------------------------------------------------

@@setfont
$
Operator: setfont

font setfont - 

This operator sets the current font to be font. This font can be the
result of any font creation or modification operator. This font is
used in all subsequent character operations like show.

Errors:
	invalidfont
	stackunderflow
	typecheck 

Also see: 
	findfont
	scalefont 
$

-----------------------------------------------------------------------

@@setgray
$
Operator: setgray

gray-value setgray - This operator sets the current intensity of the
ink to gray-value. gray-value must be a number from 0 (black) to 1
(white). This will affect all markings stroked or filled onto the page.
This applies even to path components created before the call to setgray
as long as they have not yet been stroked. 

Errors:
	stackunderflow
	typecheck
	undefined 
$
-----------------------------------------------------------------------

@@setlinewidth
$
Operator: setlinewidth

width setlinewidth - 

This operator sets the width of all lines to be stroked to width, which
must be specified in points. A line width of zero is possible and is
interpreted to be a hairline, as thin as can be rendered on the given
device.

Errors:
	stackunderflow
	typecheck 
$
-----------------------------------------------------------------------

@@show
$
Operator: show

string show -

This operator draws the given string onto the page. The current
graphics state applies, so the current font, fontsize, gray value, and
current transformation matrix all apply.

The location for the text is set by the current point. The current
point will specify the leftmost point of the baseline for the text.

Errors:
	invalidaccess
	invalidfont 
	nocurrentpoint
	rangecheck 
	stackunderflow
	typecheck 

See also: 
	charpath
	moveto
	setfont 
$
-----------------------------------------------------------------------

@@showpage
$
Operator: showpage

- showpage - 

This operator commits the current page to print and ejects the page
from printing device. showpage also prepares a new blank page. 
$

-----------------------------------------------------------------------

@@stroke
$
Operator: stroke

- stroke - 

This operator draws a line along the current path using the current
settings. This includes the current line thickness, current pen color,
current dash pattern, current settings for how lines should be joined,
and what kind of caps they should have. These settings are the settings 
at the time the stroke operator is invoked.

A closed path consisting of two or more points at the same location is
a degenerate path. A degenerate path will be drawn only if you have set 
the line caps to round caps. If your line caps are not round caps, or
if the path is not closed, the path will not be drawn. If the path is
drawn, it will appear as a filled circle center at the point. 

Errors: 
	limitcheck 
$
-----------------------------------------------------------------------

@@sub
$
Operator: sub

num1 num2 sub num3

This operator returns the result of subtracting num2 from num1.

Errors:
	stackunderflow
	typecheck
	undefinedresult 

See also: 
	add
	div
	mul 
$


-----------------------------------------------------------------------

@@translate
$
Operator: translate

x-coord y-coord translate -

This operator has the affect of moving the origin to the point
(x-coord, y-coord) in the current user space.

Errors:
	rangecheck
	stackunderflow
	typecheck 

See also: 
	rotate
	scale 
$


-----------------------------------------------------------------------
@@ERRORS
$
configurationerror 
	setpagedevice request can not be satisfied 
dictfull 
	dictionary is full 
dictstackoverflow 
	too many "begin"s 
dictstackundeflow 
	too many "end"s 
invalidaccess 
	access attribute violated (e.g. attempted to write a
	read-only object) 
invalidfont 
	bad font name or dictionary 
invalidrestore 
	the saved state object is too old to "restore" 
ioerror 
	some kind of error during input or output 
limitcheck 
	some implementation-dependent size restriction has been
	exceeded 
nocurrentpoint 
	the current point is not defined, yet 
rangecheck 
	operand is too big or too small 
stackoverflow 
	the stack was full before the last push 
stackunderflow 
	you tried to pop from an empty stack 
syntaxerror 
	PostScript's syntax has been violated 
typecheck 
	operand is of the wrong type 
undefined 
	name is not defined in any dictionary on the stack 
undefinedresult 
	the result of the last numeric operation is invalid
	(e.g. division by zero) 
VMerror 
	virtual memory full 
$

-----------------------------------------------------------------------

@@GRAPHICS
$
Graphics Concepts

There are a few concepts that you need to know about before we dive
into the language itself. These concepts are the concepts PostScript
uses to describe and manipulate images on a page. There are really only 
a few. 


Device Space 

This is the coordinate space understood by the printer hardware. This
coordinate system is typically measured in terms of the device's
resolution. There is really nothing else that can be said about this
space, as PostScript programs are typically not expressed using it.

User Space 

This is the coordinate system used by PostScript programs to describe
the location of points and lines. User space is essentially the same as 
the first quadrant of the standard coordinate system used in high
school math classes. Point (0, 0) is in the lower left corner.
Coordinates are real numbers, so there is no set resolution in user
space. The interpreter automatically converts user space coordinates to 
device space. 

Current Transformation Matrix 

The transformation of user space coordinates to device space
coordinates is done through the current transformation matrix. This
matrix is a three by three matrix that allows the user to rotate,
scale, and translate the entire user space within the device space.
This is the source of a lot of PostScript's power, as will be
demonstrated later. 

Path 

A path is a collection of (possibly disjoint) line segments and curves
arranged on the page. The path does not describe actual ink on the
paper; it merely describes an imaginary tracing over the page. There
are operators which allow the user to draw ink along the path (stroke),
fill an enclosed path with ink (fill), or clip out all future images
that are outside the path (clip). 

Current Path 

This is the path that the PostScript program is creating at the moment. 
The current path is assembled piece by piece.

Clipping Path 

The PostScript rendering system will ignore any part of a line segment,
curve, or bitmap that extends outside a certain region; it will only
draw the parts of those elements which are within the region. The
region is described by a path called the clipping path. The clipping
path is usually a rectangle about a quarter of an inch in from the edge 
of the page, but it can easily be set by the user to an arbitrary path. 

Graphics State 

This is a collection of various settings that describe the current
state of the graphics system. Things like the current path, the current 
font, and the current transformation matrix make up the graphics state. 
Often, a program will need to temporarily save a graphics state to be
used later. There are a couple of ways of doing this, but the easiest
is to push the state onto a special graphics state stack and pop it
back later. This can be accomplished with the gsave, and grestore
operators. 
$



----------------------------------------------------------------------

@@LANGUAGE
$
Language Concepts

As a programming language, PostScript is particularly simple. There are
really only a few concepts that need to be sketched out. 



Comment 

A comment in PostScript is any text preceded by a '%'. The special
comment '%!' as the first two characters of a PostScript program is
seen as a tag marking the file as PostScript code by many systems
(including Unix's lpr command). It is a good idea to start every
PostScript document with a '%!'... doing so will ensure that every
spooler and printer the document may encounter will recognize it as
PostScript code. 

Stack 

There are several stacks in a PostScript system, but only two are
important for this guide: the operand stack, and the dictionary stack.
The operand stack is where arguments to procedures (or operators, in
PostScript jargon) are pushed prior to use. The dictionary stack is for 
dictionaries, and it provides storage for variables. 

Dictionary 

A dictionary is a collection of name-value pairs. All named variables
are stored in dictionaries. Also, all available operators are stored in 
dictionaries along with their code. The dictionary stack is a stack of
all currently open dictionaries. When a program refers to some key, the 
interpreter wanders down the stack looking for the first instance
of that key in a dictionary. In this manner, names may be associated
with variables and a simple form of scoping is implemented.
Conveniently, dictionaries may be given names and be stored in other
dictionaries. 

Name 

A name is any sequence of characters that can not be interpreted as a
number. With the exception of spaces and certain reserved characters
(the characters '(', ')', '[', ']', '<', '>', '{', '}', '/', and '%')
any character may be part of a name. The name may even start with
digits (1Z is a name, for example), but you can get into problems with
them (1E10 is a real number). A name is seen as being a reference to
some value in a dictionary on the dictionary stack.

It should be noted that there are a couple of names that are legal in
PostScript which do not follow the above definition. These are the '['
and the ']' operators. Yes, they are operators and are stored in the
dictionary. Some other names that might surprise you are: '=', '==',
'<<', and '>>'.

If a name is preceded by a slash, PostScript will place the name on the 
stack as an operand. If the name has no slash, the interpreter will
look up its value in the dictionary stack. If the value is a procedure
object, the procedure will be evaluated. If the value is not a
procedure, the value will be pushed onto the operand stack.

Number 

PostScript supports integers and reals. You can express numbers in two
forms: radix form, and scientific notation. Radix form is a number of
the form radix#value where radix specifies the base for value.
Scientific notation is the standard mantissaEexponent form used in most 
languages. 

String 

Strings are, of course, just strings of characters. There are two ways
of expressing strings in Level 1 PostScript. The most common way is to
wrap your text in parentheses. For example the string "This is a
string" would be written as (This is a string). You can also express a
string as hexidecimal codes in angle brackets. For example, the string
"ABC" would be expressed as <414243>. There are several escape codes
that may be used in the parenthesis format of strings.

Array 

Arrays in PostScript are like arrays in any other language. Arrays may
contain objects of different type, and they are written as a list of
objects surrounded by brackets. For instance, [12 /Foo 5] is a three
element array containing the number 12, the name Foo, and the number 5.
 
Procedure 

A procedure is your way of defining new operators. A procedure is an
array that is executable and is written with braces rather than
brackets. For example, a procedure to square the top element on the
stack might be written as: {dup mul}. We can define this procedure to
be the square operator with: /square {dup mul} def.
$

----------------------------------------------------------------------








Index of Operators



add arc begin bind clip charpath closepath curveto def div dup end exch fill for findfont grestore gsave if ifelse index lineto moveto mul newpath pop restore rlineto rmoveto rotate save scale scalefont setfont setgray setlinewidth show showpage stroke sub translate 



