Here's a LuaLaTeX-based solution. It allows both single and multiple instances of whitespace characters -- space, tab, and newline characters -- to indicate a column separator. It works with all tabular
, tabular*
, tabularx
, and tabulary
environments.
Two comments:
If a cell contains two or more words separated by spaces, these spaces will need to be replaced with a special character before processing. In the example below, I suggest using the #
character for "real" spaces.
To generate empty cells, use either {}
or &&
(the latter without adjoining spaces). See the example below for applications.
The solution works as follows: A Lua function called sp2amp
(short for "space to ampersand") is set up. It first checks if the input line being processed is inside a tabular
, tabular*
, tabularx
, or tabulary
environment; if so, it sets the Boolean variable ok_2_process
to "true". (If you need to extend the scope of the function to include longtable
environments, do let me know -- it's not difficult to generalize the if
conditions.) If and only if ok_2_process
is equal to "true", all instances of one more more whitesspace characters in the input line are replaced with &
, and all instances of #
are replaced with
(a single space character). By assigning the Lua function to the process_input_buffer
callback, its work is done at a very early stage of processing, before TeX's "eyes" -- let alone its "mouth" and "stomach" -- get to do their work.
% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{luacode,luatexbase}
\begin{luacode}
ok_to_process = false
function sp2amp ( line )
if string.find ( line , "\\begin{tabular[%*xy]?}" ) then
ok_to_process = true
elseif string.find ( line , "\\end{tabular[%*xy]?}" ) then
ok_to_process = false
elseif ok_to_process then
line = string.gsub ( line , "%s+", "&" )
line = string.gsub ( line , "#", " " )
end
return line
end
luatexbase.add_to_callback( "process_input_buffer", sp2amp, "sp2amp")
\end{luacode}
\begin{document}
\begin{tabular}{|*{5}{l|}}
a b c
d A#complete#sentence.\\
e&&g {} i
\end{tabular}
\end{document}
\StrSubstitute
?