more PostScript info

Quick Reference for Ghostscript entities

Types,   Numbers,   Special characters,   Stacks,   Arrays,
Coordinate system,   Operators,   ALPHABETICAL OPERATOR INDEX.

DEFINITIONS: TYPES etc.

  • integer
  • real = machine-real number
  • number = either of the above
  • array = ordered set of objects
  • matrix = special 6-element numerical array [a b c d x y] which represents matrix
                            [ a  b  0 ]
                            [ c  d  0 ]
                            [ x  y  1 ]
    
  • character = integer between 0 and 255, inclusive
  • string = array of characters
  • boolean = true or false
  • name = identifying symbol or "key"
  • dictionary = table of name/value pairs
  • procedure = executable array
  • any = any of the above
  • mrk = mark = array delimiter

NUMBERS

(signed) integers
        127   -65   +14   0   9999
reals
        3.14   -2.   0.0   -.55   47.2e10   3E-3
radix numbers
        8#1727          ( = 1727 base 8)
        16#F07E         ( = F07E base 16)
    The base must be in [2...36], and digits in [0...(base-1)],
    where the 36 possible digits are 0...9A...Z
    Characters can be expressed as integers 8#000...8#377

SPECIAL CHARACTERS

%   (   )   <   >   [   ]   /   {   }


THE STACKS

There are four distinct stacks which represent the state of a Ghostscript program;
  • Graphics stack (graphics states)
    each graphics state includes the transformation matrix, current path, font, current point, clipping path, and the line and color attributes.
  • Dictionary stack (dictionary objects; name search path)
    Initially there are 2 dictionaries on this stack, and they can never be popped off the stack. At the bottom is systemdict, which includes the definitions of all the basic Ghostscript operators. The userdict is above that, including all global user-defined (or user-redefined) operators. Beyond these two, additional dictionaries can be pushed and popped. The top element of this stack is called the current dictionary.
  • Execution stack (partially-executed procedures)
  • Operand stack (arbitrary objects)
If the reference to a "stack" is unqualified then it probably means the operand stack.
Fonts are special dictionaries with their own directory, added using "definefont" and read with "findfont".

ARRAYS and INDICES

Arrays are 1-dimensional collections of objects, and an array can contain elements of all different types. Arrays are indexed from 0; an array of length n has indices from 0 to (n-1). Since [square brackets] delimit arrays in Ghostscript notation, an array of length n can be represented as [e0 e1 e2 ... en-1]. The element ei-1 may be referred to as the "ith" element in the references below. (So the 1st element is e0, and the 2nd element is e1. Get used to it.)

Procedures are actually "executable arrays", and strings are arrays whose elements are all characters (that is, integers in the range 0 to 255).


Operators, by category

In the "usage" examples which follow, the following operands are assumed to be of the indicated type:
		     i, j, n = integer
		     x, y, z = any number, real or integer
		     a, b, c = any type of object
		           e = element of an array
		    STR, str = longer and shorter string
		    ARY, ary = longer and shorter array

MATH

(return to Index)

abs

add

aload

pushes all elements of the array onto stack, followed by array itself

and

binary bitwise and (à la C)

atan

awidthshow

prints string, combining special effects of ashow and widthshow

bitshift

bytesavailable

number of bytes available for reading. EOF=-1

ceiling

charpath

adds character path outlines of given string, without stroking them, to the current path

cos

count

counts operands, pushes number onto stack

div

exp

floor

idiv

ln

log

mod

mul

neg

not

bitwise complement

or

bitwise inclusive-or

rand

returns a pseudorandom integer n < 2^31. Don't rely on this random-number-generator being of high quality...

round

rrand

returns the current seed for the random-number-generator, which can be used later with srand

sin

sqrt

srand

makes n the seed value for the random-number-generator

sub

truncate

y is the same type as x, but with the fraction part dropped

xor

bitwise exclusive-or

COORDINATE SYSTEM

