Turns out this question is very similar to Ignore whitespace with PEG.js
It's all about ignoring whitespaces and newlines. I actually don't know why the above code fails, but after playing around, I managed to get pegjs to do what I want
Start
= List
Character
= [^ \t\r\n"("")"]
LeftParenthesis
= "("
RightParenthesis
= ")"
Separator
= [ \t\r\n]
Token
= List
/ token:Character+{return token.join("");}
Tuple
= first:Token second:Separator+ rest:Tuple*{
return rest.length > 0 ? first.concat([" "]).concat(rest) : first;
}
/ Token
List
= left:LeftParenthesis Separator* token:Tuple Separator* right:RightParenthesis{
return [left].concat(token).concat([right]).join("");
}
So, when you give the following string to parse:
(f x
(g y (
h z t) ) )
The parser outputs
"(f x (g y (h z t)))"
which is exactly what I wanted