pegpegjs

How can i make a backslash for change line with peg.js?


Currently, I use '\n' to split each line (paragraph), but now, I want to make a backslash like python for change line.

This is my current rule:

Start
    = _ head:Line tail:('\n'+ l:Line { return l })* _ {
        return [head].concat(tail)
    }

Line = (!'\n' .)+ { return { lines: [ text() ] } }

_ = [ \n\r\t]*

Input:

This is Line 1

This is \ Line
\ 2

Current Output:

[
   {
      "lines": [
         "This is Line 1"
      ]
   },
   {
      "lines": [
         "This is \ Line"
      ]
   },
   {
      "lines": [
         "\ 2"
      ]
   }
]

Expect Output:

[
   {
      "lines": [
         "This is Line 1"
      ]
   },
   {
      "lines": [
         "This is",
         "Line",
         "2"
      ]
   },
]

Solution

  • Oh, I have make it come true by myself, this is my code:

    {
      var lines = [];
      var lineText = "";
      function resetLines() {
        lines = [];
        lineText = "";
      }
    }
    
    Start
      = _ head:Line tail:("\n"+ l:Line { return l; })* _ {
          return [head].concat(tail);
        }
    
    Line
      = ResetLines
        chars:(
          "\n"? "\\" "\n"? {
              lines.push(lineText);
              lineText = "";
            }
          / !"\n" . { lineText += text(); }
        )+ {
          lines.push(lineText);
          return lines;
        }
    
    ResetLines = &" "* { (lines = []), (lineText = ""); }
    
    _ = [ \n\r\t]*
    

    Input:

    This is Line 1
    
    This is\Line
    \2
    
    This is Line 3
    

    Output:

    [
       [
          "This is Line 1"
       ],
       [
          "This is",
          "Line",
          "2"
       ],
       [
          "This is Line 3"
       ]
    ]