Command for nulifying spaces (String.trim()) in latex Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Backward compatibility for command namesHow to make spaces as command argument delimiters?Expandable 'character scanning' command that preserves spacesCreate command to inline an image in a question?LaTeX command for equal (=)LaTeX Document class for department technical reportsFindig the latex-command for a characterlooking for selective latex command replacement methodsEnvironment for respecting spacesSpaces around command with empty output (for comments within paragraphs)

Identifying polygons that intersect with another layer using QGIS?

How do I keep my slimes from escaping their pens?

What is a non-alternating simple group with big order, but relatively few conjugacy classes?

Bete Noir -- no dairy

String `!23` is replaced with `docker` in command line

Why do people hide their license plates in the EU?

Resolving to minmaj7

What is the meaning of the new sigil in Game of Thrones Season 8 intro?

Is it ethical to give a final exam after the professor has quit before teaching the remaining chapters of the course?

porting install scripts : can rpm replace apt?

Should I use a zero-interest credit card for a large one-time purchase?

Extract all GPU name, model and GPU ram

What is Arya's weapon design?

How to call a function with default parameter through a pointer to function that is the return of another function?

How to react to hostile behavior from a senior developer?

What causes the vertical darker bands in my photo?

How does debian/ubuntu knows a package has a updated version

Identify plant with long narrow paired leaves and reddish stems

Short Story with Cinderella as a Voo-doo Witch

What's the purpose of writing one's academic biography in the third person?

What does "fit" mean in this sentence?

Can a non-EU citizen traveling with me come with me through the EU passport line?

When do you get frequent flier miles - when you buy, or when you fly?

Why did the Falcon Heavy center core fall off the ASDS OCISLY barge?



Command for nulifying spaces (String.trim()) in latex



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Backward compatibility for command namesHow to make spaces as command argument delimiters?Expandable 'character scanning' command that preserves spacesCreate command to inline an image in a question?LaTeX command for equal (=)LaTeX Document class for department technical reportsFindig the latex-command for a characterlooking for selective latex command replacement methodsEnvironment for respecting spacesSpaces around command with empty output (for comments within paragraphs)










3















I want to declare a variable in class that takes in the font name from the preamble of the TeX file.
Something like docFont<Variable>. Is there a command that could nullify the space key in latex? For example docFont Arial would return the same result as docFontArial.



My myclass.cls File is something like this:



NeedsTeXFormatLaTeX2e
ProvidesClassmyclass[2019/04/09 Standard HomeWork Template]
LoadClass[a4paper,12pt,onecolumn,final]article
RequirePackgeetoolbox
defhFont#1gdef@hFont#1
def@hFont@latex@warning@no@lineNo noexpandhFont given
BeforeBeginEnvironmentdocument
RequirePackagexepersian
settextfont@hFont



And my *.Tex file is something like this:



documentclassmyclass
hFontArial %Document Persian Font
begindocument
something
enddocument









share|improve this question



















  • 2





    Are you talking about some sort of string.Trim() you would find in other languages? You can check out tl_trim_spaces:n from expl3 – texdoc interface3 has the documentation.

    – Sean Allred
    Apr 11 at 10:00











  • @SeanAllred This is exactly what I am looking for

    – Al_Fh
    Apr 11 at 10:00






  • 2





    Can you expand your question with a complete MWE? Due to expansion concerns, the exact context of how you want to use this macro will determine its implementation.

    – Sean Allred
    Apr 11 at 10:02











  • @SeanAllred edited.

    – Al_Fh
    Apr 11 at 10:13















3















I want to declare a variable in class that takes in the font name from the preamble of the TeX file.
Something like docFont<Variable>. Is there a command that could nullify the space key in latex? For example docFont Arial would return the same result as docFontArial.



My myclass.cls File is something like this:



NeedsTeXFormatLaTeX2e
ProvidesClassmyclass[2019/04/09 Standard HomeWork Template]
LoadClass[a4paper,12pt,onecolumn,final]article
RequirePackgeetoolbox
defhFont#1gdef@hFont#1
def@hFont@latex@warning@no@lineNo noexpandhFont given
BeforeBeginEnvironmentdocument
RequirePackagexepersian
settextfont@hFont