(return to Index)
"CTM" refers to the Current Transformation Matrix, which converts given coordinates into "page coordinates". The CTM is originally the identity matrix [1 0 0 1 0 0] (see note on matrices) which maps (0,0) ("user space") onto the lower left corner of the page ("device space") and (72,72) onto the point 1" to the right and 1" up, etc. The coordinate system -- actually the CTM -- can be altered usually using scale, rotate, and translate.

scale

alters the coordinate axes (CTM) by stretching the x-axis by factor sx and that of the y-axis by factor sy

rotate

rotates coordinate axes (CTM) by z degrees

translate

translates coordinate axes (CTM) by (x,y)

scale

replaces value of given matrix with one in which the coordinate system is scale by z degrees

rotate

replaces value of given matrix with one in which the coordinate system is rotated by z degrees

translate

replaces value of given matrix with one in which the coordinate system is translated by (x,y)

concat

updates CTM (current transformation matrix) with matrix X CTM

concatmatrix

replaces value of matr3 with matr1 X matr2

currentmatrix

replaces value of matrix with CTM

defaultmatrix

replaces value of matrix with the default transformaton matrix of current device, and pushes it onto stack

transform

transforms coordinates (x,y) using CTM

transform

transforms coordinates (x,y) using matrix

itransform

transforms coordinates (x,y) using the inverse of CTM

itransform

transforms coordinates (x,y) using the inverse of matrix

dtransform

transforms distance vector (x,y) using CTM

dtransform

transforms distance vector (x,y) using matrix

idtransform

transforms distance vector (x,y) using the inverse of CTM

idtransform

transforms distance vector (x,y) using the inverse of matrix

identmatrix

sets matr to [1 0 0 1 0 0]

initmatrix

sets the CTM to the default matrix

invertmatrix

returns mtrx2, which now is the inverse of mtrx1

matrix

creates an identity matrix

setmatrix

replaces CTM with given matrix. Don't use this

PATH CONSTRUCTION

(return to Index)

newpath

empties current path, undefines current point

currentpoint

coordinates of current graphics point

arc

appends counterclockwise circular arc to current path, possibly preceeded by straight segment: center (x,y), radius r, from theta = a1 to a2 (in degrees)

arcn

just like arc, but in clockwise direction

arcto

appends circular arc to current path, possibly preceeded by a straight segment; radius r, with tangent lines from current point to (x1,y1) to (x2,y2). The returned values are the coordinates of the two tangent points

curveto

appends Bezier cubic section, from current point (x0,y0) to point (x3,y3), onto the current path; (x3,y3) becomes the new current point. This curve follows equation
x = (1-t)^3 x0 + 3t(1-t)^2 x1 + 3t^2(1-t) x2 + t^3 x3
y = (1-t)^3 y0 + 3t(1-t)^2 y1 + 3t^2(1-t) y2 + t^3 y3
for parameter t, 0<=t<=1

lineto

appends a straight line segment from previous current point to new current point (x,y)

moveto

starts a new subpath at point (x,y)

rcurveto

like curveto, but the 3 x-y pairs are relative to current point (x0,y0)

rlineto

like lineto, but the x-y coordinate pair is a measurement relative to the current point (x0,y0), not absolute coordinates

rmoveto

like moveto, but the x-y coordinate pair is a measurement relative to the current point (x0,y0), not absolute coordinates

closepath

closes current path, appending a straight segment which connects the current point to starting point

charpath

adds character path outlines of given string, without stroking them, to the current path

clip

produces new (smaller) clipping path, by intersecting current clipping path with interior of current path

clippath

sets current path to current clipping path

eoclip

produces new (smaller) clipping path, by intersecting current clipping path with interior of current path, using the even-odd rule to determine the latter

flattenpath

replaces current path with the path where all "curveto" portions are replaced with equivalent "lineto" segments

initclip

replaces current clip path with default clip path (edges of page!)

pathbbox

returns the bounding box of the current path in current coordinate system; the x-y values of the lower-left and upper-right corners

pathforall

executes a procedure on each of the elements of the current path, in order; proc1 on all the "moveto" elements, proc2 on all the "lineto" elements, proc3 on the "curveto" elements, and proc4 on the "closepath" elements

reversepath

replaces current path with same path in reverse order

