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

28
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 (2583L/16K).

/* input e.g.:

  if (a
    and b)
    bla;
    
  This will yield ("if (a\n  and b)", "  bla;")
*/
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   

Travelled to 2 computer(s): mqqgnosmbjvj, tvejysmllsmz

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/2
Text MD5: 4981f2d2962418284ea9aaf4844866ab
Transpilation MD5: c81943fe66fa4bf408bd54b19cabb8ff
Author: stefan
Category: javax / parsing
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-10-08 13:37:10
Source code size: 735 bytes / 28 lines
Pitched / IR pitched: No / No
Views / Downloads: 6 / 20
Version history: 1 change(s)
Referenced in: [show references]