And my *.Tex file is something like this:



documentclassmyclass
hFontArial %Document Persian Font
begindocument
something
enddocument









share|improve this question



















  • 2





    Are you talking about some sort of string.Trim() you would find in other languages? You can check out tl_trim_spaces:n from expl3 – texdoc interface3 has the documentation.

    – Sean Allred
    Apr 11 at 10:00











  • @SeanAllred This is exactly what I am looking for

    – Al_Fh
    Apr 11 at 10:00






  • 2





    Can you expand your question with a complete MWE? Due to expansion concerns, the exact context of how you want to use this macro will determine its implementation.

    – Sean Allred
    Apr 11 at 10:02











  • @SeanAllred edited.

    – Al_Fh
    Apr 11 at 10:13













3












3








3








I want to declare a variable in class that takes in the font name from the preamble of the TeX file.
Something like docFont<Variable>. Is there a command that could nullify the space key in latex? For example docFont Arial would return the same result as docFontArial.



My myclass.cls File is something like this:



NeedsTeXFormatLaTeX2e
ProvidesClassmyclass[2019/04/09 Standard HomeWork Template]
LoadClass[a4paper,12pt,onecolumn,final]article
RequirePackgeetoolbox
defhFont#1gdef@hFont#1
def@hFont@latex@warning@no@lineNo noexpandhFont given
BeforeBeginEnvironmentdocument
RequirePackagexepersian
settextfont@hFont



And my *.Tex file is something like this:



documentclassmyclass
hFontArial %Document Persian Font
begindocument
something
enddocument









share|improve this question
















I want to declare a variable in class that takes in the font name from the preamble of the TeX file.
Something like docFont<Variable>. Is there a command that could nullify the space key in latex? For example docFont Arial would return the same result as docFontArial.



My myclass.cls File is something like this:



NeedsTeXFormatLaTeX2e
ProvidesClassmyclass[2019/04/09 Standard HomeWork Template]
LoadClass[a4paper,12pt,onecolumn,final]article
RequirePackgeetoolbox
defhFont#1gdef@hFont#1
def@hFont@latex@warning@no@lineNo noexpandhFont given
BeforeBeginEnvironmentdocument
RequirePackagexepersian
settextfont@hFont



And my *.Tex file is something like this:



documentclassmyclass
hFontArial %Document Persian Font
begindocument
something
enddocument






macros documentclass-writing






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 12 at 11:19







Al_Fh

















asked Apr 11 at 9:53









Al_FhAl_Fh

997




997







  • 2





    Are you talking about some sort of string.Trim() you would find in other languages? You can check out tl_trim_spaces:n from expl3 – texdoc interface3 has the documentation.

    – Sean Allred
    Apr 11 at 10:00











  • @SeanAllred This is exactly what I am looking for

    – Al_Fh
    Apr 11 at 10:00






  • 2





    Can you expand your question with a complete MWE? Due to expansion concerns, the exact context of how you want to use this macro will determine its implementation.

    – Sean Allred
    Apr 11 at 10:02











  • @SeanAllred edited.

    – Al_Fh
    Apr 11 at 10:13












  • 2





    Are you talking about some sort of string.Trim() you would find in other languages? You can check out tl_trim_spaces:n from expl3 – texdoc interface3 has the documentation.

    – Sean Allred
    Apr 11 at 10:00











  • @SeanAllred This is exactly what I am looking for

    – Al_Fh
    Apr 11 at 10:00






  • 2





    Can you expand your question with a complete MWE? Due to expansion concerns, the exact context of how you want to use this macro will determine its implementation.

    – Sean Allred
    Apr 11 at 10:02











  • @SeanAllred edited.

    – Al_Fh
    Apr 11 at 10:13







2




2





Are you talking about some sort of string.Trim() you would find in other languages? You can check out tl_trim_spaces:n from expl3 – texdoc interface3 has the documentation.

– Sean Allred
Apr 11 at 10:00





Are you talking about some sort of string.Trim() you would find in other languages? You can check out tl_trim_spaces:n from expl3 – texdoc interface3 has the documentation.

