Chapter11. Macros
An\expandaftercommandis necessarytoremovethe\fi (see page 147), so o that
\xWhitewillgetthenextpositionasargumentinsteadof\fi.
Positionsareeithertwoorthreecharacterslong.Thecallto\WhitePieceOrPawn,afour-
parametermacro,appendedaterminatorstringXY.Inthecaseofapawn,therefore,argu-
ment3isthecharacterXandargument4isempty;forallotherpiecesargument1isthe
piece,2and3aretheposition,andargument4isX.
\def\WhitePieceOrPawn#1#2#3#4Y{
\if#3X \WhitePiece{P}{#1#2}%
\else \WhitePiece{#1}{#2#3}\fi}
11.9.2 Examiningtheargument
Itmaybenecessaryinsomecasestotestwhetheramacroargumentcontainssomeelement.
Forareal-lifeexample,considerthefollowing(seealsothe\DisplayEquationexample
onpage214).
Supposethetitleandauthorofanarticlearegivenas
\title{An angle trisector}
\author{A.B. Cee\footnote*{Research supported by the
Very Big Company of America}}
withmultipleauthorsgivenas
\author{A.B. Cee\footnote*{Supported by NSF grant 1}
\and
X.Y. Zee\footnote{**}{Supported by NATO grant 2}}
Supposefurtherthatthe\titleand\authormacrosaredefinedas
\def\title#1{\def\TheTitle{#1}} \def\author#1{\def\TheAuthor{#1}}
whichwillbeusedas
\def\ArticleHeading{ ... \TheTitle ... \TheAuthor ... }
Forsomejournalsit isrequired to havetheauthorshipandthetitleofthearticleinall
capitals.Theimplementationofthiscouldbe
\def\ArticleCapitalHeading
{ ...
\uppercase\expandafter{\TheTitle}
...
\uppercase\expandafter{\TheAuthor}
...
}
Nowthe\expandaftercommandswillexpandthetitleandauthorintotheactualtexts,
and the\uppercase commands will capitalizethem. However, for theauthors this is
wrong,sincethe\uppercasecommandwillalsocapitalizethefootnotetexts.Thepro-
blemisthentouppercaseonlythepartsofthetitleinbetweenthefootnotes.
Asafirstattempt,letustakethecaseofoneauthor,andletthebasiccallbe
\expandafter\UCnoFootnote\TheAuthor
120
VictorEijkhout–T
E
XbyTopic
Cut pages from pdf online - remove PDF pages in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Provides Users with Mature Document Manipulating Function for Deleting PDF Pages
copy pages from pdf into new pdf; copy page from pdf
Cut pages from pdf online - VB.NET PDF Page Delete Library: remove PDF pages in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
Visual Basic Sample Codes to Delete PDF Document Page in .NET
delete pdf pages online; delete page pdf file
11.9. Macrotechniques
Thisexpandsinto
\UCnoFootnote A.B. Cee\footnote*{Supported ... }
Themacro
\def\UCnoFootnote#1\footnote#2#3{\uppercase{#1}\footnote{#2}{#3}}
willanalysethiscorrectly:
#1<-A.B. Cee
#2<-*
#3<-Supported ...
However,ifthereisnofootnote,thismacroiscompletelywrong.
Asafirstrefinementweaddafootnoteourselves,justtomakesurethatoneispresent:
\expandafter\UCnoFootnote\TheAuthor\footnote 00
Nowwehavetotestwhatkindoffootnotewefind:
\def\stopper{0}
\def\UCnoFootnote#1\footnote#2#3{\uppercase{#1}\def\tester{#2}%
\ifx\stopper\tester
\else\footnote{#2}{#3}\fi}
With\ifxwetest thedelimiterfootnotesign against theactual signencountered.Note
thatasolutionwith
\ifx0#2
wouldbewrongifthefootnotesignconsistsofmorethanonetoken,forinstance{**}.
Themacro so fariscorrectif therewasnofootnote,but iftherewas oneitiswrong:
theterminatingtokensremaintobedisposedof.Theyaretakencareofinthefollowing
version:
\def\stopper{0}
\def\UCnoFootnote#1\footnote#2#3{\uppercase{#1}\def\tester{#2}%
\ifx\stopper\tester
\else\footnote{#2}{#3}\expandafter\UCnoFootnote
\fi}
Arepeatedcallto\UCnoFootnoteremovesthedelimitertokens(the\expandafterfirst
removesthe\fi),andasanaddedbonus,thismacroisalsocorrectformultipleauthors.
11.9.3 Optionalmacroparameterswith\futurelet
Onestandardapplicationof\futureletisimplementingoptionalparametersofmacros.
Thegeneralcourseofactionisasfollows:
\def\Com{\futurelet\testchar\MaybeOptArgCom}
\def\MaybeOptArgCom{\ifx[\testchar \let\next\OptArgCom
\else \let\next\NoOptArgCom \fi \next}
\def\OptArgCom[#1]#2{ ... }\def\NoOptArgCom#1{ ... }
Notethat\ifxisusedeventhoughittestsforacharacter.Thereasonisofcoursethat,if
theoptionalargumentisomitted,theremightbeanexpandablecontrolsequencebehind
the\Com.
VictorEijkhout–T
E
XbyTopic
121
VB.NET PDF Page Extract Library: copy, paste, cut PDF pages in vb.
Ability to copy PDF pages and paste into another PDF file. Security PDF component download. Online source codes for quick evaluation in VB.NET class.
delete page on pdf; copy pages from pdf to new pdf
C# PDF Page Extract Library: copy, paste, cut PDF pages in C#.net
NET application. Online C# source code for extracting, copying and pasting PDF pages in C#.NET console class. Support .NET WinForms
delete a page from a pdf online; delete pages on pdf online
Chapter11. Macros
Themacro\Comnowhasoneoptionalandoneregularargument;itcanbecalledas
\Com{argument}
oras
\Com[optional]{argument}
Oftenthecallwithouttheoptionalargumentwillinsertsomedefaultvalue:
\def\NoOptArgCom#1{\OptArgCom[default]{#1}}
ThismechanismiswidelyusedinformatssuchasL
A
T
E
XandLAMST
E
X;seealso[49].
11.9.4 Two-stepmacros
Oftenwhatlooksto theuserlikeonemacro isinreality atwo-stepprocess,whereone
macrowillsetupconditions,andasecondmacrowilldothework.
Asanexample,hereisamacro\PickToEolwithanargumentthatisdelimitedbytheline
end.Firstwewriteamacrowithoutargumentsthatchangesthecategorycodeoftheline
end,andthencallsthesecondmacro.
\def\PickToEol{\begingroup\catcode‘\^^M=12 \xPickToEol}
Thesecondmacrocanthentakeasanargumenteverythinguptotheendoftheline:
\def\xPickToEol#1^^M{ ... #1 ... \endgroup}
Thereisoneproblemwiththisdefinition:the^^Mcharactershouldhavecategory12.We
arriveatthefollowing:
\def\PickToEol{\begingroup\catcode‘\^^M=12 \xPickToEol}
{\catcode‘\^^M=12 %
\gdef\xPickToEol#1^^M{ ... #1 ... \endgroup}%
}
wherethecategorycodeof^^Mischangedforthesakeofthedefinitionof\xPickToEol.
Notethatthe^^Min\PickToEoloccursinacontrolsymbol,sotherethecategorycode
isirrelevant.Thereforethatdefinitioncanbeoutsidethegroupwherethecategorycodeof
^^Misredefined.
11.9.5 Acommentenvironment
Asanapplicationoftheaboveideaoftwo-stepmacros,andinordertoillustratetailrecur-
sion,herearemacrosfora‘comment’environment.
OftenitisnecessarytoremoveapartofT
E
Xinputtemporarily.Forthisonewouldliketo
write
\comment
...
\endcomment
Thesimplestimplementationofthis,
\def\comment#1\endcomment{}
122
VictorEijkhout–T
E
XbyTopic
VB.NET PDF copy, paste image library: copy, paste, cut PDF images
Copy, paste and cut PDF image while preview without adobe Free Visual Studio .NET PDF library, easy to be Online source codes for quick evaluation in VB.NET
delete a page in a pdf file; delete pdf page acrobat
C# PDF copy, paste image Library: copy, paste, cut PDF images in
C#.NET PDF SDK - Copy, Paste, Cut PDF Image in C#.NET. C#.NET Demo Code: Cut Image in PDF Page in C#.NET. PDF image cutting is similar to image deleting.
delete blank pages from pdf file; reader extract pages from pdf
11.9. Macrotechniques
hasanumberofweaknesses.Forinstance,itcannotcopewithoutermacrosorinputthat
doesnothavebalancedbraces.Itsworstshortcoming,however,isthatitreadsthecomplete
commenttextasamacroargument.ThislimitsthesizeofthecommenttothatofT
E
X’s
inputbuffer.
Itwouldbeabetterideatotakeontheout-commentedtextonelineatatime.Forthiswe
wanttowritearecursivemacrowithabasicstructure
\def\comment#1^^M{ ... \comment }
Inordertobeabletowritethisdefinitionatall,thecategorycodeofthelineendmustbe
changed;asabovewewillhave
\def\comment{\begingroup \catcode‘\^^M=12 \xcomment}
{\catcode‘\^^M=12 \endlinechar=-1 %
\gdef\xcomment#1^^M{ ... \xcomment}
}
Changingthe\endlinecharismerelytopreventhavingtoputcommentcharactersatthe
endofeverylineofthedefinition.
Ofcourse,theprocessmuststopatacertaintime.Tothispurposeweinvestigatetheline
thatwasscoopedupasmacroargument:
{\catcode‘\^^M=12 \endlinechar=-1 %
\gdef\xcomment#1^^M{\def\test{#1}
\ifx\test\endcomment \let\next=\endgroup
\else \let\next=\xcomment \fi
\next}
}
andwehavetodefine\endcomment:
\def\endcomment{\endcomment}
Thiscommandwillneverbeexecuted:itismerelyforpurposesoftestingwhethertheend
oftheenvironmenthasbeenreached.
Wemaywanttocommentouttextthatisnotsyntacticallycorrect.Thereforeweswitchto
averbatimmodewhencommenting.ThefollowingmacroisgiveninplainT
E
X:
\def\dospecials{\do\ \do\\\do\{\do\}\do\$\do\&%
\do\#\do\^\do\^^K\do\_\do\^^A\do\%\do\~}
Weuseittodefine\commentasfollows:
\def\makeinnocent#1{\catcode‘#1=12 }
\def\comment{\begingroup
\let\do=\makeinnocent \dospecials
\endlinechar‘\^^M \catcode‘\^^M=12 \xcomment}
Apartfromthepossibilitymentionedaboveofcommentingouttextthatisnotsyntactically
correct,forinstancebecauseofunmatchedbraces,thissolutioncanhandleoutermacros.
Theformerimplementationof\xcommentwouldcauseaT
E
Xerrorifoneoccurredinthe
commenttext.
VictorEijkhout–T
E
XbyTopic
123
VB.NET PDF Page Insert Library: insert pages into PDF file in vb.
add and insert one or multiple pages to existing adobe PDF document in VB.NET. Ability to create a blank PDF page with related by using following online VB.NET
delete page numbers in pdf; delete pages of pdf reader
C# PDF Page Insert Library: insert pages into PDF file in C#.net
adding and inserting one or multiple pages to existing Offer PDF page break inserting function. Free components and online source codes for .NET framework 2.0+.
delete pages from a pdf reader; delete pdf pages ipad
Chapter11. Macros
However, using verbatim modeposesthe problem ofconcludingtheenvironment. The
finallineofthecommentisnownotthecontrolsequence\endcomment,butthecharacters
constitutingit.Wehavetotestforthesethen:
{\escapechar=-1
\xdef\endcomment{\string\\endcomment}
}
Thesequence\string\\givesabackslash.Wecouldnothaveused
\edef\endcomment{\string\endcomment}
becausethelettersofthewordendcommentwouldthenhavecategorycode12,insteadof
the11thattheonesonthelastlineofthecommentwillhave.
124
VictorEijkhout–T
E
XbyTopic
C# HTML5 PDF Viewer SDK to view PDF document online in C#.NET
Image: Copy, Paste, Cut Image in Page. Link: Edit Redact Text Content. Redact Images. Redact Pages. Annotation & Text. Add Text Box. Drawing Markups. PDF Print. Work
delete page from pdf file online; cut pages out of pdf
VB.NET PDF- View PDF Online with VB.NET HTML5 PDF Viewer
from PDF Page. Image: Copy, Paste, Cut Image in Redact Text Content. Redact Images. Redact Pages. Annotation & Add Text. Add Text Box. Drawing Markups. PDF Print.
delete page on pdf reader; delete page from pdf online
Chapter12
Expansion
ExpansioninT
E
Xisratherdifferentfromprocedurecallsinmostprogramminglanguages.
Thischaptertreatsthecommandsconnectedwithexpansion,andgivesanumberof(non-
trivial)examples.
\relax Donothing.
\expandafter Takethenexttwotokensandplacetheexpansionofthesecondafterthe
first.
\noexpand Donotexpandthenexttoken.
\edef Startamacrodefinition;thereplacementtextisexpandedatdefinitiontime.
\aftergroup Savethenexttokenforinsertionafterthecurrentgroup.
\afterassignment Savethenexttokenforexecutionafterthenextassignmentormacro
definition.
\the ExpandthevalueofvariousquantitiesinT
E
Xintoastringofcharactertokens.
12.1 Introduction
T
E
X’sexpansionprocessoracceptsastreamoftokenscomingoutoftheinputprocessor,
anditsresultisagainastreamoftokens,which it feedstotheexecutionprocessor.For
theinputprocessortherearetwokindsoftokens:expandableandunexpandableones.The
lattercategoryispasseduntouched,anditcontainslargelyassignmentsandtypesettable
material;theformercategory isexpanded,andtheresultofthat expansionisexamined
anew.
12.2 Ordinaryexpansion
Thefollowinglistgivesthoseconstructsthatareexpanded,unlessexpansionisinhibited:
macros
conditionals
\number,\romannumeral
\string,\fontname,\jobname,\meaning,\the
125
VB.NET PDF: Basic SDK Concept of XDoc.PDF
example, you may easily create, load, combine, and split PDF file(s), and add, create, insert, delete, re-order, copy, paste, cut, rotate, and save PDF page(s
delete page from pdf document; delete pages out of a pdf file
Chapter12. Expansion
\csname ... \endcsname
\expandafter,\noexpand
\topmark,\botmark,\firstmark,\splitfirstmark,\splitbotmark
\input,\endinput
Thisisthelistofallinstanceswhereexpansionisinhibited:
whenT
E
Xisreadingatokentobedefinedby
aletassignment,thatis,by\letor\futurelet,
ashorthanddefinition,thatis,by\chardefor\mathchardef,oraregister
def,thatis,\countdef,\dimendef,\skipdef,\muskipdef,or\toksdef,
adefinition,thatisamacrodefinitionwith\def,\gdef,\edef,or\xdef,
thesimpleassignments\readand\font;
whenaparametertextormacroargumentsarebeing read; alsowhen there-
placementtextofacontrolsequencebeingdefinedby\def,\gdef,or\readis
beingread;
whenthetokenlistforatokenvariableor\uppercase,\lowercase,or\write
isbeingread;however,thetokenlistfor\writewillbeexpandedlaterwhenitis
shippedout;
whentokensarebeingdeletedduringerrorrecovery;
whenpartofaconditionalisbeingskipped;
intwoinstanceswhenT
E
Xhastoknowwhatfollows
afteraleftquoteinacontextwherethatisusedtodenoteaninteger(thusin
\catcode‘\athe\aisnotexpanded),or
afteramathshiftcharacterthatbeginsmathmodetoseewhetheranother
mathshiftcharacterfollows(inwhichcaseadisplayopens);
whenanalignmentpreambleisbeingscanned;however,inthiscaseatokenpre-
cededby\spanandthetokensina\tabskipassignmentarestillexpanded.
12.3 Reversingexpansionorder
Everyonceinawhileyouneedtochangethenormalorderofexpansionoftokens.T
E
X
providesseveralmechanismsforthis.Someofthecontrolsequencesinthissectionarenot
strictlyconcernedwithexpansion.
12.3.1 Onestepexpansion:\expandafter
Themostobvioustoolforreversedexpansionorderis\expandafter.Thesequence
\expandaftertoken
1
token
2
expandsto
token
1
theexpansionoftoken
2
Notethefollowing.
Iftoken
2
isamacro,itisreplacedbyitsreplacementtext,notbyitsfinalexpan-
sion.Thus,if
126
VictorEijkhout–T
E
XbyTopic
12.3. Reversingexpansionorder
\def\tokentwo{\ifsomecondition this \else that \fi}
\def\tokenone#1{ ... }
thecall
\expandafter\tokenone\tokentwo
willgive\ifsomeconditionastheparameterto\tokenone:
\tokenone #1-> ...
#1<-\ifsomecondition
Ifthe\tokentwoisamacrowithoneormoreparameters,sufficientlymanysub-
sequenttokenswillbeabsorbedtoformthereplacementtext.
12.3.2 Totalexpansion:\edef
Macrosareusuallydefinedby\def,butforthecaseswhereonewantsthereplacement
texttoreflectcurrentconditions(asopposedtoconditionsatthetimeofthecall),thereis
an‘expandingdefine’,\edef,which expandseverythinginthereplacementtext,before
assigningittothecontrolsequence.
\edef\modedef{This macro was defined in
‘\ifvmode vertical\else \ifmmode math
\else horizontal\fi\fi’ mode}
Themodetestswillbeexecutedat definitiontime,so thereplacement
textwillbeasinglestring.
Asamoreusefulexample,supposethatinafilethatwillbe\inputthe
categorycodeofthe@willbechanged.Onecouldthenwrite
\edef\restorecat{\catcode‘@=\the\catcode‘@}
atthestart,and
\restorecat
attheend.Seepage137forafullyworked-outversionofthis.
Contrarytothe‘onestepexpansion’of\expandafter,theexpansioninsidean\edefis
complete:itgoesonuntilonlyunexpandablecharacterandcontrolsequencetokensremain.
Therearetwoexceptionstothistotalexpansion:
anycontrolsequenceprecededby\noexpandisnotexpanded,and,
if\sometokenlistisatokenlist,theexpression
\the\sometokenlist
isexpandedtothecontentsofthelist,butthecontentsarenotexpandedanyfurther
(seeChapter14forexamples).
Oncertainoccasionsthe\edefcanconvenientlybeabused,inthesensethatoneisnotin-
terestedindefiningacontrolsequence,butonlyintheresultoftheexpansion.Forexample,
withthedefinitions
\def\othermacro{\ifnum1>0 {this}\else {that}\fi}
\def\somemacro#1{ ... }
thecall
\expandafter\somemacro\othermacro
givestheparameterassignment
#1<-\ifnum
VictorEijkhout–T
E
XbyTopic
127
Chapter12. Expansion
Thiscanberepairedbycalling
\edef\next{\noexpand\somemacro\othermacro}\next
Conditionalsarecompletelyexpandedinsidean\edef,sothereplacementtextof\next
willconsistofthesequence
\somemacro{this}
andasubsequentcallto\nextexecutesthisstatement.
12.3.3 \afterassignment
The commandtakesonetokenandsetsitasideforinsertioninthetokenstreamafterthe
nextassignmentormacrodefinition.Ifthefirstassignmentisofaboxtoaboxregister,the
tokenwillbeinsertedrightaftertheopeningbraceofthebox(seepage66).
Onlyonetokencanbesavedthisway;asubsequenttokensavedby\afterassignment
willoverridethefirst.
Letusconsideranexampleoftheuseof\afterassignment.Itisoftendesirabletohave
amacrothatwill
assigntheargumenttosomevariable,andthen
doalittlecalculation,basedonthenewvalueofthevariable.
Thefollowingexampleillustratesthestraightforwardapproach:
\def\setfontsize#1{\thefontsize=#1pt\relax
\baselineskip=1.2\thefontsize\relax}
\setfontsize{10}
Amoreelegantsolutionispossibleusing\afterassignment:
\def\setbaselineskip
{\baselineskip=1.2\thefontsize\relax}
\def\fontsize{\afterassignment\setbaselineskip
\thefontsize}
\fontsize=10pt
Nowthemacrolookslikeanassignment:theequalssignisevenoptional.Inrealityitsex-
pansionendswithavariabletobeassignedto.Thecontrolsequence\setbaselineskip
issavedforexecutionaftertheassignmentto\thefontsize.
Examplesof\afterassignmentinplainT
E
Xarethe\magnificationand\hgluema-
cros.See[31]foranothercreativeapplicationofthiscommand.
12.3.4 \aftergroup
Severaltokenscanbesavedforinsertionafterthecurrentgroupwithan
\aftergrouptoken
command.Thetokensareinsertedafterthegroupinthesequencethe\aftergroupcom-
mandsweregivenin.Thegroupcanbedelimitedeitherbyimplicitorexplicitbraces,or
by\begingroupand\endgroup.
128
VictorEijkhout–T
E
XbyTopic
12.4. Preventingexpansion
{\aftergroup\a \aftergroup\b}
isequivalentto
\a \b
Thiscommandhasmanyapplications.Onecanbefoundinthe\textvcentermacroon
page138;anotheroneisprovidedbythefootnotemechanismofplainT
E
X.
ThefootnotecommandofplainT
E
Xhasthelayout
\footnotefootnotesymbol{footnotetext}
whichlookslikeamacrowithtwoarguments.However,itisundesirabletoscoopupthe
footnotetext,sincethisprecludesforinstancecategorycodechangesinthefootnote.
Whathappensintheplainfootnotemacrois(globally)thefollowing.
The\footnotecommandopensaninsert,
\def\footnote#1{ ...#1... %treat the footnote sign
\insert\footins\bgroup
Intheinsertboxagroupisopened,andan\aftergroupcommandisgivento
closeofftheinsertproperly:
\bgroup\aftergroup\@foot
Thiscommandismeanttowindupaftertheclosingbraceofthetextthattheuser
typedtoendthefootnotetext;theopeningbraceoftheuser’sfootnotetextmust
beremovedby
\let\next=}%end of definition \footnote
whichassignsthenexttoken,thebrace,to\next.
Thefootnotetextissetasordinarytextinthisinsertbox.
Afterthefootnotethecommand\@footdefinedby
\def\@foot{\strut\egroup}
willbeexecuted.
12.4 Preventingexpansion
Sometimesitisnecessarytopreventexpansioninaplacewhereitnormallyoccurs.For
thispurposethecontrolsequences\stringand\noexpandareavailable.
Theuseof\stringisratherlimited,sinceitconvertsacontrolsequencetokenintoastring
ofcharacters,withthevalueof\escapecharusedforthecharacterofcategorycode0.It
iseminentlysuitableforuseina\write,inordertooutputacontrolsequencename(see
alsoChapter30);foranotherapplicationseetheexplanationof\newifinChapter13.
Allcharactersresultingfrom\stringhavecategory code12,‘other’,exceptfor space
characters;theyreceivecode10.SeealsoChapter3.
12.4.1 \noexpand
The\noexpandcommandisexpandable,anditsexpansion isthefollowingtoken.The
meaningofthattokenismadetemporarilyequalto\relax,sothatitcannotbeexpanded
further.
VictorEijkhout–T
E
XbyTopic
129
Documents you may be interested
Documents you may be interested