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

66
LINES

< > BotCompany Repo | #1016456 // EditRecorder - records text edits compactly

JavaX fragment (include)

1  
sclass EREvent {
2  
}
3  
4  
sclass ERText extends EREvent {
5  
  int startIndex, endIndex;
6  
  S text;
7  
}
8  
9  
sclass ERCaret extends EREvent  {
10  
  int pos;
11  
} 
12  
13  
sclass EditRecorder {
14  
  VF1<EREvent> onEvent;
15  
  
16  
  *() {}
17  
  *(VF1<EREvent> *onEvent) {}
18  
  
19  
  // editor state
20  
  S text = "";
21  
  int caret;
22  
  
23  
  // update the text
24  
  void update(S newText) {
25  
    text = unnull(text);
26  
    newText = unnull(newText);
27  
    S a = text, b = newText;
28  
    int i = lCommonPrefix(a, b);
29  
    a = substring(a, i);
30  
    b = substring(b, i);
31  
    int j = lCommonSuffix(a, b);
32  
    a = substring(a, 0, l(a)-j);
33  
    b = substring(b, 0, l(b)-j);
34  
    
35  
    // Now differing part remains in a and b;
36  
    // i and j give length of unchanged beginning+end
37  
    
38  
    if (empty(a) && empty(b)) ret;
39  
40  
    ERText change = nu(ERText, startIndex := i, endIndex := i+l(a), text := b);
41  
42  
    // Verify the change we made
43  
    assertEquals(newText, replayTextEdit(change, text));
44  
    text = newText;
45  
    
46  
    onEvent(change);
47  
  }
48  
  
49  
  void updateCaret(int pos) {
50  
    if (pos != caret) {
51  
      onEvent(nu(ERCaret, +pos));
52  
      caret = pos;
53  
    }
54  
  }
55  
  
56  
  void onEvent(EREvent e) {
57  
    callF(onEvent, e);
58  
  }
59  
  
60  
  static S replayTextEdit(ERText change, S text) {
61  
    if (change == null) ret text;
62  
    ret substring(text, 0, change.startIndex)
63  
      + change.text
64  
      + substring(text, change.endIndex);
65  
  }
66  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1016456
Snippet name: EditRecorder - records text edits compactly
Eternal ID of this version: #1016456/7
Text MD5: 5d1fc7c5ff4adbf53271eafd03b9ec28
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-06-18 22:14:22
Source code size: 1408 bytes / 66 lines
Pitched / IR pitched: No / No
Views / Downloads: 407 / 943
Version history: 6 change(s)
Referenced in: [show references]