R, 196 189 170 bytes
function(x){l=nchar;o=function(y)which(diff(l(y))<0)[1];d=function(x,i)"[<-"(x,i:(j<-i+1),c(a<-substr(x[i],1,l(x[j])),sub(a,x[j],x[i])));while(!is.na(o(x)))x=d(x,o(x));x} A human-readable version:
f2<f<-function(x){ l=nchar; o=function# find the first line in x that is longer than the next line # if no such line exists o(x) will be NA o = function(y) which(diff(l(y))<0)[1] # od(x,i) --> the no. ofclips firstthe line thati isin longerx, thanadding the next lineremainder orto NAx[i+1] d=functiond = function(x,i) "[<-"(x,i:(j<-i+1), c( a<-substr(x[i],1,l(x[j])), sub(a,x[j],x[i]))) # a --> clipped x[i], sub(a,x[j],x[i]) --> expanded x[j] # d(x,i) --> clips the line i in x, adding the remainder to x[i+1] while(!is.na(o(x)))x=d(x,o(x));x } How it works:
- Take the first "bad" line, i.e., line which is longer than the next line, take the "extra" part and add it to the next line
- IfCheck if there are any "bad" lines left, if yes go to #1
(Or in other words, "superfluous" parts fall down until everything that can fall down has fallen down.)
Input: a character vector.
x<-readLines(textConnection("Programming\nPuzzles\n&\nCode\nGolf")) f(x) # [1] "P" "Prog" "&uzz" "Coderam" "Golflesming"