ASystemforTypesettingMathematics BrianW.KernighanandLorindaL.Cherry ABSTRACT Thispaperdescribesthedesignandimplementationofasystemfortypesetting mathematics.Thelanguagehasbeendesignedtobeeasytolearnandtousebypeople (forexample,secretariesandmathematicaltypists)whoknowneithermathematicsnor typesetting.Experienceindicatesthatthelanguagecanbelearnedinanhourorso,forit hasfewrulesandfewerexceptions.Fortypicalexpressions,thesizeandfontchanges, positioning,linedrawing,andthelikenecessarytoprintaccordingtomathematicalconventionsarealldoneautomatically.Forexample,theinput sumfromi=0toinfinityxsubi=piover2 produces infinityi=0Σxi=π2 Thesyntaxofthelanguageisspecifiedbyasmallcontext-freegrammar;acompiler-compilerisusedtomakeacompilerthattranslatesthislanguageintotypesettingcom-mands.Outputmaybeproducedoneitheraphototypesetteroronaterminalwithfor-wardandreversehalf-linemotions.Thesysteminterfacesdirectlywithtextformatting programs,somixturesoftextandmathematicsmaybehandledsimply. ThispaperisarevisionofapaperoriginallypublishedinCACM,March,1975. 1.Introduction ‘‘Mathematicsisknowninthetradeasdifficult,orpenalty,copybecauseitisslower,moredifficult,andmoreexpensivetosetintypethanany otherkindofcopynormallyoccurringinbooks andjournals.’’[1] Onedifficultywithmathematicaltextisthe multiplicityofcharacters,sizes,andfonts.An expressionsuchas x−>π/2lim(tanx)sin2x=1 requiresanintimatemixtureofroman,italicand greekletters,inthreesizes,andaspecialcharacter ortwo.(‘‘Requires’’isperhapsthewrongword, butmathematicshasitsowntypographicalconventionswhicharequitedifferentfromthoseof ordinarytext.)Typesettingsuchanexpressionby traditionalmethodsisstillanessentiallymanual operation. Aseconddifficultyisthetwodimensional characterofmathematics,whichthesuperscript andlimitsintheprecedingexampleshowedinits simplestform.Thisiscarriedfurtherby a0+b1a1+b2a2+b3a3+... andstillfurtherby ∫dxaemx−be−mx= 12m√ablog√aemx−√b√aemx+√b1m√abtanh−1(√a√bemx)−1m√abcoth−1(√a√bemx) Theseexamplesalsoshowline-drawing,built-up characterslikebracesandradicals,andaspectrum ofpositioningproblems.(Section6showswhata userhastotypetoproducetheseonoursystem.) 2.Photocomposition Photocompositiontechniquescanbeusedto solvesomeoftheproblemsoftypesettingmathematics.Aphototypesetterisadevicewhich exposesapieceofphotographicpaperorfilm, placingcharacterswherevertheyarewanted.The GraphicSystemsphototypesetter[2]ontheUNIX -2-operatingsystem[3]worksbyshininglightthrough acharacterstencil.Thecharacterismadethe rightsizebylenses,andthelightbeamdirectedby fiberopticstothedesiredplaceonapieceofphotographicpaper.Theexposedpaperisdeveloped andtypicallyusedinsomeformofphoto-offset reproduction. OnUNIX,thephototypesetterisdrivenbya formattingprogramcalledTROFF[4].TROFFwas designedforsettingrunningtext.Italsoprovides allofthefacilitiesthatoneneedsfordoingmathematics,suchasarbitraryhorizontalandvertical motions,line-drawing,sizechanging,butthesyn-taxfordescribingthesespecialoperationsisdiffi-culttolearn,anddifficultevenforexperienced userstotypecorrectly. ForthisreasonwedecidedtouseTROFFas an‘‘assemblylanguage,’’bydesigningalanguage fordescribingmathematicalexpressions,andcompilingitintoTROFF. 3.LanguageDesign Thefundamentalprincipleuponwhichwe basedourlanguagedesignisthatthelanguage shouldbeeasytousebypeople(forexample,secretaries)whoknowneithermathematicsnortypesetting. Thisprincipleimpliesseveralthings.First, ‘‘normal’’mathematicalconventionsaboutoperatorprecedence,parentheses,andthelikecannotbe used,fortogivespecialmeaningtosuchcharactersmeansthattheuserhastounderstandwhat heorsheistyping.Thusthelanguageshouldnot assume,forinstance,thatparenthesesarealways balanced,fortheyarenotinthehalf-openinterval (a,b].Norshoulditassumethatthat√a+bcan bereplacedby(a+b)1/2,orthat1/(1−x)isbetter writtenas11−x(orviceversa). Second,thereshouldberelativelyfewrules, keywords,specialsymbolsandoperators,andthe like.Thiskeepsthelanguageeasytolearnand remember.Furthermore,thereshouldbefew exceptionstotherulesthatdoexist:ifsomething worksinonesituation,itshouldworkeverywhere. Ifavariablecanhaveasubscript,thenasubscript canhaveasubscript,andsoonwithoutlimit. Third,‘‘standard’’thingsshouldhappen automatically.Someonewhotypes‘‘x=y+z+1’’ shouldget‘‘x=y+z+1’’.Subscriptsandsuperscriptsshouldautomaticallybeprintedinan appropriatelysmallersize,withnospecialintervention.Fractionbarshavetobemadetheright lengthandpositionedattherightheight.Andso on.Indeedamechanismforoverridingdefault actionshastoexist,butitsapplicationisthe exception,nottherule.

