Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

30
LINES

< > BotCompany Repo | #1025609 // lines_honoringBrackets - like lines, but keeps bracket-enclosed lines together

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (2585L/16K).

1  
/* input e.g.:
2  
3  
  if (a
4  
    and b)
5  
    bla;
6  
    
7  
  This will yield ("if (a\n  and b)", "  bla;")
8  
  
9  
  Note: doesn't support multi-line strings
10  
*/
11  
static LS lines_honoringBrackets(S text) {
12  
  LS lines = lines(text);
13  
  new LS out;
14  
  int bracketLevel = 0; // how many open brackets
15  
  int start = 0; // line where current block starts
16  
  for i over lines: {
17  
    LS tok = javaTok(lines.get(i));
18  
    for (int j = 1; j < l(tok); j += 2) {
19  
      S t = tok.get(j);
20  
      if (eqOneOf(t, "(", "{", "[")) ++bracketLevel;
21  
      else if (eqOneOf(t, ")", "}", "]")) --bracketLevel;
22  
    }
23  
    if (bracketLevel == 0) {
24  
      out.add(lines_rtrim(subList(lines, start, i+1)));
25  
      start = i+1;
26  
    }
27  
  }
28  
  addIfNempty(out, lines_rtrim(subList(lines, start)));
29  
  ret out;
30  
}

Author comment

Began life as a copy of #1024308

download  show line numbers  debug dex  old transpilations   

Travelled to 6 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1025609
Snippet name: lines_honoringBrackets - like lines, but keeps bracket-enclosed lines together
Eternal ID of this version: #1025609/3
Text MD5: 5663a42b796fb6db8de1b1d2c8fe2c24
Transpilation MD5: 74d975790ef45a75ad37eb9c66bd966b
Author: stefan
Category: javax / parsing
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-10-26 03:11:09
Source code size: 783 bytes / 30 lines
Pitched / IR pitched: No / No
Views / Downloads: 201 / 251
Version history: 2 change(s)
Referenced in: [show references]