strokepath

replaces the current path with the outline of the shape that would result from using "stroke"

PAINTING

(return to Index)

fill

overpaints the interior of the current path

stroke

paints a line on the current path, using the current color, linewidth, dash pattern and other parameters

eofill

overpaints the interior of the current path, using the even-odd rule to determine "interior"

image

paints a rectangular bitmap image, executing proc repeatedly to obtain the image data as characters. W,H are the width and height of the image samle array, bps (bits per sample), either 1,2,4 or 8, indicates how the samples are packed into the character data. matrix indicates how to scale and position the image relative to a unit square at the current point.

imagemask

like "image", but uses image only as a 1-bps mask to control where to paint the current color. Instead of "bps", the 3rd parameter bool indicates whether to paint on the 1-bits ("true") or 0-bits ("false")

RELATIONAL / BOOLEAN

(return to Index)

true

false

eq

true if equal, otherwise false

not

logical negation

not

bitwise complement

ne

logical negation of eq

not

logical negation

not

bitwise complement

ge

numerical or lexical "greater than or equals"

gt

numerical or lexical "greater than"

le

numerical or lexical "less than or equals"

lt

numerical or lexical "less than"

or

logical disjunction

or

bitwise inclusive-or

and

binary bitwise and; i && j

and

logical conjunction

xor

logical disjunction

xor

bitwise exclusive-or

STRINGS

(return to Index)

string

creates a string of n characters, all ASCII 0

copy

replaces 1st n characters of STR with str, where length of str = n <= length of STR

cvi

interprets string, converts to an integer

cvr

interprets string and converts it to a real number

cvrs

Represents an integer (the integer part of non-negative value x) with radix j (1<j<36) and converts the representation to a string, returning the string and using it to overwrite initial substring of STR.

cvs

converts to string: produces text representation of a and returns that string, overwriting initial substring of STR

forall

executes proc on each character (integer 0-255) of str in turn

get

gets the (i+1)th character of str

getinterval

gets the substring of length n, starting with (i+1)th character

length

number of characters in string

put

replaces (i+1)th character of str with ASCII character n

putinterval

overwrites STR, starting at the (i+1)th character, with smaller string str

search

looks for a substring of STR which matches str, and returns strZ str strA true if successful: strA is the portion of STR which preceeds the match, and strZ is the portion which follows it. If there is no match, then instead this command returns STR false

anchorsearch

if str matches initial substring of STR; (remainder) (match) true otherwise; STR false

token

returns "true" is str contains anything besides white space (also returns pieces of original string). Otherwise, false.

GRAPHICS STATE

(return to Index)

showpage

sends current page to be printed, and starts a new, blank page

gsave

pushes a copy of the current graphics state onto the graphics-state stack.

grestore

pops the top element from the graphics-state stack and makes that the current graphics state

save

takes a "snapshot" of all virtual memory (values of all element of composite objects) and also duplicates current graphics state onto the graphics stack

restore

restores all values and graphics state to what they were when the most recent "save" was called; more recent graphics states and values are discarded and the virtual memory released

grestoreall

pops all graphics states more recent than the one preserved by the most recent "save" command (not gsave!) or the bottommost graphics state. Makes it the current graphics state

initgraphics

resets values in graphics state to their default: initmatrix newpath initclip 1 setlinewidth 0 setlinecap 0 setlinejoin [] 0 setdash 0 setgray 10 setmiterlimit

setdash

sets the dash pattern: ary contains the cyclic on-off distances of the dashes, which begin after an offset of x units from the current point. The array must consist of zero or more positive numbers. The command [] 0 setdash turns off dashing, making lines solid.

setflat

sets the flatness parameter to positive number x. This parameter controls how accurately curves are rendered into straight line segments

setgray

sets the current color parameter to a gray shade, where black = 0 <= x <= 1 = white.

sethsbcolor

sets the current color parameter according to hue, saturation and brightness values, which must each lie between 0 and 1. For bright colors use y=z=1. Hue (x) values: 0=red, 0.33=green, 0.67=blue

setlinecap