Weassumethatthetypisthasareasonable picture(atwo-dimensionalrepresentation)ofthe desiredfinalform,asmightbehandwrittenbythe authorofapaper.Wealsoassumethattheinput istypedonacomputerterminalmuchlikeanordinarytypewriter.Thisimpliesaninputalphabetof perhaps100characters,noneofthemspecial. Asecondary,butstillimportant,goalinour designwasthatthesystemshouldbeeasyto implement,sinceneitheroftheauthorshadany desiretomakealong-termprojectofit.Sinceour designwasnotfirm,itwasalsonecessarythatthe programbeeasytochangeatanytime. Tomaketheprogrameasytobuildandto change,andtoguaranteeregularity(‘‘itshould workeverywhere’’),thelanguageisdefinedbya context-freegrammar,describedinSection5.The compilerforthelanguagewasbuiltusingacompiler-compiler. Apriori,thegrammar/compiler-compiler approachseemedtherightthingtodo.Oursubsequentexperienceleadsustobelievethatanyother coursewouldhavebeenfolly.Theoriginallanguagewasdesignedinafewdays.Constructionof aworkingsystemsufficienttotrysignificantexamplesrequiredperhapsaperson-month.Sincethen, wehavespentamodestamountofadditionaltime overseveralyearstuning,addingfacilities,and occasionallychangingthelanguageasusersmake criticismsandsuggestions. Wealsodecidedquiteearlythatwewould letTROFFdoourworkforuswheneverpossible. TROFFisquiteapowerfulprogram,withamacro facility,textandarithmeticvariables,numerical computationandtesting,andconditionalbranching.Thuswehavebeenabletoavoidwritingalot ofmundanebuttrickysoftware.Forexample,we storenotextstrings,butsimplypassthemonto TROFF.Thusweavoidhavingtowriteastorage managementpackage.Furthermore,wehavebeen abletoisolateourselvesfrommostdetailsofthe particulardeviceandcharactersetcurrentlyin use.Forexample,weletTROFFcomputethe widthsofallstringsofcharacters;weneedknow nothingaboutthem. Athirddesigngoalisspecialtoourenvironment.Sinceourprogramisonlyusefulfortypesettingmathematics,itisnecessarythatitinterfacecleanlywiththeunderlyingtypesettinglanguageforthebenefitofuserswhowanttoset intermingledmathematicsandtext(theusual case).Thestandardmodeofoperationisthat whenadocumentistyped,mathematicalexpressionsareinputaspartofthetext,butmarkedby usersettabledelimiters.Theprogramreadsthis inputandtreatsascommentsthosethingswhich arenotmathematics,simplypassingthemthrough untouched.Atthesametimeitconvertsthe -3-mathematicalinputintothenecessaryTROFF commands.Theresultingioutputispassed directlytoTROFFwherethecommentsandthe mathematicalpartsbothbecometextand/or TROFFcommands. 4.TheLanguage Wewillnottrytodescribethelanguagepreciselyhere;interestedreadersmayrefertothe appendixformoredetails.Throughoutthissection,wewillwriteexpressionsexactlyastheyare handedtothetypesettingprogram(hereinafter called‘‘EQN’’),exceptthatwewon’tshowthe delimitersthattheusertypestomarkthebeginningandendoftheexpression.Theinterface betweenEQNandTROFFisdescribedattheend ofthissection. Aswesaid,typingx=y+z+1shouldproduce x=y+z+1,andindeeditdoes.Variablesare madeitalic,operatorsanddigitsbecomeroman, andnormalspacingsbetweenlettersandoperators arealteredslightlytogiveamorepleasingappearance. Inputisfree-form.Spacesandnewlinesin theinputareusedbyEQNtoseparatepiecesof theinput;theyarenotusedtocreatespaceinthe output.Thus x=y +z+1 alsogivesx=y+z+1.Free-forminputiseasier totypeinitially;subsequenteditingisalsoeasier, foranexpressionmaybetypedasmanyshort lines. Extrawhitespacecanbeforcedintotheoutputbyseveralcharactersofvarioussizes.Atilde ‘‘˜ ’’givesaspaceequaltothenormalwordspacingintext;acircumflexgiveshalfthismuch,and atabcharcterspacestothenexttabstop. Spaces(ortildes,etc.)alsoservetodelimit piecesoftheinput.Forexample,toget f(t)=2π∫sin(ωt)dt wewrite f(t)=2piintsin(omegat)dt Herespacesarenecessaryintheinputtoindicate thatsin,pi,int,andomegaarespecial,andpotentiallyworthspecialtreatment.EQNlooksupeach suchstringofcharactersinatable,andifappropriategivesitatranslation.Inthiscase,piand omegabecometheirgreekequivalents,intbecomes theintegralsign(whichmustbemoveddownand enlargedsoitlooks‘‘right’’),andsinismade roman,followingconventionalmathematical practice.Parentheses,digitsandoperatorsare automaticallymaderomanwhereverfound. Fractionsarespecifiedwiththekeyword over: a+boverc+d+e=1 produces a+bc+d+e=1 Similarly,subscriptsandsuperscriptsare introducedbythekeywordssubandsup: x2+y2=z2 isproducedby xsup2+ysup2=zsup2 Thespacesafterthe2’sarenecessarytomarkthe endofthesuperscripts;similarlythekeywordsup hastobemarkedoffbyspacesorsomeequivalent delimiter.Thereturntotheproperbaselineis automatic.Multiplelevelsofsubscriptsorsuperscriptsareofcourseallowed:‘‘xsupysupz’’is xyz.Theconstruct‘‘somethingsubsomethingsup something’’isrecognizedasaspecialcase,so‘‘x subisup2’’isx2iinsteadofxi2. Morecomplicatedexpressionscannowbe formedwiththeseprimitives: ∂2f∂x2=x2a2+y2b2 isproducedby {partialsup2f}over{partialxsup2}= xsup2overasup2+ysup2overbsup2 Braces{}areusedtogroupobjectstogether;in thiscasetheyindicateunambiguouslywhatgoes overwhatontheleft-handsideoftheexpression. Thelanguagedefinestheprecedenceofsuptobe higherthanthatofover,sonobracesareneeded togetthecorrectassociationontherightside. Bracescanalwaysbeusedwhenindoubtabout precedence. Thebracesconventionisanexampleofthe powerofusingarecursivegrammartodefinethe language.Itispartofthelanguagethatifaconstructcanappearinsomecontext,thenany expressioninbracescanalsooccurinthatcontext. Thereisasqrtoperatorformakingsquare rootsoftheappropriatesize:‘‘sqrta+b’’produces √a+b,and x={−b+−sqrt{bsup2−4ac}}over2a is x=−b±√b2−4ac2a -4-Sincelargeradicalslookpooronourtypesetter, sqrtisnotusefulfortallexpressions. Limitsonsummations,integralsandsimilar constructionsarespecifiedwiththekeywordsfrom andto.Toget ∞i=0Σxi→0 weneedonlytype sumfromi=0toinfxsubi−>0 CenteringandmakingtheΣbigenoughandthe limitssmallerareallautomatic.Thefromandto partsarebothoptional,andthecentralpart(e.g., theΣ)caninfactbeanything: limfrom{x−>pi/2}(tan˜ x)=inf is x→π/2lim(tanx)=∞ Again,thebracesindicatejustwhatgoesintothe frompart. Thereisafacilityformakingbraces,brackets,parentheses,andverticalbarsoftheright height,usingthekeywordsleftandright: left[x+yover2aright]˜ =˜ 1 makes [x+y2a]=1 Aleftneednothaveacorrespondingright,aswe shallseeinthenextexample.Anycharactersmay followleftandright,butgenerallyonlyvarious parenthesesandbarsaremeaningful. Bigbrackets,etc.,areoftenusedwith anotherfacility,calledpiles,whichmakevertical pilesofobjects.Forexample,toget sign(x)≡ 10−1ifififx>0x=0x<0 wecantype sign(x)˜ ==˜ left{ rpile{1above0above−1} ˜˜ lpile{ifaboveifaboveif} ˜˜ lpile{x>0abovex=0abovex<0} Theconstruction‘‘left{’’makesaleftbracebig enoughtoenclosethe‘‘rpile{...}’’,whichisa right-justifiedpileof‘‘above...above...’’.‘‘lpile’’ makesaleft-justifiedpile.Therearealsocentered piles.Becauseoftherecursivelanguagedefinition, apilecancontainanynumberofelements;any elementofapilecanofcoursecontainpiles. AlthoughEQNmakesavaliantattemptto usetherightsizesandfonts,therearetimeswhen thedefaultassumptionsaresimplynotwhatis wanted.Forinstancetheitalicsigninthepreviousexamplewouldconventionallybeinroman. Slidesandtransparenciesoftenrequirelargercharactersthannormaltext.Thuswealsoprovidesize andfontchangingcommands:‘‘size12bold {A˜ x˜ =˜ y}’’willproduceAx=y.Sizeisfollowedbyanumberrepresentingacharactersizein points.(Onepointis1/72inch;thispaperisset in9pointtype.) Ifnecessary,aninputstringcanbequotedin "...",whichturnsoffgrammaticalsignificance,and anyfontorspacingchangesthatmightotherwise bedoneonit.Thuswecansay lim˜ roman"sup"˜ xsubn=0 toensurethatthesupremumdoesn’tbecomea superscript: limsupxn=0 Diacriticalmarks,longaproblemintraditionaltypesetting,arestraightforward: .x+ˆ x+˜ y+ˆ X+..Y=z+Z ismadebytyping xdotunder+xhat+ytilde +Xhat+Ydotdot=z+Zbar Therearealsofacilitiesforgloballychanging defaultsizesandfonts,forexampleformaking viewgraphsorforsettingchemicalequations.The languageallowsformatrices,andforliningup equationsatthesamehorizontalposition. Finally,thereisadefinitionfacility,soauser cansay definename"..." atanytimeinthedocument;henceforth,any occurrenceofthetoken‘‘name’’inanexpression willbeexpandedintowhateverwasinsidethedoublequotesinitsdefinition.Thisletsuserstailor thelanguagetotheirownspecifications,foritis quitepossibletoredefinekeywordslikesupor over.Section6showsanexampleofdefinitions. TheEQNpreprocessorreadsintermixedtext andequations,andpassesitsoutputtoTROFF. SinceTROFFuseslinesbeginningwithaperiodas controlwords(e.g.,‘‘.ce’’means‘‘centerthenext outputline’’),EQNusesthesequence‘‘.EQ’’to markthebeginningofanequationand‘‘.EN’’to marktheend.The‘‘.EQ’’and‘‘.EN’’arepassed throughtoTROFFuntouched,sotheycanalsobe usedbyaknowledgeableusertocenterequations, numberthemautomatically,etc.Bydefault,however,‘‘.EQ’’and‘‘.EN’’aresimplyignoredby TROFF,sobydefaultequationsareprintedin-line.

-5- ‘‘.EQ’’and‘‘.EN’’canbesupplementedby TROFFcommandsasdesired;forexample,acentereddisplayequationcanbeproducedwiththe input: .ce .EQ xsubi=ysubi... .EN Sinceitistedioustotype‘‘.EQ’’and‘‘.EN’’ aroundveryshortexpressions(singleletters,for instance),theusercanalsodefinetwocharacters toserveastheleftandrightdelimitersofexpressions.Thesecharactersarerecognizedanywhere insubsequenttext.Forexampleiftheleftand rightdelimitershavebothbeensetto‘‘#’’,the input: Let#xsubi#,#y#and#alpha#bepositive produces: Letxi,yandαbepositive Runningapreprocessorisstrikinglyeasyon UNIX.Totypesettextstoredinfile‘‘f’’,oneissues thecommand: eqnf|troff Theverticalbarconnectstheoutputofoneprocess(EQN)totheinputofanother(TROFF). 5.LanguageTheory Thebasicstructureofthelanguageisnota particularlyoriginalone.Equationsarepictured asasetof‘‘boxes,’’piecedtogetherinvarious ways.Forexample,somethingwithasubscriptis justaboxfollowedbyanotherboxmoveddownwardandshrunkbyanappropriateamount.A fractionisjustaboxcenteredaboveanotherbox, attherightaltitude,withalineofcorrectlength drawnbetweenthem. Thegrammarforthelanguageisshown below.Forpurposesofexposition,wehavecollapsedsomeproductions.Intheoriginalgrammar, thereareabout70productions,butmanyofthese aresimpleonesusedonlytoguaranteethatsome keywordisrecognizedearlyenoughintheparsing process.Symbolsincapitallettersareterminal symbols;lowercasesymbolsarenon-terminals, i.e.,syntacticcategories.Theverticalbar|indicatesanalternative;thebrackets[]indicate optionalmaterial.ATEXTisastringofnonblankcharactersoranystringinsidedouble quotes;theotherterminalsymbolsrepresentliteral occurrencesofthecorrespondingkeyword. eqn:box|eqnbox box:text |{eqn} |boxOVERbox |SQRTbox |boxSUBbox|boxSUPbox |[L|C|R]PILE{list} |LEFTtexteqn[RIGHTtext] |box[FROMbox][TObox] |SIZEtextbox |[ROMAN|BOLD|ITALIC]box |box[HAT|BAR|DOT|DOTDOT|TILDE] |DEFINEtexttext list:eqn|listABOVEeqn text:TEXT Thegrammarmakesitobviouswhythereare fewexceptions.Forexample,theobservationthat somethingcanbereplacedbyamorecomplicated somethinginbracesisimplicitintheproductions: eqn:box|eqnbox box:text|{eqn} Anywhereasinglecharactercouldbeused,any legalconstructioncanbeused. Clearly,ourgrammarishighlyambiguous. What,forinstance,dowedowiththeinput aoverboverc? Isit {aoverb}overc orisit aover{boverc}? Toanswerquestionslikethis,thegrammaris supplementedwithasmallsetofrulesthat describetheprecedenceandassociativityofoperators.Inparticular,wespecify(moreorlessarbitrarily)thatoverassociatestotheleft,sothefirst alternativeaboveistheonechosen.Ontheother hand,subandsupbindtotheright,becausethis isclosertostandardmathematicalpractice.That is,weassumexabisx(ab),not(xa)b. Theprecedencerulesresolvetheambiguity inaconstructionlike asup2overb Wedefinesuptohaveahigherprecedencethan over,sothisconstructionisparsedasa2binstead ofa2b. Naturally,ausercanalwaysforceaparticularparsingbyplacingbracesaroundexpressions. Theambiguousgrammarapproachseemsto bequiteuseful.Thegrammarweuseissmall -6-enoughtobeeasilyunderstood,foritcontains noneoftheproductionsthatwouldbenormally usedforresolvingambiguity.Insteadthesupplementalinformationaboutprecedenceandassociativity(alsosmallenoughtobeunderstood)providesthecompiler-compilerwiththeinformationit needstomakeafast,deterministicparserforthe specificlanguagewewant.Whenthelanguageis supplementedbythedisambiguatingrules,itisin factLR(1)andthuseasytoparse[5]. Theoutputcodeisgeneratedastheinputis scanned.Anytimeaproductionofthegrammar isrecognized,(potentially)someTROFFcommandsareoutput.Forexample,whenthelexical analyzerreportsthatithasfoundaTEXT(i.e.,a stringofcontiguouscharacters),wehaverecognizedtheproduction: text:TEXT Thetranslationofthisissimple.Wegeneratea localnameforthestring,thenhandthenameand thestringtoTROFF,andletTROFFperformthe storagemanagement.Allwesaveisthenameof thestring,itsheight,anditsbaseline. Asanotherexample,thetranslationassociatedwiththeproduction box:boxOVERbox is: Widthofoutputbox= slightlymorethanlargestinputwidth Heightofoutputbox= slightlymorethansumofinputheights Baseofoutputbox= slightlymorethanheightofbottominputbox Stringdescribingoutputbox= movedown; moverightenoughtocenterbottombox; drawbottombox(i.e.,copystringforbottombox); moveup;moveleftenoughtocentertopbox; drawtopbox(i.e.,copystringfortopbox); movedownandleft;drawlinefullwidth; returntoproperbaseline. Mostoftheotherproductionshaveequallysimple semanticactions.Picturingtheoutputasasetof properlyplacedboxesmakestherightsequenceof positioningcommandsquiteobvious.Themain difficultyisinfindingtherightnumberstousefor estheticallypleasingpositioning. Withagrammar,itisusuallyclearhowto extendthelanguage.Forinstance,oneofour userssuggestedaTENSORoperator,tomakeconstructionslike lmknTji Grammatically,thisiseasy:itissufficienttoadda productionlike box:TENSOR{list} Semantically,weneedonlyjuggletheboxestothe rightplaces. 6.Experience Therearereallythreeaspectsofinterest— howwellEQNsetsmathematics,howwellitsatisfiesitsgoalofbeing‘‘easytouse,’’andhoweasyit wastobuild. Thefirstquestioniseasilyaddressed.This entirepaperhasbeensetbytheprogram.Readerscanjudgeforthemselveswhetheritisgood enoughfortheirpurposes.Oneofouruserscommentedthatalthoughtheoutputisnotasgoodas thebesthand-setmaterial,itisstillbetterthan average,andmuchbetterthantheworst.Inany case,whocares?Printedbookscannotcompete withthebirdsandflowersofilluminated manuscriptsonestheticgrounds,either,butthey havesomecleareconomicadvantages. Someofthedeficienciesintheoutputcould becleanedupwithmoreworkonourpart.For example,wesometimesleavetoomuchspace betweenaromanletterandanitalicone.Ifwe werewillingtokeeptrackofthefontsinvolved,we coulddothisbettermoreofthetime. Someotherweaknessesareinherentinour outputdevice.Itishard,forinstance,todrawa lineofanarbitrarylengthwithoutgettingaperceptibleoverstrikeatoneend. Astoeaseofuse,atthetimeofwriting,the systemhasbeenusedbytwodistinctgroups.One userpopulationconsistsofmathematicians, chemists,physicists,andcomputerscientists. Theirtypicalreactionhasbeensomethinglike: (1)It’seasytowrite,althoughImakethefollowingmistakes... (2)HowdoIdo...? (3)Itbotchesthefollowingthings....Whydon’t youfixthem? (4)Youreallyneedthefollowingfeatures... Thelearningtimeisshort.Afewminutes givesthegeneralflavor,andtypingapageortwo ofapapergenerallyuncoversmostofthemisconceptionsabouthowitworks. Thesecondusergroupismuchlarger,the secretariesandmathematicaltypistswhowerethe originaltargetofthesystem.Theytendtobe enthusiasticconverts.Theyfindthelanguageeasy tolearn(mostarelargelyself-taught),andhave littletroubleproducingtheoutputtheywant. Theyareofcourselesscriticaloftheestheticsof theiroutputthanuserstrainedinmathematics. Afteratransitionperiod,mostfindusinga -7-computermoreinterestingthanaregulartype-writer. Themaindifficultythatusershaveseemsto berememberingthatablankisadelimiter;even experiencedusersuseblankswheretheyshouldn’t andomitthemwhentheyareneeded.Acommon instanceistyping f(xsubi) whichproduces f(xi) insteadof f(xi) SincetheEQNlanguageknowsnomathematics,it cannotdeducethattherightparenthesisisnot partofthesubscript. Thelanguageissomewhatprolix,butthis doesn’tseemexcessiveconsideringhowmuchis beingdone,anditiscertainlymorecompactthan thecorrespondingTROFFcommands.Forexample,hereisthesourceforthecontinuedfraction expressioninSection1ofthispaper: asub0+bsub1over {asub1+bsub2over {asub2+bsub3over {asub3+...}}} ThisistheinputforthelargeintegralofSection1; noticetheuseofdefinitions: defineemx"{esupmx}" definemab"{msqrtab}" definesa"{sqrta}" definesb"{sqrtb}" intdxover{aemx−besup−mx}˜ =˜ left{lpile{ 1over{2mab}˜ log˜ {saemx−sb}over{saemx+sb} above 1overmab˜ tanhsup−1(saoversbemx) above −1overmab˜ cothsup−1(saoversbemx) } Astoeaseofconstruction,wehavealready mentionedthattherearereallyonlyafewpersonmonthsinvested.Muchofthistimehasgoneinto twothings—fine-tuning(whatisthemostestheti-callypleasingspacetousebetweenthenumerator anddenominatorofafraction?),andchanging thingsfounddeficientbyourusers(shouldn’ta tildebeadelimiter?). Theprogramconsistsofanumberofsmall, essentiallyunconnectedmodulesforcodegeneration,asimplelexicalanalyzer,acannedparser whichwedidnothavetowrite,andsomemiscellanyassociatedwithinputfilesandthemacro facility.Theprogramisnowabout1600linesofC [6],ahigh-levellanguagereminiscentofBCPL. About20percentoftheselinesare‘‘print’’statements,generatingtheoutputcode. Thesemanticroutinesthatgeneratethe actualTROFFcommandscanbechangedto accommodateotherformattinglanguagesand devices.Forexample,inlessthan24hours,oneof uschangedtheentiresemanticpackagetodrive NROFF,avariantofTROFF,fortypesettingmathematicsonteletypewriterdevicescapableof reverselinemotions.Sincemanypotentialusers donothaveaccesstoatypesetter,butstillhaveto typemathematics,thisprovidesawaytogeta typedversionofthefinaloutputwhichisclose enoughfordebuggingpurposes,andsometimes evenforultimateuse. 7.Conclusions Wethinkwehaveshownthatitispossible todoacceptablygoodtypesettingofmathematics onaphototypesetter,withaninputlanguagethat iseasytolearnanduseandthatsatisfiesmany users’demands.Suchapackagecanbeimplementedinshortorder,givenacompiler-compiler andadecenttypesettingprogramunderneath. Definingalanguage,andbuildingacompiler foritwithacompiler-compilerseemsliketheonly sensiblewaytodobusiness.Ourexperiencewith theuseofagrammarandacompiler-compilerhas beenuniformlyfavorable.Ifwehadwritteneverythingintocodedirectly,wewouldhavebeen lockedintoouroriginaldesign.Furthermore,we wouldhaveneverbeensurewheretheexceptions andspecialcaseswere.Butbecausewehavea grammar,wecanchangeourmindsreadilyand stillbereasonablysurethatifaconstruction worksinoneplaceitwillworkeverywhere. Acknowledgements WearedeeplyindebtedtoJ.F.Ossanna,the authorofTROFF,forhiswillingnesstomodify TROFFtomakeourtaskeasierandforhiscontinuousassistanceduringthedevelopmentofourprogram.WearealsogratefultoA.V.Ahoforhelp withlanguagetheory,toS.C.Johnsonforaid withthecompiler-compiler,andtoourearlyusers A.V.Aho,S.I.Feldman,S.C.Johnson,R.W. Hamming,andM.D.McIlroyfortheirconstructivecriticisms. References [1]AManualofStyle,12thEdition.University ofChicagoPress,1969.p295. [2]ModelC/A/TPhototypesetter.GraphicSystems,Inc.,Hudson,N.H.

-8- [3]Ritchie,D.M.,andThompson,K.L.,‘‘The UNIXtime-sharingsystem.’’Comm.ACM 17,7(July1974),365-375. [4]Ossanna,J.F.,TROFFUser’sManual.Bell LaboratoriesComputingScienceTechnical Report54,1977. [5]Aho,A.V.,andJohnson,S.C.,‘‘LRParsing.’’Comp.Surv.6,2(June1974),99-124. [6]B.W.KernighanandD.M.Ritchie,TheC ProgrammingLanguage.Prentice-Hall,Inc., 1978.