ATROFFTutorial BrianW.Kernighan Typesetting Textformatting NROFF ABSTRACT troffisatext-formattingprogramfordrivingtheGraphicSystemsphoto-typesetterontheUNIX◯randGCOSoperatingsystems.Thisdeviceiscapableof producinghighqualitytext;thispaperisanexampleoftroffoutput. Thephototypesetteritselfnormallyrunswithfourfonts,containingroman, italicandboldletters(asonthispage),afullgreekalphabet,andasubstantial numberofspecialcharactersandmathematicalsymbols.Characterscanbe printedinarangeofsizes,andplacedanywhereonthepage. troffallowstheuserfullcontroloverfonts,sizes,andcharacterpositions,as wellastheusualfeaturesofaformatter—right-marginjustification,automatic hyphenation,pagetitlingandnumbering,andsoon.Italsoprovidesmacros, arithmeticvariablesandoperations,andconditionaltesting,forcomplicatedformattingtasks. Thisdocumentisanintroductiontothemostbasicuseoftroff.Itpresents justenoughinformationtoenabletheusertodosimpleformattingtaskslike makingviewgraphs,andtomakeincrementalchangestoexistingpackagesof troffcommands.Inmostrespects,theUNIXformatternroffisidenticaltotroff, sothisdocumentalsoservesasatutorialonnroff. 9April1993 ATROFFTutorial BrianW.Kernighan Typesetting Textformatting NROFF 1.Introduction troff[1]isatext-formattingprogram,writ-tenbyJ.F.Ossanna,forproducinghigh-quality printedoutputfromthephototypesetteronthe UNIXandGCOSoperatingsystems.Thisdocumentisanexampleoftroffoutput. Thesinglemostimportantruleofusing troffisnottouseitdirectly,butthroughsome intermediary.Inmanyways,troffresemblesan assemblylanguage—aremarkablypowerfuland flexibleone—butnonethelesssuchthatmany operationsmustbespecifiedatalevelofdetail andinaformthatistoohardformostpeopleto useeffectively. Fortwospecialapplications,thereareprogramsthatprovideaninterfacetotroffforthe majorityofusers.eqn[2]providesaneasyto learnlanguagefortypesettingmathematics;the eqnuserneedknownotroffwhatsoevertotypesetmathematics.tbl[3]providesthesameconvenienceforproducingtablesofarbitrarycomplexity. Forproducingstraighttext(whichmaywell containmathematicsortables),therearea numberof‘macropackages’thatdefineformatting rulesandoperationsforspecificstylesofdocuments,andreducetheamountofdirectcontact withtroff.Inparticular,the‘−ms’[4]and PWB/MM[5]packagesforBellLabsinternal memorandaandexternalpapersprovidemostof thefacilitiesneededforawiderangeofdocument preparation.(Thismemowaspreparedwith ‘−ms’.)Therearealsopackagesforviewgraphs, forsimulatingtheolderroffformattersonUNIX andGCOS,andforotherspecialapplications. Typicallyyouwillfindthesepackageseasiertouse thantroffonceyougetbeyondthemosttrivial operations;youshouldalwaysconsiderthemfirst. Inthefewcaseswhereexistingpackages don’tdothewholejob,thesolutionisnottowrite anentirelynewsetoftroffinstructionsfrom scratch,buttomakesmallchangestoadaptpackagesthatalreadyexist. Inaccordancewiththisphilosophyofletting someoneelsedothework,thepartoftroff describedhereisonlyasmallpartofthewhole, althoughittriestoconcentrateonthemoreuseful parts.Inanycase,thereisnoattempttobecomplete.Rather,theemphasisisonshowinghowto dosimplethings,andhowtomakeincremental changestowhatalreadyexists.Thecontentsof theremainingsectionsare: 2.Pointsizesandlinespacing 3.Fontsandspecialcharacters 4.Indentsandlinelength 5.Tabs 6.Localmotions:Drawinglinesandcharacters 7.Strings 8.Introductiontomacros 9.Titles,pagesandnumbering 10.Numberregistersandarithmetic 11.Macroswitharguments 12.Conditionals 13.Environments 14.Diversions Appendix:Typesettercharacterset ThetroffdescribedhereistheC-languageversion runningonUNIXatMurrayHill,asdocumentedin [1]. Tousetroffyouhavetopreparenotonly theactualtextyouwantprinted,butsomeinformationthattellshowyouwantitprinted.(Readerswhouseroffwillfindtheapproachfamiliar.) Fortroffthetextandtheformattinginformation areoftenintertwinedquiteintimately.Mostcommandstotroffareplacedonalineseparatefrom thetextitself,beginningwithaperiod(onecommandperline).Forexample, Sometext. .ps14 Somemoretext. willchangethe‘pointsize’,thatis,thesizeofthe lettersbeingprinted,to‘14point’(onepointis 1/72inch)likethis: Sometext.Somemoretext. Occasionally,though,somethingspecial occursinthemiddleofaline—toproduce -2-Area=πr2 youhavetotype Area=\(∗p\fIr\fR\|\s8\u2\d\s0 (whichwewillexplainshortly).Thebackslash character\\isusedtointroducetroffcommands andspecialcharacterswithinalineoftext. 2.PointSizes;LineSpacing Asmentionedabove,thecommand.ps.pssets thepointsize.Onepointis1/72inch,so6-point charactersareatmost1/12inchhigh,and 36-pointcharactersare1/2inch.Thereare15point sizes,listedbelow. 6point:Packmyboxwithfivedozenliquorjugs. 7point:Packmyboxwithfivedozenliquorjugs. 8point:Packmyboxwithfivedozenliquorjugs. 9point:Packmyboxwithfivedozenliquorjugs. 10point:Packmyboxwithfivedozenliquor 11point:Packmyboxwithfivedozen 12point:Packmyboxwithfivedozen 14point:Packmyboxwithfive 16point18point20point 22242836 Ifthenumberafter.ps.psisnotoneofthese legalsizes,itisroundeduptothenextvalidvalue, withamaximumof36.Ifnonumberfollows.ps.ps, troffrevertstotheprevioussize,whateveritwas. troffbeginswithpointsize10,whichisusually fine.Thisdocumentisin9point. Thepointsizecanalsobechangedinthe middleofalineorevenawordwiththein-line command\s\s.Toproduce UNIXrunsonaPDP-11/45 type \s8UNIX\s10runsona\s8PDP-\s1011/45 Asabove,\s\sshouldbefollowedbyalegalpoint size,exceptthat\s0\s0causesthesizetoreverttoits previousvalue.Noticethat\s1011\s1011canbeunderstoodcorrectlyas‘size10,followedbyan11’,if thesizeislegal,butnototherwise.Becautious withsimilarconstructions. Relativesizechangesarealsolegalanduseful: \s−2UNIX\s+2 temporarilydecreasesthesize,whateveritis,by twopoints,thenrestoresit.Relativesizechanges havetheadvantagethatthesizedifferenceisindependentofthestartingsizeofthedocument.The amountoftherelativechangeisrestrictedtoasingledigit. Theotherparameterthatdetermineswhat thetypelookslikeisthespacingbetweenlines, whichissetindependentlyofthepointsize.Verticalspacingismeasuredfromthebottomofone linetothebottomofthenext.Thecommandto controlverticalspacingis.vs.vs.Forrunningtext,it isusuallybesttosettheverticalspacingabout 20%biggerthanthecharactersize.Forexample, sofarinthisdocument,wehaveused‘‘9on11’’, thatis, .ps9 .vs11p Ifwechangedto .ps9 .vs9p therunningtextwouldlooklikethis.Afterafew lines,youwillagreeitlooksalittlecramped.The rightverticalspacingispartlyamatteroftaste, dependingonhowmuchtextyouwanttosqueeze intoagivenspace,andpartlyamatteroftraditionalprintingstyle.Bydefault,troffuses10on 12. Pointsizeandverticalspacing makeasubstantialdifferenceinthe amountoftextpersquareinch.This is12on14. Pointsizeandverticalspacingmakeasubstantialdifferenceinthe amountoftextpersquareinch.Forexample,10on12usesabouttwiceas muchspaceas7on8.Thisis6on7,whichisevensmaller.Itpacksalot morewordsperline,butyoucangoblindtryingtoreadit. Whenusedwithoutarguments,.ps.psand.vs.vs reverttotheprevioussizeandverticalspacing respectively. Thecommand.sp.spisusedtogetextraverticalspace.Unadorned,itgivesyouoneextrablank line(one.vs.vs,whateverthathasbeensetto).Typically,that’smoreorlessthanyouwant,so.sp.spcan befollowedbyinformationabouthowmuchspace youwant— .sp2i means‘twoinchesofverticalspace’. .sp2p means‘twopointsofverticalspace’;and .sp2 means‘twoverticalspaces’—twoofwhatever.vs.vs issetto(thiscanalsobemadeexplicitwith .sp2v.sp2v);troffalsounderstandsdecimalfractionsin mostplaces,so -3- .sp1.5i isaspaceof1.5inches.Thesesamescalefactors canbeusedafter.vs.vstodefinelinespacing,andin factaftermostcommandsthatdealwithphysical dimensions. Itshouldbenotedthatallsizenumbersare convertedinternallyto‘machineunits’,whichare 1/432inch(1/6point).Formostpurposes,thisis enoughresolutionthatyoudon’thavetoworry abouttheaccuracyoftherepresentation.Thesituationisnotquitesogoodvertically,whereresolutionis1/144inch(1/2point). 3.FontsandSpecialCharacters troffandthetypesetterallowfourdifferent fontsatanyonetime.Normallythreefonts (Timesroman,italicandbold)andonecollection ofspecialcharactersarepermanentlymounted. abcdefghijklmnopqrstuvwxyz0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ Thegreek,mathematicalsymbolsandmiscellany ofthespecialfontarelistedinAppendixA. troffprintsinromanunlesstoldotherwise. Toswitchintobold,usethe.ft.ftcommand .ftB andforitalics, .ftI Toreturntoroman,use.ftR.ftR;toreturntothepreviousfont,whateveritwas,useeither.ftP.ftPorjust .ft.ft.The‘underline’command .ul causesthenextinputlinetoprintinitalics..ul.ul canbefollowedbyacounttoindicatethatmore thanonelineistobeitalicized. Fontscanalsobechangedwithinalineor wordwiththein-linecommand\f\f: boldfacetext isproducedby \fBbold\fIface\fRtext Ifyouwanttodothissothepreviousfont,whateveritwas,isleftundisturbed,insertextra\fP\fP commands,likethis: \fBbold\fP\fIface\fP\fRtext\fP Becauseonlytheimmediatelypreviousfontis remembered,youhavetorestorethepreviousfont aftereachchangeoryoucanloseit.Thesameis trueof.ps.psand.vs.vswhenusedwithoutanargument. Thereareotherfontsavailablebesidesthe standardset,althoughyoucanstilluseonlyfour atanygiventime.Thecommand.fp.fptellstroff whatfontsarephysicallymountedonthetypesetter: .fp3H saysthattheHelveticafontismountedonposition 3.(Foracompletelistoffontsandwhattheylook like,seethetroffmanual.)Appropriate.fp.fpcommandsshouldappearatthebeginningofyourdocumentifyoudonotusethestandardfonts. Itispossibletomakeadocumentrelatively independentoftheactualfontsusedtoprintitby usingfontnumbersinsteadofnames;forexample, \f3\f3and.ft˜ 3.ft˜ 3mean‘whateverfontismountedat position3’,andthusworkforanysetting.Normal settingsareromanfonton1,italicon2,boldon3, andspecialon4. Thereisalsoawaytoget‘synthetic’bold fontsbyoverstrikingletterswithaslightoffset. Lookatthe.bd.bdcommandin[1]. Specialcharactershavefour-characternames beginningwith\(\(,andtheymaybeinsertedanywhere.Forexample, 1/4+1/2=3/4 isproducedby \(14+\(12=\(34 Inparticular,greeklettersarealloftheform \(∗−\(∗−,where−−isanupperorlowercaseroman letterreminiscentofthegreek.Thustoget Σ(α×β)→∞ inbaretroffwehavetotype \(∗S(\(∗a\(mu\(∗b)\(−>\(if Thatlineisunscrambledasfollows: \(∗SΣ (( \(∗aα \(mu× \(∗bβ )) \(−>→ \(if∞ Acompletelistofthesespecialnamesoccursin AppendixA. Ineqn[2]thesameeffectcanbeachieved withtheinput SIGMA(alphatimesbeta)−>inf -4-whichislessconcise,butclearertotheuninitiated. Noticethateachfour-characternameisa singlecharacterasfarastroffisconcerned—the ‘translate’command .tr\(mi\(em isperfectlyclear,meaning .tr−— thatis,totranslate−into—. Somecharactersareautomaticallytranslatedintoothers:grave` andacute´ accents (apostrophes)becomeopenandclosesinglequotes ‘˜ ’;thecombinationof‘‘...’’isgenerallypreferable tothedoublequotes"...".Similarlyatyped minussignbecomesahyphen-.Toprintan explicit−sign,use\-\-.Togetabackslashprinted, use\e\e. 4.IndentsandLineLengths troffstartswithalinelengthof6.5inches, toowidefor81/2×11paper.Toresettheline length,usethe.ll.llcommand,asin .ll6i Aswith.sp.sp,theactuallengthcanbespecifiedin severalways;inchesareprobablythemostintuitive. Themaximumlinelengthprovidedbythe typesetteris7.5inches,bytheway.Tousethe fullwidth,youwillhavetoresetthedefaultphysicalleftmargin(‘‘pageoffset’’),whichisnormally slightlylessthanoneinchfromtheleftedgeofthe paper.Thisisdonebythe.po.pocommand. .po0 setstheoffsetasfartotheleftasitwillgo. Theindentcommand.in.incausestheleft margintobeindentedbysomespecifiedamount fromthepageoffset.Ifweuse.in.intomovetheleft marginin,and.ll.lltomovetherightmargintothe left,wecanmakeoffsetblocksoftext: .in0.3i .ll−0.3i texttobesetintoablock .ll+0.3i .in−0.3i willcreateablockthatlookslikethis: Paternosterquiestincaelissanctificeturnomentuum;adveniatregnum tuum;fiatvoluntastua,sicutincaelo, etinterra....Amen. Noticetheuseof‘+’and‘−’tospecifythe amountofchange.Thesechangetheprevious settingbythespecifiedamount,ratherthanjust overridingit.Thedistinctionisquiteimportant: .ll+1i.ll+1imakeslinesoneinchlonger;.ll1i.ll1imakes themoneinchlong. With.in.in,.ll.lland.po.po,thepreviousvalueis usedifnoargumentisspecified. Toindentasingleline,usethe‘temporary indent’command.ti.ti.Forexample,allparagraphs inthismemoeffectivelybeginwiththecommand .ti3 Threeofwhat?Thedefaultunitfor.ti.ti,asfor mosthorizontallyorientedcommands(.ll.ll,.in.in,.po.po), isems;anemisroughlythewidthoftheletter‘m’ inthecurrentpointsize.(Precisely,aeminsizep isppoints.)Althoughinchesareusuallyclearer thanemstopeoplewhodon’tsettypeforaliving, emshaveaplace:theyareameasureofsizethat isproportionaltothecurrentpointsize.Ifyou wanttomaketextthatkeepsitsproportions regardlessofpointsize,youshoulduseemsforall dimensions.Emscanbespecifiedasscalefactors directly,asin.ti2.5m.ti2.5m. Linescanalsobeindentednegativelyifthe indentisalreadypositive: .ti−0.3i causesthenextlinetobemovedbackthreetenths ofaninch.Thustomakeadecorativeinitialcapital,weindentthewholeparagraph,thenmovethe letter‘P’backwitha.ti.ticommand: Paternosterquiestincaelissanctificeturnomentuum;adveniat regnumtuum;fiatvoluntastua, sicutincaelo,etinterra....Amen. Ofcourse,thereisalsosometrickerytomakethe ‘P’bigger(justa‘\s36P\s0’),andtomoveitdown fromitsnormalposition(seethesectiononlocal motions). 5.Tabs Tabs(theASCII‘horizontaltab’character) canbeusedtoproduceoutputincolumns,orto setthehorizontalpositionofoutput.Typically tabsareusedonlyinunfilledtext.Tabstopsare setbydefaulteveryhalfinchfromthecurrent indent,butcanbechangedbythe.ta.tacommand. Tosetstopseveryinch,forexample, .ta1i2i3i4i5i6i Unfortunatelythestopsareleft-justified only(asonatypewriter),soliningupcolumnsof right-justifiednumberscanbepainful.Ifyouhave manynumbers,orifyouneedmorecomplicated tablelayout,don’tusetroffdirectly;usethetbl programdescribedin[3].

-5-Forahandfulofnumericcolumns,youcan doitthisway:Precedeeverynumberbyenough blankstomakeitlineupwhentyped. .nf .ta1i2i3i 1tab2tab3 40tab50tab60 700tab800tab900 .fi Thenchangeeachleadingblankintothestring\0\0. Thisisacharacterthatdoesnotprint,butthat hasthesamewidthasadigit.Whenprinted,this willproduce 123 405060 700800900 Itisalsopossibletofilluptabbed-over spacewithsomecharacterotherthanblanksby settingthe‘tabreplacementcharacter’withthe.tc.tc command: .ta1.5i2.5i .tc\(ru(\(ruis"") NametabAgetab produces NameAge Toresetthetabreplacementcharactertoablank, use.tc.tcwithnoargument.(Linescanalsobe drawnwiththe\l\lcommand,describedinSection 6.) troffalsoprovidesaverygeneralmechanismcalled‘fields’forsettingupcomplicated columns.(Thisisusedbytbl).Wewillnotgo intoitinthispaper. 6.LocalMotions:Drawinglinesandcharacters Remember‘Area=πr2’andthebig‘P’in thePaternoster.Howaretheydone?troffprovidesahostofcommandsforplacingcharactersof anysizeatanyplace.Youcanusethemtodraw specialcharactersortotuneyouroutputforaparticularappearance.Mostofthesecommandsare straightforward,butmessytoreadandtoughto typecorrectly. Ifyouwon’tuseeqn,subscriptsandsuperscriptsaremosteasilydonewiththehalf-linelocal motions\u\uand\d\d.Togobackupthepagehalfa point-size,inserta\u\uatthedesiredplace;togo down,inserta\d\d.(\u\uand\d\dshouldalwaysbe usedinpairs,asexplainedbelow.)Thus Area=\(∗pr\u2\d produces Area=πr2 Tomakethe‘2’smaller,bracketitwith\s−2...\s0\s−2...\s0. Since\u\uand\d\drefertothecurrentpointsize,be suretoputthemeitherbothinsideorbothoutside thesizechanges,oryouwillgetanunbalanced verticalmotion. Sometimesthespacegivenby\u\uand\d\d isn’ttherightamount.The\v\vcommandcanbe usedtorequestanarbitraryamountofvertical motion.Thein-linecommand \v´ (amount)´ causesmotionupordownthepagebytheamount specifiedin‘(amount)’.Forexample,tomovethe ‘P’down,weused .in+0.6i(moveparagraphin) .ll−0.3i(shortenlines) .ti−0.3i(movePback) \v´ 2´ \s36P\s0\v´ −2´ aternosterquiest incaelis... Aminussigncausesupwardmotion,whilenosign oraplussignmeansdownthepage.Thus\v′−2′\v′−2′ causesanupwardverticalmotionoftwoline spaces. Therearemanyotherwaystospecifythe amountofmotion— \v´ 0.1i´ \v´ 3p´ \v´ −0.5m´ andsoonarealllegal.Noticethatthescalespecifieriiorppormmgoesinsidethequotes.Anycharactercanbeusedinplaceofthequotes;thisis alsotrueofallothertroffcommandsdescribedin thissection. Sincetroffdoesnottakewithin-the-line verticalmotionsintoaccountwhenfiguringout whereitisonthepage,outputlinescanhave unexpectedpositionsiftheleftandrightends aren’tatthesameverticalposition.Thus\v\v,like \u\uand\d\d,shouldalwaysbalanceupwardvertical motioninalinewiththesameamountinthe downwarddirection. Arbitraryhorizontalmotionsarealsoavailable—\h\hisquiteanalogousto\v\v,exceptthat thedefaultscalefactorisemsinsteadofline spaces.Asanexample, \h´ −0.1i´ causesabackwardsmotionofatenthofaninch. Asapracticalmatter,considerprintingthemathematicalsymbol‘>>’.Thedefaultspacingistoo wide,soeqnreplacesthisby >\h´ −0.3m´ > toproduce>>.

-6-Frequently\h\hisusedwiththe‘widthfunc-tion’\w\wtogeneratemotionsequaltothewidthof somecharacterstring.Theconstruction \w´ thing´ isanumberequaltothewidthof‘thing’in machineunits(1/432inch).Alltroffcomputationsareultimatelydoneintheseunits.Tomove horizontallythewidthofan‘x’,wecansay \h´ \w´ x´ u´ Aswementionedabove,thedefaultscalefactorfor allhorizontaldimensionsismm,ems,soherewe musthavetheuuformachineunits,orthemotion producedwillbefartoolarge.troffisquite happywiththenestedquotes,bytheway,solong asyoudon’tleaveanyout. Asaliveexampleofthiskindofconstruction,allofthecommandnamesinthetext,like .sp.sp,weredonebyoverstrikingwithaslightoffset. Thecommandsfor.sp.spare .sp\h´ −\w´ .sp´ u´ \h´ 1u´ .sp Thatis,putout‘.sp’,moveleftbythewidthof ‘.sp’,moveright1unit,andprint‘.sp’again.(Of coursethereisawaytoavoidtypingthatmuch inputforeachcommandname,whichwewilldiscussinSection11.) Therearealsoseveralspecial-purposetroff commandsforlocalmotion.Wehavealreadyseen \0\0,whichisanunpaddablewhitespaceofthe samewidthasadigit.‘Unpaddable’meansthatit willneverbewidenedorsplitacrossalinebyline justificationandfilling.Thereisalso\\(blank), whichisanunpaddablecharacterthewidthofa space,\|\|,whichishalfthatwidth,\ˆ \ˆ ,whichisone quarterofthewidthofaspace,and\&\&,whichhas zerowidth.(Thislastoneisuseful,forexample, inenteringatextlinewhichwouldotherwisebegin witha‘.’.) Thecommand\o\o,usedlike \o´ setofcharacters´ causes(upto9)characterstobeoverstruck,centeredonthewidest.Thisisniceforaccents,asin syst\o"e\(ga"met\o"e\(aa"l\o"e\(aa"phonique whichmakes syste` mete´ le´ phonique Theaccentsare\(ga\(gaand\(aa\(aa,or\` \` and\´ \´ ; rememberthateachisjustonecharactertotroff. Youcanmakeyourownoverstrikeswith anotherspecialconvention,\z\z,thezero-motion command.\zx\zxsuppressesthenormalhorizontal motionafterprintingthesinglecharacterxx,so anothercharactercanbelaidontopofit.

Althoughsizescanbechangedwithin\o\o,itcentersthecharactersonthewidest,andtherecanbe nohorizontalorverticalmotions,so\z\zmaybethe onlywaytogetwhatyouwant: isproducedby .sp2 \s8\z\(sq\s14\z\(sq\s22\z\(sq\s36\(sq The.sp.spisneededtoleaveroomfortheresult. Asanotherexample,anextra-heavysemi-colonthatlookslike ,.insteadof;or; canbeconstructedwithabigcommaandabig periodaboveit: \s+6\z,\v´ −0.25m´ .\v´ 0.25m´ \s0 ‘0.25m’isanempiricalconstant. Amoreornateoverstrikeisgivenbythe bracketingfunction\b\b,whichpilesupcharacters vertically,centeredonthecurrentbaseline.Thus wecangetbigbrackets,constructingthemwith piled-upsmallerpieces: ⌈⌊x⌉⌋ bytypinginonlythis: .sp \b′\(lt\(lk\(lb′\b′\(lc\(lf′x\b′\(rc\(rf′\b′\(rt\(rk\(rb′ troffalsoprovidesaconvenientfacilityfor drawinghorizontalandverticallinesofarbitrary lengthwitharbitrarycharacters.\l′1i′\l′1i′drawsaline oneinchlong,likethis:.The lengthcanbefollowedbythecharactertouseif theisn’tappropriate;\l′0.5i.′\l′0.5i.′drawsahalf-inch lineofdots:...............Theconstruction\L\Lis entirelyanalogous,exceptthatitdrawsavertical lineinsteadofhorizontal. 7.Strings Obviouslyifapapercontainsalarge numberofoccurrencesofanacuteaccentovera letter‘e’,typing\o"e\´ "\o"e\´ "foreache´ wouldbea greatnuisance. Fortunately,troffprovidesawayinwhich youcanstoreanarbitrarycollectionoftextina ‘string’,andthereafterusethestringnameasa shorthandforitscontents.Stringsareoneofseveraltroffmechanismswhosejudicioususeletsyou typeadocumentwithlesseffortandorganizeitso thatextensiveformatchangescanbemadewith -7-feweditingchanges. Areferencetoastringisreplacedbywhatevertextthestringwasdefinedas.Stringsare definedwiththecommand.ds.ds.Theline .dse\o"e\´ " definesthestringeetohavethevalue\o"e\´ "\o"e\´ " Stringnamesmaybeeitheroneortwocharacterslong,andarereferredtoby\∗x\∗xforone characternamesor\∗(xy\∗(xyfortwocharacternames. Thustogette´ le´ phone,giventhedefinitionofthe stringeeasabove,wecansayt\∗el\∗ephone. Ifastringmustbeginwithblanks,defineit as .dsxx"text Thedoublequotesignalsthebeginningofthedefinition.Thereisnotrailingquote;theendofthe lineterminatesthestring. Astringmayactuallybeseverallineslong; iftroffencountersa\\attheendofanyline,itis thrownawayandthenextlineaddedtothecurrentone.Soyoucanmakealongstringsimplyby endingeachlinebutthelastwithabackslash: .dsxxthis\ isavery\ longstring Stringsmaybedefinedintermsofother strings,orevenintermsofthemselves;wewilldiscusssomeofthesepossibilitieslater. 8.IntroductiontoMacros Beforewecangomuchfurtherintroff,we needtolearnabitaboutthemacrofacility.Inits simplestform,amacroisjustashorthandnotationquitesimilartoastring.Supposewewant everyparagraphtostartinexactlythesameway —withaspaceandatemporaryindentoftwo ems: .sp .ti+2m Thentosavetyping,wewouldliketocollapse theseintooneshorthandline,atroff‘command’ like .PP thatwouldbetreatedbytroffexactlyas .sp .ti+2m .PP.PPiscalledamacro.Thewaywetelltroffwhat .PP.PPmeansistodefineitwiththe.de.decommand:

.dePP .sp .ti+2m .. Thefirstlinenamesthemacro(weused‘.PP.PP’for ‘paragraph’,anduppercasesoitwouldn’tconflict withanynamethattroffmightalreadyknow about).Thelastline....markstheendofthedefinition.Inbetweenisthetext,whichissimply insertedwhenevertroffseesthe‘command’or macrocall .PP Amacrocancontainanymixtureoftextandformattingcommands. Thedefinitionof.PP.PPhastoprecedeitsfirst use;undefinedmacrosaresimplyignored.Names arerestrictedtooneortwocharacters. Usingmacrosforcommonlyoccurring sequencesofcommandsiscriticallyimportant. Notonlydoesitsavetyping,butitmakeslater changesmucheasier.Supposewedecidethatthe paragraphindentistoosmall,theverticalspaceis muchtoobig,andromanfontshouldbeforced. Insteadofchangingthewholedocument,weneed onlychangethedefinitionof.PP.PPtosomethinglike .dePP\"paragraphmacro .sp2p .ti+3m .ftR .. andthechangetakeseffecteverywhereweused .PP.PP. \"\"isatroffcommandthatcausestherest ofthelinetobeignored.Weuseitheretoadd commentstothemacrodefinition(awiseidea oncedefinitionsgetcomplicated). Asanotherexampleofmacros,consider thesetwowhichstartandendablockofoffset, unfilledtext,likemostoftheexamplesinthis paper: .deBS\"startindentedblock .sp .nf .in+0.3i .. .deBE\"endindentedblock .sp .fi .in−0.3i .. Nowwecansurroundtextlike -8-Copyto JohnDoe RichardRoberts StanleySmith bythecommands.BS.BSand.BE.BE,anditwillcome outasitdidabove.Noticethatweindentedby .in+0.3i.in+0.3iinsteadof.in0.3i.in0.3i.Thiswaywecannest ourusesof.BS.BSandBEBEtogetblockswithin blocks. Iflateronwedecidethattheindentshould be0.5i,thenitisonlynecessarytochangethedefinitionsof.BS.BSand.BE.BE,notthewholepaper. 9.Titles,PagesandNumbering Thisisanareawherethingsgettougher, becausenothingisdoneforyouautomatically.Of necessity,someofthissectionisacookbook,tobe copiedliterallyuntilyougetsomeexperience. Supposeyouwantatitleatthetopofeach page,sayingjust ˜˜˜˜ lefttopcentertoprighttop˜ ˜ ˜ ˜ Inroff,onecansay .he´ lefttop´ centertop´ righttop´ .fo´ leftbottom´ centerbottom´ rightbottom´ togetheadersandfootersautomaticallyonevery page.Alas,thisdoesn’tworkintroff,aserious hardshipforthenovice.Insteadyouhavetodoa lotofspecification. Youhavetosaywhattheactualtitleis (easy);whentoprintit(easyenough);andwhat todoatandaroundthetitleline(harder).Taking theseinreverseorder,firstwedefineamacro.NP.NP (for‘newpage’)toprocesstitlesandthelikeat theendofonepageandthebeginningofthenext: .deNP ′bp ′sp0.5i .tl´ lefttop´ centertop´ righttop´ ′sp0.3i .. Tomakesurewe’reatthetopofapage,weissuea ‘beginpage’command′bp′bp,whichcausesaskipto top-of-page(we’llexplainthe′′shortly).Thenwe spacedownhalfaninch,printthetitle(theuseof .tl.tlshouldbeselfexplanatory;laterwewilldiscuss parameterizingthetitles),spaceanother0.3 inches,andwe’redone. Toaskfor.NP.NPatthebottomofeachpage, wehavetosaysomethinglike‘whenthetextis withinaninchofthebottomofthepage,startthe processingforanewpage.’Thisisdonewitha ‘when’command.wh.wh: .wh−1iNP (No‘.’isusedbeforeNP;thisissimplythename ofamacro,notamacrocall.)Theminussign means‘measureupfromthebottomofthepage’, so‘−1i’means‘oneinchfromthebottom’. The.wh.whcommandappearsintheinputoutsidethedefinitionof.NP.NP;typicallytheinput wouldbe .deNP ... .. .wh−1iNP Nowwhathappens?Astextisactually beingoutput,troffkeepstrackofitsverticalpositiononthepage,andafteralineisprintedwithin oneinchfromthebottom,the.NP.NPmacroisactivated.(Inthejargon,the.wh.whcommandsetsa trapatthespecifiedplace,whichis‘sprung’when thatpointispassed.).NP.NPcausesaskiptothetop ofthenextpage(that’swhatthe′bp′bpwasfor), thenprintsthetitlewiththeappropriatemargins. Why′bp′bpand′sp′spinsteadof.bp.bpand.sp.sp?The answeristhat.sp.spand.bp.bp,likeseveralothercommands,causeabreaktotakeplace.Thatis,all theinputtextcollectedbutnotyetprintedis flushedoutassoonaspossible,andthenextinput lineisguaranteedtostartanewlineofoutput.If wehadused.sp.spor.bp.bpinthe.NP.NPmacro,this wouldcauseabreakinthemiddleofthecurrent outputlinewhenanewpageisstarted.Theeffect wouldbetoprinttheleft-overpartofthatlineat thetopofthepage,followedbythenextinputline onanewoutputline.Thisisnotwhatwewant. Using′′insteadof..foracommandtellstroffthat nobreakistotakeplace—theoutputlinecurrentlybeingfilledshouldnotbeforcedoutbefore thespaceornewpage. Thelistofcommandsthatcauseabreakis shortandnatural: .bp.br.ce.fi.nf.sp.in.ti Allotherscausenobreak,regardlessofwhether youusea..ora′′.Ifyoureallyneedabreak,adda .br.brcommandattheappropriateplace. Oneotherthingtobewareof—ifyou’re changingfontsorpointsizesalot,youmayfind thatifyoucrossapageboundaryinanunexpectedfontorsize,yourtitlescomeoutinthat sizeandfontinsteadofwhatyouintended.Furthermore,thelengthofatitleisindependentof thecurrentlinelength,sotitleswillcomeoutat thedefaultlengthof6.5inchesunlessyouchange it,whichisdonewiththe.lt.ltcommand. Thereareseveralwaystofixtheproblems ofpointsizesandfontsintitles.Forthesimplest applications,wecanchange.NP.NPtosettheproper sizeandfontforthetitle,thenrestoretheprevious -9-values,likethis: .deNP ′bp ′sp0.5i .ftR\"settitlefonttoroman .ps10\"andsizeto10point .lt6i\"andlengthto6inches .tl´ left´ center´ right´ .ps\"reverttoprevioussize .ftP\"andtopreviousfont ′sp0.3i .. Thisversionof.NP.NPdoesnotworkifthe fieldsinthe.tl.tlcommandcontainsizeorfont changes.Tocopewiththatrequirestroff’s‘environment’mechanism,whichwewilldiscussinSection13. Togetafooteratthebottomofapage,you canmodify.NP.NPsoitdoessomeprocessingbefore the′bp′bpcommand,orsplitthejobintoafooter macroinvokedatthebottommarginandaheader macroinvokedatthetopofthepage.Thesevariationsareleftasexercises. Outputpagenumbersarecomputedautomaticallyaseachpageisproduced(startingat1), butnonumbersareprintedunlessyouaskfor themexplicitly.Togetpagenumbersprinted, includethecharacter%%inthe.tl.tllineatthepositionwhereyouwantthenumbertoappear.For example .tl´ ´ -%-´ ´ centersthepagenumberinsidehyphens,asonthis page.Youcansetthepagenumberatanytime witheither.bpn.bpn,whichimmediatelystartsanew pagenumberednn,orwith.pnn.pnn,whichsetsthe pagenumberforthenextpagebutdoesn’tcausea skiptothenewpage.Again,.bp+n.bp+nsetsthepage numbertonnmorethanitscurrentvalue;.bp.bp means.bp+1.bp+1. 10.NumberRegistersandArithmetic troffhasafacilityfordoingarithmetic,and fordefiningandusingvariableswithnumericvalues,callednumberregisters.Numberregisters, likestringsandmacros,canbeusefulinsettingup adocumentsoitiseasytochangelater.Andof coursetheyserveforanysortofarithmeticcomputation. Likestrings,numberregistershaveoneor twocharacternames.Theyaresetbythe.nr.nr command,andarereferencedanywhereby\nx\nx (onecharactername)or\n(xy\n(xy(twocharacter name).

Therearequiteafewpre-definednumber registersmaintainedbytroff,amongthem%%for thecurrentpagenumber;nlnlforthecurrentverticalpositiononthepage;dydy,momoandyryrforthe currentday,monthandyear;and.s.sand.f.fforthe currentsizeandfont.(Thefontisanumberfrom 1to4.)Anyofthesecanbeusedincomputations likeanyotherregister,butsome,like.s.sand.f.f, cannotbechangedwith.nr.nr. Asanexampleoftheuseofnumberregisters,inthe−ms−msmacropackage[4],mostsignificantparametersaredefinedintermsofthevalues ofahandfulofnumberregisters.Theseinclude thepointsizefortext,theverticalspacing,and thelineandtitlelengths.Tosetthepointsize andverticalspacingforthefollowingparagraphs, forexample,ausermaysay .nrPS9 .nrVS11 Theparagraphmacro.PP.PPisdefined(roughly)as follows: .dePP .ps\\n(PS\"resetsize .vs\\n(VSp\"spacing .ftR\"font .sp0.5v\"halfaline .ti+3m .. ThissetsthefonttoRomanandthepointsizeand linespacingtowhatevervaluesarestoredinthe numberregistersPSPSandVSVS. Whyaretheretwobackslashes?Thisisthe eternalproblemofhowtoquoteaquote.When trofforiginallyreadsthemacrodefinition,itpeels offonebackslashtoseewhat’scomingnext.To ensurethatanotherisleftinthedefinitionwhen themacroisused,wehavetoputintwobackslashesinthedefinition.Ifonlyonebackslashis used,pointsizeandverticalspacingwillbefrozen atthetimethemacroisdefined,notwhenitis used. Protectingbyanextralayerofbackslashes isonlyneededfor\n\n,\∗\∗,\$\$(whichwehaven’t cometoyet),and\\itself.Thingslike\s\s,\f\f,\h\h, \v\v,andsoondonotneedanextrabackslash, sincetheyareconvertedbytrofftoaninternal codeimmediatelyuponbeingseen. Arithmeticexpressionscanappearanywhere thatanumberisexpected.Asatrivialexample, .nrPS\\n(PS−2 decrementsPSby2.Expressionscanusethe arithmeticoperators+,−,∗,/,%(mod),therelationaloperators>,>=,<,<=,=,and!=(not equal),andparentheses.

-10-Althoughthearithmeticwehavedonesofar hasbeenstraightforward,morecomplicatedthings aresomewhattricky.First,numberregistershold onlyintegers.troffarithmeticusestruncating integerdivision,justlikeFortran.Second,inthe absenceofparentheses,evaluationisdoneleft-to-rightwithoutanyoperatorprecedence(including relationaloperators).Thus 7∗−4+3/13 becomes‘−1’.Numberregisterscanoccuranywhereinanexpression,andsocanscaleindicators likepp,ii,mm,andsoon(butnospaces).Although integerdivisioncausestruncation,eachnumber anditsscaleindicatorisconvertedtomachine units(1/432inch)beforeanyarithmeticisdone, so1i/2uevaluatesto0.5icorrectly. Thescaleindicatoruuoftenhastoappear whenyouwouldn’texpectit—inparticular,when arithmeticisbeingdoneinacontextthatimplies horizontalorverticaldimensions.Forexample, .ll7/2i wouldseemobviousenough—31/2inches.Sorry. Rememberthatthedefaultunitsforhorizontal parameterslike.ll.llareems.That’sreally‘7ems/ 2inches’,andwhentranslatedintomachineunits, itbecomeszero.Howabout .ll7i/2 Sorry,stillnogood—the‘2’is‘2ems’,so‘7i/2’is small,althoughnotzero.Youmustuse .ll7i/2u Soagain,asaferuleistoattachascaleindicator toeverynumber,evenconstants. Forarithmeticdonewithina.nr.nrcommand, thereisnoimplicationofhorizontalorvertical dimension,sothedefaultunitsare‘units’,and 7i/2and7i/2umeanthesamething.Thus .nrll7i/2 .ll\\n(llu doesjustwhatyouwant,solongasyoudon’tforgettheuuonthe.ll.llcommand. 11.Macroswitharguments Thenextstepistodefinemacrosthatcan changefromoneusetothenextaccordingto parameterssuppliedasarguments.Tomakethis work,weneedtwothings:first,whenwedefinethe macro,wehavetoindicatethatsomepartsofit willbeprovidedasargumentswhenthemacrois called.Thenwhenthemacroiscalledwehaveto provideactualargumentstobepluggedintothe definition. Letusillustratebydefiningamacro.SM.SM thatwillprintitsargumenttwopointssmaller thanthesurroundingtext.Thatis,themacrocall .SMTROFF willproduceTROFF. Thedefinitionof.SM.SMis .deSM \s−2\\$1\s+2 .. Withinamacrodefinition,thesymbol\\$n\\$nrefers tothennthargumentthatthemacrowascalled with.Thus\\$1\\$1isthestringtobeplacedina smallerpointsizewhen.SM.SMiscalled. Asaslightlymorecomplicatedversion,the followingdefinitionof.SM.SMpermitsoptionalsecond andthirdargumentsthatwillbeprintedinthe normalsize: .deSM \\$3\s−2\\$1\s+2\\$2 .. Argumentsnotprovidedwhenthemacroiscalled aretreatedasempty,so .SMTROFF), producesTROFF),while .SMTROFF).( produces(TROFF).Itisconvenienttoreversethe orderofargumentsbecausetrailingpunctuationis muchmorecommonthanleading. Bytheway,thenumberofargumentsthata macrowascalledwithisavailableinnumberregister.$.$. Thefollowingmacro.BD.BDistheoneusedto makethe‘boldroman’wehavebeenusingfor troffcommandnamesintext.Itcombineshorizontalmotions,widthcomputations,andargument rearrangement. .deBD \&\\$3\f1\\$1\h´ −\w´ \\$1´ u+1u´ \\$1\fP\\$2 .. The\h\hand\w\wcommandsneednoextrabackslash,aswediscussedabove.The\&\&istherein casetheargumentbeginswithaperiod. Twobackslashesareneededwiththe\\$n\\$n commands,though,toprotectoneofthemwhen themacroisbeingdefined.Perhapsasecond examplewillmakethisclearer.Consideramacro called.SH.SHwhichproducessectionheadingsrather likethoseinthispaper,withthesectionsnumberedautomatically,andthetitleinboldina smallersize.Theuseis .SH"Sectiontitle..." -11- (Iftheargumenttoamacroistocontainblanks, thenitmustbesurroundedbydoublequotes, unlikeastring,whereonlyoneleadingquoteis permitted.) Hereisthedefinitionofthe.SH.SHmacro: .nrSH0\"initializesectionnumber .deSH .sp0.3i .ftB .nrSH\\n(SH+1\"incrementnumber .ps\\n(PS−1\"decreasePS \\n(SH.\\$1\"number.title .ps\\n(PS\"restorePS .sp0.3i .ftR .. ThesectionnumberiskeptinnumberregisterSH, whichisincrementedeachtimejustbeforeitis used.(Anumberregistermayhavethesame nameasamacrowithoutconflictbutastringmay not.) Weused\\n(SH\\n(SHinsteadof\n(SH\n(SHand \\n(PS\\n(PSinsteadof\n(PS\n(PS.Ifwehadused\n(SH\n(SH, wewouldgetthevalueoftheregisteratthetime themacrowasdefined,notatthetimeitwasused. Ifthat’swhatyouwant,fine,butnothere.Similarly,byusing\\n(PS\\n(PS,wegetthepointsizeatthe timethemacroiscalled. Asanexamplethatdoesnotinvolvenumbers,recallour.NP.NPmacrowhichhada .tl´ left´ center´ right´ Wecouldmaketheseintoparametersbyusing instead .tl´ \\∗(LT´ \\∗(CT´ \\∗(RT´ sothetitlecomesfromthreestringscalledLT,CT andRT.Iftheseareempty,thenthetitlewillbe ablankline.NormallyCTwouldbesetwith somethinglike .dsCT-%- togivejustthepagenumberbetweenhyphens(as onthetopofthispage),butausercouldsupply privatedefinitionsforanyofthestrings. 12.Conditionals Supposewewantthe.SH.SHmacrotoleave twoextrainchesofspacejustbeforesection1,but nowhereelse.Thecleanestwaytodothatisto testinsidethe.SH.SHmacrowhetherthesection numberis1,andaddsomespaceifitis.The.if.if commandprovidestheconditionaltestthatwe canaddjustbeforetheheadinglineisoutput:

.if\\n(SH=1.sp2i\"firstsectiononly Theconditionafterthe.if.ifcanbeanyarithmeticorlogicalexpression.Iftheconditionislogicallytrue,orarithmeticallygreaterthanzero,the restofthelineistreatedasifitweretext—here acommand.Iftheconditionisfalse,orzeroor negative,therestofthelineisskipped. Itispossibletodomorethanonecommand ifaconditionistrue.Supposeseveraloperations aretobedonebeforesection1.Onepossibilityis todefineamacro.S1.S1andinvokeitifweareabout todosection1(asdeterminedbyan.if.if). .deS1 ---processingforsection1--- .. .deSH ... .if\\n(SH=1.S1 ... .. Analternatewayistousetheextended formofthe.if.if,likethis: .if\\n(SH=1\{---processing forsection1----\} Thebraces\{\{and\}\}mustoccurinthepositions shownoryouwillgetunexpectedextralinesin youroutput.troffalsoprovidesan‘if-else’con-struction,whichwewillnotgointohere. Aconditioncanbenegatedbyprecedingit with!!;wegetthesameeffectasabove(butless clearly)byusing .if!\\n(SH>1.S1 Thereareahandfulofotherconditionsthat canbetestedwith.if.if.Forexample,isthecurrent pageevenorodd? .ife.tl´ ´ evenpagetitle´ ´ .ifo.tl´ ´ oddpagetitle´ ´ givesfacingpagesdifferenttitleswhenusedinside anappropriatenewpagemacro. Twootherconditionsarettandnn,whichtell youwhethertheformatteristroffornroff. .ifttroffstuff... .ifnnroffstuff... Finally,stringcomparisonsmaybemadein an.if.if: .if´ string1´ string2´ stuff does‘stuff’ifstring1isthesameasstring2.The characterseparatingthestringscanbeanything reasonablethatisnotcontainedineitherstring. Thestringsthemselvescanreferencestringswith -12- \∗\∗,argumentswith\$\$,andsoon. 13.Environments Aswementioned,thereisapotentialproblemwhengoingacrossapageboundary:parameterslikesizeandfontforapagetitlemaywellbe differentfromthoseineffectinthetextwhenthe pageboundaryoccurs.troffprovidesaverygeneralwaytodealwiththisandsimilarsituations. Therearethree‘environments’,eachofwhichhas independentlysettableversionsofmanyofthe parametersassociatedwithprocessing,including size,font,lineandtitlelengths,fill/nofillmode, tabstops,andevenpartiallycollectedlines.Thus thetitlingproblemmaybereadilysolvedbyprocessingthemaintextinoneenvironmentand titlesinaseparateonewithitsownsuitable parameters. Thecommand.evn.evnshiftstoenvironmentnn; nnmustbe0,1or2.Thecommand.ev.evwithno argumentreturnstothepreviousenvironment. Environmentnamesaremaintainedinastack,so callsfordifferentenvironmentsmaybenestedand unwoundconsistently. Supposewesaythatthemaintextisprocessedinenvironment0,whichiswheretroff beginsbydefault.Thenwecanmodifythenew pagemacro.NP.NPtoprocesstitlesinenvironment1 likethis: .deNP .ev1\"shifttonewenvironment .lt6i\"setparametershere .ftR .ps10 ...anyotherprocessing... .ev\"returntopreviousenvironment .. Itisalsopossibletoinitializetheparametersfor anenvironmentoutsidethe.NP.NPmacro,butthe versionshownkeepsalltheprocessinginoneplace andisthuseasiertounderstandandchange. 14.Diversions Therearenumerousoccasionsinpagelayout whenitisnecessarytostoresometextforaperiod oftimewithoutactuallyprintingit.Footnotesare themostobviousexample:thetextofthefootnote usuallyappearsintheinputwellbeforetheplace onthepagewhereitistobeprintedisreached. Infact,theplacewhereitisoutputnormally dependsonhowbigitis,whichimpliesthatthere mustbeawaytoprocessthefootnoteatleast enoughtodecideitssizewithoutprintingit. troffprovidesamechanismcalledadiversionfordoingthisprocessing.Anypartofthe outputmaybedivertedintoamacroinsteadof beingprinted,andthenatsomeconvenienttime themacromaybeputbackintotheinput. Thecommand.dixy.dixybeginsadiversion— allsubsequentoutputiscollectedintothemacro xyxyuntilthecommand.di.diwithnoargumentsis encountered.Thisterminatesthediversion.The processedtextisavailableatanytimethereafter, simplybygivingthecommand .xy Theverticalsizeofthelastfinisheddiversionis containedinthebuilt-innumberregisterdndn. Asasimpleexample,supposewewantto implementa‘keep-release’operation,sothattext betweenthecommands.KS.KSand.KE.KEwillnotbe splitacrossapageboundary(asforafigureor table).Clearly,whena.KS.KSisencountered,we havetobegindivertingtheoutputsowecanfind outhowbigitis.Thenwhena.KE.KEisseen,we decidewhetherthedivertedtextwillfitonthe currentpage,andprintiteitherthereifitfits,or atthetopofthenextpageifitdoesn’t.So: .deKS\"startkeep .br\"startfreshline .ev1\"collectinnewenvironment .fi\"makeitfilledtext .diXX\"collectinXX .. .deKE\"endkeep .br\"getlastpartialline .di\"enddiversion .if\\n(dn>=\\n(.t.bp\"bpifdoesn´ tfit .nf\"bringitbackinno-fill .XX\"text .ev\"returntonormalenvironment .. Recallthatnumberregisternlnlisthecurrentpositionontheoutputpage.Sinceoutputwasbeing diverted,thisremainsatitsvaluewhenthediversionstarted.dndnistheamountoftextinthe diversion;.t.t(anotherbuilt-inregister)isthedis-tancetothenexttrap,whichweassumeisatthe bottommarginofthepage.Ifthediversionis largeenoughtogopastthetrap,the.if.ifissatisfied,anda.bp.bpisissued.Ineithercase,the divertedoutputisthenbroughtbackwith.XX.XX.It isessentialtobringitbackinno-fillmodesotroff willdonofurtherprocessingonit. Thisisnotthemostgeneralkeep-release, norisitrobustinthefaceofallconceivable inputs,butitwouldrequiremorespacethanwe haveheretowriteitinfullgenerality.Thissectionisnotintendedtoteacheverythingabout diversions,buttosketchoutenoughthatyoucan readexistingmacropackageswithsomecomprehension.

-13-Acknowledgements IamdeeplyindebtedtoJ.F.Ossanna,the authoroftroff,forhisrepeatedpatientexplanationsoffinepoints,andforhiscontinuingwillingnesstoadapttrofftomakeotheruseseasier.I amalsogratefultoJimBlinn,TedDolotta,Doug McIlroy,MikeLeskandJoelSturmanforhelpful commentsonthispaper. References [1]J.F.Ossanna,NROFF/TROFFUser’sManual,BellLaboratoriesComputingScience TechnicalReport54,1976. [2]B.W.Kernighan,ASystemforTypesetting Mathematics—User’sGuide(SecondEdition),BellLaboratoriesComputingScience TechnicalReport17,1977. [3]M.E.Lesk,TBL—AProgramtoFormat Tables,BellLaboratoriesComputingScience TechnicalReport49,1976. [4]M.E.Lesk,TypingDocumentsonUNIX, BellLaboratories,1978. [5]J.R.MasheyandD.W.Smith,PWB/MM —Programmer’sWorkbenchMemorandum Macros,BellLaboratoriesinternalmemorandum.

-14-AppendixA:PhototypesetterCharacterSet Thesecharactersexistinroman,italic,andbold.Togettheoneontheleft,typethefour-characternameon theright. ff\(fffi\(fifl\(flffi\(Fiffl\(Fl \(ru—\(em1/4\(141/2\(123/4\(34 ◯c\(co\(de†\(dg′\(fmc/\(ct ◯r\(rg•\(bu\(sq-\(hy (Inbold,\(sqis.) Thefollowingarespecial-fontcharacters: +\(pl−\(mi×\(mu÷\(di =\(eq≡\(==≥\(>=≤\(<= ≠\(!=±\(+-¬\(no/\(sl ∼\(ap≃\(˜ =∝\(pt∇\(gr →\(->←\(<-↑\(ua↓\(da ∫\(is∂\(pd∞\(if√\(sr ⊂\(sb⊃\(sp∪\(cu∩\(ca ⊆\(ib⊇\(ip∈\(mo∅\(es ´ \(aa` \(ga◯\(ci\(bs §\(sc‡\(dd⇐\(lh⇒\(rh \(lt \(rt⌈\(lc⌉\(rc \(lb \(rb⌊\(lf⌋\(rf \(lk \(rk|\(bvς\(ts \(br|\(or\(ul\(rn ∗\(∗∗ Thesefourcharactersalsohavetwo-characternames.The´ istheapostropheonterminals;the` is theotherquotemark. ´ \´ ` \` −\−\ Thesecharactersexistonlyonthespecialfont,buttheydonothavefour-characternames: "{}<>˜ ˆ \#@ Forgreek,precedetheromanletterby\(∗\(∗togetthecorrespondinggreek;forexample,\(∗a\(∗aisα. abgdezyhiklmncoprstufxqw αβγδϵζηθικλμνξoπρστυϕχψω ABGDEZYHIKLMNCOPRSTUFXQW ABΓΔEZHΘIKΛMNΞOΠPΣTΥΦXΨΩ -15-Index !(negatingconditionals)˜ 17#$(macroargument)˜ 16 #∗x,#(xy(invokestringmacro)˜ 14#b(bracketing function)˜ 13#d(subscript)˜ 11#f(fontchange)˜ 5#h (horizontalmotion)˜ 12#nx,#n(xy(numberregister)˜ 15 #o(overstrike)˜ 13#s(sizechange)˜ 3#u(superscript)˜ 11#v(verticalmotion)˜ 11#w(widthfunction)˜ 12#z(zeromotion)˜ 13′commandinsteadof ˆ command˜ 9%(pagenumberregister)˜ 10,15ˆ ˆ (endof macrodefinition)˜ 7ˆ bp˜ 9,10ˆ br(break)˜ 9ˆ ce(center)˜ 2ˆ ds(definestringmacro)˜ 7,14ˆ fi(fill)˜ 2ˆ ft (changefont)˜ 5ˆ if(conditionaltest)˜ 16ˆ in(indent)˜ 6 ˆ lg(setligatures˜ 5ˆ ll(linelength)˜ 6ˆ nf(nofill)˜ 2ˆ nr (setnumberregister)˜ 14ˆ pn(pagenumber)˜ 10ˆ ps (changepointsize)˜ 1,3ˆ sp(space)˜ 4ˆ ss(setspace size)˜ 10ˆ ta(settabstops)˜ 11ˆ tc(settabcharacter)˜ 10 ˆ tl(title)˜ 9ˆ tr(translatecharacters)˜ 2,6ˆ ul(italicize)˜ 6 ˆ vs(verticalspacing)˜ 3ˆ wh(whenconditional)˜ 9,17 accents˜ 6,13apostrophes˜ 6arithmetic˜ 15backslash˜ 1,3,5,14,16beginpage(ˆ bp)˜ 9blockmacros (B1,B2)˜ 8boldfont(.ftB)˜ 5boustrophedon˜ 12bracketingfunction(##b)˜ 13break(ˆ br)˜ 9break-causingcom-mmands˜ 9centering(ˆ ce)˜ 2changingfonts(ˆ ft,#f)˜ 5 changingmacros˜ 15characterset˜ 4,5,19charactertranslation(ˆ tr)˜ 2,6columnatedoutput˜ 10commands˜ 1commandsthatcausebreak˜ 9conditionals(ˆ if)˜ 16constant proportion˜ 7defaultbreaklist˜ 9definemacro(ˆ de)˜ 7 definestringmacro(ˆ ds)˜ 14drawinglines˜ 11em˜ 7,11 endofmacro(ˆ ˆ )˜ 7evenpagetest(e)˜ 17fill(ˆ fi)˜ 2 fonts(ˆ ft)˜ 4,19Greek(#(∗-)˜ 5,19hangingindent (ˆ ti)˜ 12hints˜ 20horizontalmotion(#h)˜ 12hp(horizontalpositionregister)˜ 15hyphen˜ 6iscaleindicator˜ 4 indent(ˆ in)˜ 6index˜ 21italicfont(.ftI)˜ 4italicize (ˆ ul)˜ 6legalpointsizes˜ 3ligatures(ff,fi,fl;ˆ lg)˜ 5line length(ˆ ll)˜ 6linespacing(ˆ vs)˜ 3localmotions (#u,#d,#v,#h,#w,#o,#z,#b)˜ 11ffmscaleindicator˜ 7 machineunits˜ 4,12macroarguments˜ 15macros˜ 7 macrosthatchange˜ 15multiplebackslashes˜ 14negating conditionals(!)˜ 17newpagemacro(NP)˜ 8nl(current verticalpositionregister)˜ 15nofill(ˆ nf)˜ 2NROFFtest (n)˜ 17nestedquotes˜ 12numberregisters(ˆ nr,#n)˜ 14 numberedparagraphs˜ 12oddpagetest(o)˜ 17orderof evaluation˜ 14overstrike(#o)˜ 13pscaleindicator˜ 3 pagenumberregister(%)˜ 10pagenumbers(ˆ pn, ˆ bp)˜ 10paragraphmacro(PG)˜ 7Paternoster˜ 6point size(ˆ ps)˜ 1,3previousfont(#fP,ˆ ftP)˜ 5previouspoint size(#s0,ˆ ps)˜ 3quotes˜ 6relativechange(±)˜ 6ROFF˜ 1 ROFFheaderandfooter˜ 8Romanfont(.ftR)˜ 4scale indicatori˜ 4scaleindicatorm˜ 7scaleindicatorp˜ 3scale indicatoru˜ 12scaleindicatorsinarithmetic˜ 15section headingmacro(SC)˜ 15setspacesize(ˆ ss)˜ 10sizesee pointsizespace(ˆ sp)˜ 4spacebetweenlines(ˆ vs)˜ 3specialcharacters(#(xx)˜ 5,19stringmacros(ˆ ds,#∗)˜ 14 subscripts(#d)˜ 11superscripts(#u)˜ 11tabcharacter (ˆ tc)˜ 11tabs(ˆ ta)˜ 10temporaryindent(ˆ ti)˜ 7titles (ˆ tl)˜ 8translate(ˆ tr)˜ 2,6,12TROFFexamples˜ 19 TROFFtest(t)˜ 17truncatingdivision˜ 15typefaces seefontsuscaleindicator˜ 12underline(ˆ ul)˜ 6valid pointsizes˜ 3verticalmotion(#v)˜ 11verticalpositionon page˜ 9verticalspacing(ˆ vs)˜ 3when(ˆ wh)˜ 9,17width function(#w)˜ 12widthofdigits˜ 10zeromotion (#z)˜ 13