sets the line cap parameter: i=0: line ends are squared off at the endpoint i=1: line ends are rounded off i=2: line ends are given a projecting square cap

setlinejoin

set the line join parameter: i=0: corners are given a miter join (possibly beveled) i=1: corners are given a round join i=2: corners are given a bevel join

setlinewidth

sets the line width parameter to x>=0; line width 0 produces the thinnest possible device-resolution line

setmiterlimit

sets the miter limit parameter to x>=1, which limits the length of sharp corner miters

setrgbcolor

sets the current color parameter according to red, green, blue values, which must each lie between 0 and 1. Red = 1 0 0. Yellow = 1 1 0. Orange = 1 0.65 0.

setscreen

sets the current halftone screen definition

settransfer

sets the function which converts "user gray" values (0-1) into "device gray" values (0-1)

currentmiterlimit

current miter limit value

currentdash

current dash array and offset

currentflat

current flatness parameter
rr currenttransfer

currentgray

current brightness value (0-1)

currenthsbcolor

current color, HSB components

currentlinecap

current line cap pameter

currentlinejoin

current line join parameter

currentlinewidth

current line width value

currentrgbcolor

current color, RGB components

currentscreen

current halftone screen parameters

currenttransfer

current graphics transfer function

DICTIONARY

(return to Index)

begin

pushes given dictionary onto the dictionary stack (making it the current dictionary)

copy

copies all n elements of dict1 into length-zero dict2 (of maxlength >= n)

countdictstack

counts number of dictionaries currently on the dictionary stack; pushes number on stack

currentdict

copies current dictionary onto operand stack

def

(re)defines key with value, in the current dictionary

dict

creates new empty dictionary with maximum capacity n

dictstack

copies all n elements of the dictionary stack into ARY, and returns the length-n subarray

end

pops the current dictionary off the dictionary stack

systemdict

dictionary of basic Ghostscript operators

userdict

dictionary of global operators

errordict

dictionary of error handlers

FontDirectory

global dictionary of fonts

forall

executes proc on each key-value pair of dict, in some order

get

returns the value associated with key

known

whether key is an entry in dict

length

the number of defined key-value pairs

load

puts the value associated with key onto the stack, but does not execute it

maxlength

returns maximum capacity of dictionary

put

associates key with value a in dictionary

store

redefines key-value pair in the topmost dictionary where key can be found, or defines a new key-value pair in the current dictionary if no such key exists in any dictionary on the stack

where

(returns false if key is not found.)

TYPE / CONVERSION

(return to Index)

type

returns type name of a

cvi

converts to integer (truncates)

cvi

interprets string, converts to an integer

cvlit

converts to "literal" (not executable)

cvn

Converts to a name object, e.g. (abc) cvn ---> /abc Is executable if string was: (abc) cvx cvn ---> abc

cvr

converts to real value

cvr

interprets string and converts it to a real number

cvrs

Represents an integer (the integer part of non-negative value x) with radix j (1<j<36) and converts the representation to a string, returning the string and using it to overwrite initial substring of STR.

cvs

converts to string: produces text representation of a and returns that string, overwriting initial substring of STR

cvx

converts to executable: makes top stack object executable, not literal

executeonly

reduces access attribute of object (string or array) to "execute only" and not readable

rcheck

tests "readability" of object a, which is an array, string, file or dictionary

readonly

reduces access attribute of object (array, string, file or dictionary) to "read-only"

wcheck

tests "writeability" of object a, which is an array, string, file or dictionary

xcheck

tests "executability" of object a

CONTROL

(return to Index)

exit

terminates execution of innermost enclosing loop (for, loop, repeat, forall)

for

executes proc repeatedly, each time providing a numerical operand, starting with x1 and stepping toward x2 in increments of dx

forall

executes proc for each element of ary in turn

forall

executes proc on each character (integer 0-255) of str in turn

forall

executes proc on each key-value pair of dict, in some order

if

executes proc if bool=true

ifelse

executes proc1 if bool=true, otherwise executes proc2

loop

execute procedure repeatedly until the operator "exit" is encountered.

repeat

executes procedure n times

countexecstack