– Sean Allred
Apr 11 at 10:00













@SeanAllred This is exactly what I am looking for

– Al_Fh
Apr 11 at 10:00





@SeanAllred This is exactly what I am looking for

– Al_Fh
Apr 11 at 10:00




2




2





Can you expand your question with a complete MWE? Due to expansion concerns, the exact context of how you want to use this macro will determine its implementation.

– Sean Allred
Apr 11 at 10:02





Can you expand your question with a complete MWE? Due to expansion concerns, the exact context of how you want to use this macro will determine its implementation.

– Sean Allred
Apr 11 at 10:02













@SeanAllred edited.

– Al_Fh
Apr 11 at 10:13





@SeanAllred edited.

– Al_Fh
Apr 11 at 10:13










2 Answers
2






active

oldest

votes


















7














You can use the trimspaces package for this purpose.



Simple examples



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*trim[1]%
trim@spaces@noexp#1%

makeatother

begindocument
textbar trima bcd eftextbar

textbar trim a bcd ef textbar
enddocument


enter image description here



Here is another way that first stores the result of the trimming operation in a macro (my@tmp@trimmed), then expands this macro:



documentclassarticle
usepackagetrimspaces

makeatletter

newcommand*trim[1]%
begingroup
edefmy@tmp@trimmedtrim@spaces@noexp#1%
expandafter
endgroup
my@tmp@trimmed


makeatother

begindocument
Xtrima bc defY

Xtrim a bc def Y
enddocument


enter image description here



Overview of the possibilities



The trimspaces package offers several variants depending on what you want:



  • left-only, right-only or both-sides trimming (left: trim@pre@space and trim@pre@space@noexp; right: trim@post@space, trim@post@space@noexp; both: trim@spaces, trim@spaces@noexp);

  • whether you want to expand tokens while trimming, or not (so far, I chose the @noexp variant in the examples, that just trims without expanding; otherwise, see trim@spaces in the package documentation and below).

It also allows one to trim the contents of an already-existing macro. Here is the example from the documentation concerning this point:



defb b foo ! 
trim@spaces@inb


is equivalent to



defbb foo !


trim@pre@space@in and trim@post@space@in offer analoguous functionality for left-only, resp. right-only trimming.



Difference between trim@spaces and trim@spaces@noexp



The following example illustrates the functional difference between trim@spaces and trim@spaces@noexp1: the former expands tokens from its argument whereas the latter doesn't (they can then be expanded “at the last moment”, which is often desirable).



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*storeTrimmedImmediateExp[2]%
xdef#1trim@spaces#2%


newcommand*storeTrimmedNoExp[2]%
xdef#1trim@spaces@noexp#2%

makeatother

newcommand*foo[default foo]
storeTrimmedImmediateExpimmediateExp afoo b % foo is expanded now
storeTrimmedNoExpdelayedExp afoo b % foo is not expanded yet
renewcommand*foo[updated foo]


begindocument
textbar immediateExp textbar % there is no foo inside immediateExp

textbar delayedExp textbar % foo is expanded after delayedExp
enddocument


enter image description here



Corner cases



This last example explores a few corner cases with various kinds of spaces:



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*trim[1]%
trim@spaces@noexp#1%

makeatother

% Define implicitSpace to be let-equal to a space token
begingroup
def\globalletimplicitSpace= \ % cf. TeXbook exercise 24.6
endgroup

begindocument
Atrima bc defB

Ctrim a bc def D

Etrim a bc def F % control spaces aren't trimmed

% Implicit space tokens are... sometimes trimmed (?)
GtrimimplicitSpace a bc defimplicitSpaceH
enddocument


enter image description here



Footnote



  1. The other difference being that trim@spaces@noexp requires an eTeX engine, while trim@spaces doesn't.





share|improve this answer

























  • Simple and easy to grasp. Thank you very much.

    – Al_Fh
    Apr 11 at 10:39






  • 1





    I'm glad it helped you. I realized there was an even simpler method, therefore I have expanded my answer starting with that one, then showing the difference between trim@spaces and trim@spaces@noexp, and finally testing the behavior of trim@spaces@noexp with various kinds of spaces.

    – frougon
    Apr 11 at 22:12


















