Description
Given a formula, we assign to every parenthesis a number called 'depth' which equals to the number of unbalanced left-parenthesis to the left of it. For a left-parenthesis, the number counts it.
In the following example, the first line is a formula, and the depth of every parenthesis is shown in the second line:
func1(func2(x) + y) + func3(z)
     1     2 1    0        1 0
The job is inserting a newline character after every right-parenthesis of depth 0.
Raw Input
func1(x) + func2(y) + func3(z)
func1(func2(x) + y) + func3(z)
func1(x) + func2(func3(y) + func4(z)) + func5(w)
Desired Output
func1(x)
 + func2(y)
 + func3(z)
func1(func2(x) + y)
 + func3(z)
func1(x)
 + func2(func3(y) + func4(z))
 + func5(w)
Script and Comments
Script1
[ 1] /\n/!s/^.*/\n&\n/
[ 2] :loop
[ 3] s/\n\([^()][^()]*\)\(.*\n\)/\1\n\2/
[ 4] s/\n(\(.*\n\)/(\n\1#/
[ 5] s/\n)\(.*\n\)#/)\n\1/
[ 6] /\n..*\n./b loop
[ 7] P
[ 8] /\n\n/d
[ 9] s/\n$//
[10] D
Comments
  1. Step [1] is used to add a newline character as a mark before the formula, and append a counter to the end of the formula, separating them with a newline character.
  2. Step [3] will advance the mark until a left or a right parenthesis is reached.
  3. If the character to the right of the mark is '(' or ')', we use Step [4]/Step [5] to increase/decrease the counter by 1.
  4. Step [6] will make sed branch to Step [2] if the formula has not been parsed completely.
  5. If the Pattern Space (abbreviated to PS) matches
    • \n..*\n., then the formula has not been examined completely (\n..*), and the counter is not zero(\n.); we use Step [6] to make sed branch to Step [2].
    • \n\n, the end of the formula is reached; we use Step [7] to print it no matter whether every left/right-parenthesis is balanced or not, then 'd' (Step [8]) to delete it.
    • otherwise, the first '\n' is preceded by a balanced part of the formula, we use 'P' (Step [7]) to print it, Step [8] to remove the trailing newline, Step [9] to remove the balanced part and make sed to examine remaining parts as another formula.