counts number of object on the execution stack; pushes number on stack

exec

pushes operand onto execution stack, executing it immediately

execstack

creates array of all n elements of the execution stack, overwriting initial substring of ARY

CHARACTER / FONT

(return to Index)

show

prints string, starting at the current point and using the current font specifications

stringwidth

calculates the change in the current point which would occur using "show", but doesn't actually draw the string

ashow

prints string, adding spaces (x,y) between characters

widthshow

prints string, adding space (x,y) after each occurence of the given character

awidthshow

prints string, combining special effects of ashow and widthshow

kshow

prints the characters of string one at a time, executing proc on consecutive pairs of characters at each step ("kernshow")

findfont

obtains font dictionary of given name

scalefont

scales font by linear factor y

makefont

applies matrix to font

setfont

establishes font to be used by "show"

currentfont

returns current font dictionary

definefont

registers font as a font dictionary of given name (key)

FontDirectory

global dictionary of fonts

OPERAND STACK

(return to Index)

copy

pops n, then duplicates top n operands

dup

duplicates top element of stack

exch

exchanges top 2 elements of stack

mark

same as "[", marking the initial bound of an array

clear

pops all operands from stack

cleartomark

pops all operands from stack until it reaches a "mark" (or `['), and pops the mark also

count

counts operands, pushes number onto stack

counttomark

counts operands since most recent mark, and pushes this number onto the stack

index

replaces j with a copy of stack element aj, the (j+1)th-topmost element of the remaining stack

pop

discards top element of stack

roll

pops n and i, then performs a circular shift on the top n operands by the amount i (positive or negative)

ARRAY

(return to Index)

[ ]

"[" (synonymous with "mark") marks the beginning of a sequence, and "]" completes the sequence, creating an array and leaving it on the operand stack

aload

pushes all elements of the array onto stack, followed by array itself

array

creates an n-length array of null objects

astore

determines the length of ary (say n), and then stores the top n stack objects into that array and leaves it on stack

copy

replaces 1st n elements of ARY with those of ary: length of ary = n <= length of ARY

forall

executes proc for each element of ary in turn

get

returns the (i+1)th element of ary

getinterval

returns a subarray of j elements starting with ei (the (i+1)th element of str)

length

returns the number of elements in array

put

replaces (i+1)th element of ary with a

putinterval

replaces elements of ARY with those of ary, starting with the (i+1)th element

FILE

(return to Index)

=

pops object from operand stack and sends its value (converted to text) to stdout

==

pops object from operand stack and sends it (converted to text) to stdout

bytesavailable

number of bytes available for reading. EOF=-1

closefile

closes the file

currentfile

returns current file object -- usually "stdin"

file

creates file object, for use by read or write or the previous 2 commands. str2 must be (r) or (w) for "read" or "write", and str1 is the file identifier, e.g. (%stdin)

flush

delivers any buffered characters

flushfile

delivers any buffered characters to writefile, or discards remaining characters from readfile

print

writes to standard output

prompt

writes prompt (interactive operation)

pstack

writes text version of each stack element to stdout, but doesn't change the stack

read

reads the next character from input file and pushes it (as an integer, 0-255) onto stack with "true" -- unless at end of file, in which case it returns only "false"

readhexstring

reads hex-pair characters (0-9A-Fa-f) from file to overwrite STR, ignoring any non-hex characters except End-of-file. Returns successfully-read string and either "false" (if EOF was encountered) or "true"

readline

reads a line of characters from file (terminated by \n), uses them to overwrite the initials characters of STR, and returns the line (as a string) and "true". ("False" if EOF was encountered before EOL). String STR must be long enough to accommodate line

readstring

read characters from file into STR until STR is full or EOF. Returns read portion (as a string) and either "true" or "false", depending on whether EOF was encountered. ALL characters are read literally, including newline

run

executes contents of file represented by str

stack

writes text version of each stack element to stdout, but doesn't change the stack

status

whether named file is still valid (open)

write

appends a single character to output file. char is an integer between 0 and 255

writehexstring

writes string to file as hex digits

writestring

writes string to file