1

I need a macro to behave differently in case it's at the end of a line. Is there any way to check something like that?

\documentclass[11pt]{memoir}

\newcommand{\test}{ % if at the end of line % Print A % else % Print B }

\begin{document} Hello, \test how are you doing? % Should print B

Hello, how are you doing? \test % Should print A

\test Hello, how are you doing? % Should print B

\end{document}

Thank you

Edit: I really meant at the end of a paragraph, but I'm going to leave the question as is, because there are good answers to check both the end of a line and the end of a paragraph.

2 Answers2

3

Checking whether a control sequence is at the “end of a line” is generally not possible in TeX, because endlines are converted to spaces (or ignored altogether if they follow a control word) during tokenization. You can check whether \test is followed by \par, though.

\documentclass[11pt]{memoir}

\makeatletter \newcommand{\test}{% @ifnextchar\par{A}{B}% } \makeatother

\begin{document}

Hello, \test how are you doing? % Should print B

Hello, how are you doing? \test % Should print A

\test Hello, how are you doing? % Should print B

\end{document}

enter image description here

egreg
  • 1,121,712
1

It's possible if you assume that the content are not already tokenized (loosely speaking, the command is not used inside the "argument" of other commands, or the places where \verb|...| fails)

The basic idea is to store the current inputlineno, tokenize one more token, compare inputlineno with it.

\documentclass{article}
\usepackage{tikz}

\def\test{% \count0=\inputlineno \futurelet\tmptoken\testb } \def\testb{% \ifnum\count0=\inputlineno middle of line% \else end of line% \fi }

\usepackage{hyperref} \begin{document} middle of line = \test.

end of line = \test = \test% ...

\textbf{inside a ``normal'' command argument it will always return middle of line: \test }

\begin{tikzpicture} \node [text width = 10cm] at (0, 0) {(I mean, Ti\emph{k}Z node text is not a ``normal'' command argument, see \url{https://tex.stackexchange.com/q/345871/250119}) \test }; \end{tikzpicture}

\end{document}

output

user202729
  • 7,143