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).

/* input e.g.:

  if (a
    and b)
    bla;
    
  This will yield ("if (a\n  and b)", "  bla;")
  
  Note: doesn't support multi-line strings
*/
static LS lines_honoringBrackets(S text) {
  LS lines = lines(text);
  new LS out;
  int bracketLevel = 0; // how many open brackets
  int start = 0; // line where current block starts
  for i over lines: {
    LS tok = javaTok(lines.get(i));
    for (int j = 1; j < l(tok); j += 2) {
      S t = tok.get(j);
      if (eqOneOf(t, "(", "{", "[")) ++bracketLevel;
      else if (eqOneOf(t, ")", "}", "]")) --bracketLevel;
    }
    if (bracketLevel == 0) {
      out.add(lines_rtrim(subList(lines, start, i+1)));
      start = i+1;
    }
  }
  addIfNempty(out, lines_rtrim(subList(lines, start)));
  ret out;
}

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: 188 / 235
Version history: 2 change(s)
Referenced in: [show references]