(I'm using ConTeXt, but I suspect the answer will lie in plain TeX.)
I've created an environment that takes one argument myBufferName, and stores its contents in a buffer of that name. Unfortunately, all spaces after the argument are gobbled, and I don't know how to stop this properly. The usual gobble-stoppers, {} and \, end up in the buffer verbatim if I put them after \dostartbuffer.
\startluacode
-- Print contents of buffer b to stdout and tmp.txt for inspection
function printbuffer(b)
-- Once to stdout ...
print('====')
print(buffers.getcontent(b))
print('====')
-- ... and once to tmp.txt.
jan = io.open('tmp.txt', 'w')
jan:write(buffers.getcontent(b))
jan:close()
end
\stopluacode
% This environment stores its contents in a custom-named buffer.
% (The #1 merely allows whitespace, like this: `\startMyBuffer [name]`)
\def\startMyBuffer#1[#2]
{% Store the name --- we'll need it when defining stopMyBuffer
\def\myBufferName{#2}
% ConTeXt macro that defines the \start... and \stop... commands.
\dostartbuffer[#2][startMyBuffer][stopMyBuffer]}
%% % Hack I currently use: a dot at the end of the definition.
%% \def\startMyBuffer#1[#2]
%% {\def\myBufferName{#2}
%% \dostartbuffer[#2][startMyBuffer][stopMyBuffer].}
%% % ^
%% % |
%% % I later remove the dot using Lua.
% On closing the buffer, print its contents.
\def\stopMyBuffer
{\ctxlua
{printbuffer('\myBufferName')}}
% Test it. You'll see the first line loses its leading whitespace :-(
\starttext
\startMyBuffer[myNameIsNobody]
Andra moi ennepe,
mousa,
polutropon.
\stopMyBuffer
\stoptext
When you try running it, this gives
Andra moi ennepe,
mousa,
polutropon.
as the buffer's contents.