5














Here, I preprocess the argument to docfont and pass the result to docfontcore, which solely for the purposes of demonstration, detokenizes its argument, so that you can see that it gives the originally specified tokens, trimmed of leading and trailing (but not intermediate) spaces.



The last MWE example shows that passing macros poses no impediment to the approach.



documentclassarticle
usepackage[T1]fontenc
usepackagelistofitems
newcommanddocfont[1]%
setsepchar!!!!% USE SOMETHING NOT IN THE FONTNAMES
readlist*trimmedvar#1%
itemtomacrotrimmedvar[1]thetrimmedvar%
expandafterdocfontcoreexpandafterthetrimmedvar%

newcommanddocfontcore[1][detokenize#1]
begindocument
docfont Arial Bold
docfontArial Bold
docfontArial Bold

newcommandmyfontPalatino
docfont myfont-oblique
enddocument


enter image description here






share|improve this answer

























  • Thank you very much. I will start reading more into this later. Much appreciated.

    – Al_Fh
    Apr 11 at 10:39












Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "85"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2ftex.stackexchange.com%2fquestions%2f484288%2fcommand-for-nulifying-spaces-string-trim-in-latex%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









7














You can use the trimspaces package for this purpose.



Simple examples



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*trim[1]%
trim@spaces@noexp#1%

makeatother

begindocument
textbar trima bcd eftextbar

textbar trim a bcd ef textbar
enddocument


enter image description here



Here is another way that first stores the result of the trimming operation in a macro (my@tmp@trimmed), then expands this macro:



documentclassarticle
usepackagetrimspaces

makeatletter

newcommand*trim[1]%
begingroup
edefmy@tmp@trimmedtrim@spaces@noexp#1%
expandafter
endgroup
my@tmp@trimmed


makeatother

begindocument
Xtrima bc defY

Xtrim a bc def Y
enddocument


enter image description here



Overview of the possibilities



The trimspaces package offers several variants depending on what you want:



  • left-only, right-only or both-sides trimming (left: trim@pre@space and trim@pre@space@noexp; right: trim@post@space, trim@post@space@noexp; both: trim@spaces, trim@spaces@noexp);

  • whether you want to expand tokens while trimming, or not (so far, I chose the @noexp variant in the examples, that just trims without expanding; otherwise, see trim@spaces in the package documentation and below).

It also allows one to trim the contents of an already-existing macro. Here is the example from the documentation concerning this point:



defb b foo ! 
trim@spaces@inb


is equivalent to



defbb foo !


trim@pre@space@in and trim@post@space@in offer analoguous functionality for left-only, resp. right-only trimming.



Difference between trim@spaces and trim@spaces@noexp



The following example illustrates the functional difference between trim@spaces and trim@spaces@noexp1: the former expands tokens from its argument whereas the latter doesn't (they can then be expanded “at the last moment”, which is often desirable).



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*storeTrimmedImmediateExp[2]%
xdef#1trim@spaces#2%


newcommand*storeTrimmedNoExp[2]%
xdef#1trim@spaces@noexp#2%

makeatother

newcommand*foo[default foo]
storeTrimmedImmediateExpimmediateExp afoo b % foo is expanded now
storeTrimmedNoExpdelayedExp afoo b % foo is not expanded yet
renewcommand*foo[updated foo]


begindocument
textbar immediateExp textbar % there is no foo inside immediateExp

textbar delayedExp textbar % foo is expanded after delayedExp
enddocument


enter image description here



Corner cases



This last example explores a few corner cases with various kinds of spaces:



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*trim[1]%
trim@spaces@noexp#1%

makeatother

% Define implicitSpace to be let-equal to a space token
begingroup
def\globalletimplicitSpace= \ % cf. TeXbook exercise 24.6
endgroup

begindocument
Atrima bc defB

Ctrim a bc def D

Etrim a bc def F % control spaces aren't trimmed

% Implicit space tokens are... sometimes trimmed (?)
GtrimimplicitSpace a bc defimplicitSpaceH
enddocument


enter image description here



Footnote



  1. The other difference being that trim@spaces@noexp requires an eTeX engine, while trim@spaces doesn't.





share|improve this answer

























  • Simple and easy to grasp. Thank you very much.

    – Al_Fh
    Apr 11 at 10:39






  • 1





    I'm glad it helped you. I realized there was an even simpler method, therefore I have expanded my answer starting with that one, then showing the difference between trim@spaces and trim@spaces@noexp, and finally testing the behavior of trim@spaces@noexp with various kinds of spaces.

    – frougon
    Apr 11 at 22:12















7














You can use the trimspaces package for this purpose.



Simple examples



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*trim[1]%
trim@spaces@noexp#1%

makeatother

begindocument
textbar trima bcd eftextbar

textbar trim a bcd ef textbar
enddocument


enter image description here



Here is another way that first stores the result of the trimming operation in a macro (my@tmp@trimmed), then expands this macro:



documentclassarticle
usepackagetrimspaces

makeatletter

newcommand*trim[1]%
begingroup
edefmy@tmp@trimmedtrim@spaces@noexp#1%
expandafter
endgroup
my@tmp@trimmed


makeatother

begindocument
Xtrima bc defY

Xtrim a bc def Y
enddocument


enter image description here



Overview of the possibilities



The trimspaces package offers several variants depending on what you want:



  • left-only, right-only or both-sides trimming (left: trim@pre@space and trim@pre@space@noexp; right: trim@post@space, trim@post@space@noexp; both: trim@spaces, trim@spaces@noexp);

  • whether you want to expand tokens while trimming, or not (so far, I chose the @noexp variant in the examples, that just trims without expanding; otherwise, see trim@spaces in the package documentation and below).

It also allows one to trim the contents of an already-existing macro. Here is the example from the documentation concerning this point:



defb b foo ! 
trim@spaces@inb


is equivalent to



defbb foo !


trim@pre@space@in and trim@post@space@in offer analoguous functionality for left-only, resp. right-only trimming.



Difference between trim@spaces and trim@spaces@noexp



The following example illustrates the functional difference between trim@spaces and trim@spaces@noexp1: the former expands tokens from its argument whereas the latter doesn't (they can then be expanded “at the last moment”, which is often desirable).



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*storeTrimmedImmediateExp[2]%
xdef#1trim@spaces#2%


newcommand*storeTrimmedNoExp[2]%
xdef#1trim@spaces@noexp#2%

makeatother

newcommand*foo[default foo]
storeTrimmedImmediateExpimmediateExp afoo b % foo is expanded now
storeTrimmedNoExpdelayedExp afoo b % foo is not expanded yet
renewcommand*foo[updated foo]


begindocument
textbar immediateExp textbar % there is no foo inside immediateExp

textbar delayedExp textbar % foo is expanded after delayedExp
enddocument


enter image description here



Corner cases



This last example explores a few corner cases with various kinds of spaces:



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*trim[1]%
trim@spaces@noexp#1%

makeatother

% Define implicitSpace to be let-equal to a space token
begingroup
def\globalletimplicitSpace= \ % cf. TeXbook exercise 24.6
endgroup

begindocument
Atrima bc defB

Ctrim a bc def D

Etrim a bc def F % control spaces aren't trimmed

% Implicit space tokens are... sometimes trimmed (?)
GtrimimplicitSpace a bc defimplicitSpaceH
enddocument


enter image description here



Footnote



  1. The other difference being that trim@spaces@noexp requires an eTeX engine, while trim@spaces doesn't.





share|improve this answer

























  • Simple and easy to grasp. Thank you very much.

    – Al_Fh
    Apr 11 at 10:39






  • 1





    I'm glad it helped you. I realized there was an even simpler method, therefore I have expanded my answer starting with that one, then showing the difference between trim@spaces and trim@spaces@noexp, and finally testing the behavior of trim@spaces@noexp with various kinds of spaces.

    – frougon
    Apr 11 at 22:12













7












7








7







You can use the trimspaces package for this purpose.



Simple examples



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*trim[1]%
trim@spaces@noexp#1%

makeatother

begindocument
textbar trima bcd eftextbar

textbar trim a bcd ef textbar
enddocument


enter image description here



Here is another way that first stores the result of the trimming operation in a macro (my@tmp@trimmed), then expands this macro:



documentclassarticle
usepackagetrimspaces

makeatletter

newcommand*trim[1]%
begingroup
edefmy@tmp@trimmedtrim@spaces@noexp#1%
expandafter
endgroup
my@tmp@trimmed


makeatother

begindocument
Xtrima bc defY

Xtrim a bc def Y
enddocument


enter image description here



Overview of the possibilities



The trimspaces package offers several variants depending on what you want:



  • left-only, right-only or both-sides trimming (left: trim@pre@space and trim@pre@space@noexp; right: trim@post@space, trim@post@space@noexp; both: trim@spaces, trim@spaces@noexp);

  • whether you want to expand tokens while trimming, or not (so far, I chose the @noexp variant in the examples, that just trims without expanding; otherwise, see trim@spaces in the package documentation and below).

It also allows one to trim the contents of an already-existing macro. Here is the example from the documentation concerning this point:



defb b foo ! 
trim@spaces@inb


is equivalent to



defbb foo !


trim@pre@space@in and trim@post@space@in offer analoguous functionality for left-only, resp. right-only trimming.



Difference between trim@spaces and trim@spaces@noexp



The following example illustrates the functional difference between trim@spaces and trim@spaces@noexp1: the former expands tokens from its argument whereas the latter doesn't (they can then be expanded “at the last moment”, which is often desirable).



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*storeTrimmedImmediateExp[2]%
xdef#1trim@spaces#2%


newcommand*storeTrimmedNoExp[2]%
xdef#1trim@spaces@noexp#2%

makeatother

newcommand*foo[default foo]
storeTrimmedImmediateExpimmediateExp afoo b % foo is expanded now
storeTrimmedNoExpdelayedExp afoo b % foo is not expanded yet
renewcommand*foo[updated foo]


begindocument
textbar immediateExp textbar % there is no foo inside immediateExp

textbar delayedExp textbar % foo is expanded after delayedExp
enddocument


enter image description here



Corner cases



This last example explores a few corner cases with various kinds of spaces:



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*trim[1]%
trim@spaces@noexp#1%

makeatother

% Define implicitSpace to be let-equal to a space token
begingroup
def\globalletimplicitSpace= \ % cf. TeXbook exercise 24.6
endgroup

begindocument
Atrima bc defB

Ctrim a bc def D

Etrim a bc def F % control spaces aren't trimmed

% Implicit space tokens are... sometimes trimmed (?)
GtrimimplicitSpace a bc defimplicitSpaceH
enddocument


enter image description here



Footnote



  1. The other difference being that trim@spaces@noexp requires an eTeX engine, while trim@spaces doesn't.





share|improve this answer















You can use the trimspaces package for this purpose.



Simple examples



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*trim[1]%
trim@spaces@noexp#1%

makeatother

begindocument
textbar trima bcd eftextbar

textbar trim a bcd ef textbar
enddocument


enter image description here



Here is another way that first stores the result of the trimming operation in a macro (my@tmp@trimmed), then expands this macro:



documentclassarticle
usepackagetrimspaces

makeatletter

newcommand*trim[1]%
begingroup
edefmy@tmp@trimmedtrim@spaces@noexp#1%
expandafter
endgroup
my@tmp@trimmed


makeatother

begindocument
Xtrima bc defY

Xtrim a bc def Y
enddocument


enter image description here



Overview of the possibilities



The trimspaces package offers several variants depending on what you want:



  • left-only, right-only or both-sides trimming (left: trim@pre@space and trim@pre@space@noexp; right: trim@post@space, trim@post@space@noexp; both: trim@spaces, trim@spaces@noexp);

  • whether you want to expand tokens while trimming, or not (so far, I chose the @noexp variant in the examples, that just trims without expanding; otherwise, see trim@spaces in the package documentation and below).

It also allows one to trim the contents of an already-existing macro. Here is the example from the documentation concerning this point:



defb b foo ! 
trim@spaces@inb


is equivalent to



defbb foo !


trim@pre@space@in and trim@post@space@in offer analoguous functionality for left-only, resp. right-only trimming.



Difference between trim@spaces and trim@spaces@noexp



The following example illustrates the functional difference between trim@spaces and trim@spaces@noexp1: the former expands tokens from its argument whereas the latter doesn't (they can then be expanded “at the last moment”, which is often desirable).



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*storeTrimmedImmediateExp[2]%
xdef#1trim@spaces#2%


newcommand*storeTrimmedNoExp[2]%
xdef#1trim@spaces@noexp#2%

makeatother

newcommand*foo[default foo]
storeTrimmedImmediateExpimmediateExp afoo b % foo is expanded now
storeTrimmedNoExpdelayedExp afoo b % foo is not expanded yet
renewcommand*foo[updated foo]


begindocument
textbar immediateExp textbar % there is no foo inside immediateExp

textbar delayedExp textbar % foo is expanded after delayedExp
enddocument


enter image description here



Corner cases



This last example explores a few corner cases with various kinds of spaces:



documentclassarticle
usepackagetrimspaces

makeatletter
newcommand*trim[1]%
trim@spaces@noexp#1%

makeatother

% Define implicitSpace to be let-equal to a space token
begingroup
def\globalletimplicitSpace= \ % cf. TeXbook exercise 24.6
endgroup

begindocument
Atrima bc defB

Ctrim a bc def D

Etrim a bc def F % control spaces aren't trimmed

% Implicit space tokens are... sometimes trimmed (?)
GtrimimplicitSpace a bc defimplicitSpaceH
enddocument


enter image description here



Footnote



  1. The other difference being that trim@spaces@noexp requires an eTeX engine, while trim@spaces doesn't.






share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 12 at 7:08

























answered Apr 11 at 10:07









frougonfrougon

1,054712




1,054712












  • Simple and easy to grasp. Thank you very much.

    – Al_Fh
    Apr 11 at 10:39






  • 1





    I'm glad it helped you. I realized there was an even simpler method, therefore I have expanded my answer starting with that one, then showing the difference between trim@spaces and trim@spaces@noexp, and finally testing the behavior of trim@spaces@noexp with various kinds of spaces.

    – frougon
    Apr 11 at 22:12

















  • Simple and easy to grasp. Thank you very much.

    – Al_Fh
    Apr 11 at 10:39






  • 1





    I'm glad it helped you. I realized there was an even simpler method, therefore I have expanded my answer starting with that one, then showing the difference between trim@spaces and trim@spaces@noexp, and finally testing the behavior of trim@spaces@noexp with various kinds of spaces.

    – frougon
    Apr 11 at 22:12
















Simple and easy to grasp. Thank you very much.

– Al_Fh
Apr 11 at 10:39





Simple and easy to grasp. Thank you very much.

– Al_Fh
Apr 11 at 10:39




1




1





I'm glad it helped you. I realized there was an even simpler method, therefore I have expanded my answer starting with that one, then showing the difference between trim@spaces and trim@spaces@noexp, and finally testing the behavior of trim@spaces@noexp with various kinds of spaces.

– frougon
Apr 11 at 22:12





I'm glad it helped you. I realized there was an even simpler method, therefore I have expanded my answer starting with that one, then showing the difference between trim@spaces and trim@spaces@noexp, and finally testing the behavior of trim@spaces@noexp with various kinds of spaces.

– frougon
Apr 11 at 22:12











5














Here, I preprocess the argument to docfont and pass the result to docfontcore, which solely for the purposes of demonstration, detokenizes its argument, so that you can see that it gives the originally specified tokens, trimmed of leading and trailing (but not intermediate) spaces.



The last MWE example shows that passing macros poses no impediment to the approach.



documentclassarticle
usepackage[T1]fontenc
usepackagelistofitems
newcommanddocfont[1]%
setsepchar!!!!% USE SOMETHING NOT IN THE FONTNAMES
readlist*trimmedvar#1%
itemtomacrotrimmedvar[1]thetrimmedvar%
expandafterdocfontcoreexpandafterthetrimmedvar%

newcommanddocfontcore[1][detokenize#1]
begindocument
docfont Arial Bold
docfontArial Bold
docfontArial Bold

newcommandmyfontPalatino
docfont myfont-oblique
enddocument


enter image description here






share|improve this answer

























  • Thank you very much. I will start reading more into this later. Much appreciated.

    – Al_Fh
    Apr 11 at 10:39
















5














Here, I preprocess the argument to docfont and pass the result to docfontcore, which solely for the purposes of demonstration, detokenizes its argument, so that you can see that it gives the originally specified tokens, trimmed of leading and trailing (but not intermediate) spaces.



The last MWE example shows that passing macros poses no impediment to the approach.



documentclassarticle
usepackage[T1]fontenc
usepackagelistofitems
newcommanddocfont[1]%
setsepchar!!!!% USE SOMETHING NOT IN THE FONTNAMES
readlist*trimmedvar#1%
itemtomacrotrimmedvar[1]thetrimmedvar%
expandafterdocfontcoreexpandafterthetrimmedvar%

newcommanddocfontcore[1][detokenize#1]
begindocument
docfont Arial Bold
docfontArial Bold
docfontArial Bold

newcommandmyfontPalatino
docfont myfont-oblique
enddocument


enter image description here






share|improve this answer

























  • Thank you very much. I will start reading more into this later. Much appreciated.

    – Al_Fh
    Apr 11 at 10:39














5












5








5







Here, I preprocess the argument to docfont and pass the result to docfontcore, which solely for the purposes of demonstration, detokenizes its argument, so that you can see that it gives the originally specified tokens, trimmed of leading and trailing (but not intermediate) spaces.



The last MWE example shows that passing macros poses no impediment to the approach.



documentclassarticle
usepackage[T1]fontenc
usepackagelistofitems
newcommanddocfont[1]%
setsepchar!!!!% USE SOMETHING NOT IN THE FONTNAMES
readlist*trimmedvar#1%
itemtomacrotrimmedvar[1]thetrimmedvar%
expandafterdocfontcoreexpandafterthetrimmedvar%

newcommanddocfontcore[1][detokenize#1]
begindocument
docfont Arial Bold
docfontArial Bold
docfontArial Bold

newcommandmyfontPalatino
docfont myfont-oblique
enddocument


enter image description here






share|improve this answer















Here, I preprocess the argument to docfont and pass the result to docfontcore, which solely for the purposes of demonstration, detokenizes its argument, so that you can see that it gives the originally specified tokens, trimmed of leading and trailing (but not intermediate) spaces.



The last MWE example shows that passing macros poses no impediment to the approach.



documentclassarticle
usepackage[T1]fontenc
usepackagelistofitems
newcommanddocfont[1]%
setsepchar!!!!% USE SOMETHING NOT IN THE FONTNAMES
readlist*trimmedvar#1%
itemtomacrotrimmedvar[1]thetrimmedvar%
expandafterdocfontcoreexpandafterthetrimmedvar%

newcommanddocfontcore[1][detokenize#1]
begindocument
docfont Arial Bold
docfontArial Bold
docfontArial Bold

newcommandmyfontPalatino
docfont myfont-oblique
enddocument


enter image description here







share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 11 at 10:19

























answered Apr 11 at 10:07









Steven B. SegletesSteven B. Segletes

162k9206418




162k9206418












  • Thank you very much. I will start reading more into this later. Much appreciated.

    – Al_Fh
    Apr 11 at 10:39


















  • Thank you very much. I will start reading more into this later. Much appreciated.

    – Al_Fh
    Apr 11 at 10:39

















Thank you very much. I will start reading more into this later. Much appreciated.

– Al_Fh
Apr 11 at 10:39






Thank you very much. I will start reading more into this later. Much appreciated.

– Al_Fh
Apr 11 at 10:39


















draft saved

draft discarded
















































Thanks for contributing an answer to TeX - LaTeX Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2ftex.stackexchange.com%2fquestions%2f484288%2fcommand-for-nulifying-spaces-string-trim-in-latex%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020