1 // stb_textedit.h - v1.12  - public domain - Sean Barrett
2 // Development of this library was sponsored by RAD Game Tools
3 //
4 // This C header file implements the guts of a multi-line text-editing
5 // widget; you implement display, word-wrapping, and low-level string
6 // insertion/deletion, and stb_textedit will map user inputs into
7 // insertions & deletions, plus updates to the cursor position,
8 // selection state, and undo state.
9 //
10 // It is intended for use in games and other systems that need to build
11 // their own custom widgets and which do not have heavy text-editing
12 // requirements (this library is not recommended for use for editing large
13 // texts, as its performance does not scale and it has limited undo).
14 //
15 // Non-trivial behaviors are modelled after Windows text controls.
16 //
17 //
18 // LICENSE
19 //
20 // See end of file for license information.
21 //
22 //
23 // DEPENDENCIES
24 //
25 // Uses the C runtime function 'memmove', which you can override
26 // by defining STB_TEXTEDIT_memmove before the implementation.
27 // Uses no other functions. Performs no runtime allocations.
28 //
29 //
30 // VERSION HISTORY
31 //
32 //   1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash
33 //   1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield
34 //   1.10 (2016-10-25) supress warnings about casting away const with -Wcast-qual
35 //   1.9  (2016-08-27) customizable move-by-word
36 //   1.8  (2016-04-02) better keyboard handling when mouse button is down
37 //   1.7  (2015-09-13) change y range handling in case baseline is non-0
38 //   1.6  (2015-04-15) allow STB_TEXTEDIT_memmove
39 //   1.5  (2014-09-10) add support for secondary keys for OS X
40 //   1.4  (2014-08-17) fix signed/unsigned warnings
41 //   1.3  (2014-06-19) fix mouse clicking to round to nearest char boundary
42 //   1.2  (2014-05-27) fix some RAD types that had crept into the new code
43 //   1.1  (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE )
44 //   1.0  (2012-07-26) improve documentation, initial public release
45 //   0.3  (2012-02-24) bugfixes, single-line mode; insert mode
46 //   0.2  (2011-11-28) fixes to undo/redo
47 //   0.1  (2010-07-08) initial version
48 //
49 // ADDITIONAL CONTRIBUTORS
50 //
51 //   Ulf Winklemann: move-by-word in 1.1
52 //   Fabian Giesen: secondary key inputs in 1.5
53 //   Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6
54 //
55 //   Bugfixes:
56 //      Scott Graham
57 //      Daniel Keller
58 //      Omar Cornut
59 //      Dan Thompson
60 //
61 // USAGE
62 //
63 // This file behaves differently depending on what symbols you define
64 // before including it.
65 //
66 //
67 // Header-file mode:
68 //
69 //   If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this,
70 //   it will operate in "header file" mode. In this mode, it declares a
71 //   single public symbol, STB_TexteditState, which encapsulates the current
72 //   state of a text widget (except for the string, which you will store
73 //   separately).
74 //
75 //   To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a
76 //   primitive type that defines a single character (e.g. char, wchar_t, etc).
77 //
78 //   To save space or increase undo-ability, you can optionally define the
79 //   following things that are used by the undo system:
80 //
81 //      STB_TEXTEDIT_POSITIONTYPE         small int type encoding a valid cursor position
82 //      STB_TEXTEDIT_UNDOSTATECOUNT       the number of undo states to allow
83 //      STB_TEXTEDIT_UNDOCHARCOUNT        the number of characters to store in the undo buffer
84 //
85 //   If you don't define these, they are set to permissive types and
86 //   moderate sizes. The undo system does no memory allocations, so
87 //   it grows STB_TexteditState by the worst-case storage which is (in bytes):
88 //
89 //        [4 + sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATE_COUNT
90 //      +      sizeof(STB_TEXTEDIT_CHARTYPE)      * STB_TEXTEDIT_UNDOCHAR_COUNT
91 //
92 //
93 // Implementation mode:
94 //
95 //   If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it
96 //   will compile the implementation of the text edit widget, depending
97 //   on a large number of symbols which must be defined before the include.
98 //
99 //   The implementation is defined only as static functions. You will then
100 //   need to provide your own APIs in the same file which will access the
101 //   static functions.
102 //
103 //   The basic concept is that you provide a "string" object which
104 //   behaves like an array of characters. stb_textedit uses indices to
105 //   refer to positions in the string, implicitly representing positions
106 //   in the displayed textedit. This is true for both plain text and
107 //   rich text; even with rich text stb_truetype interacts with your
108 //   code as if there was an array of all the displayed characters.
109 //
110 // Symbols that must be the same in header-file and implementation mode:
111 //
112 //     STB_TEXTEDIT_CHARTYPE             the character type
113 //     STB_TEXTEDIT_POSITIONTYPE         small type that a valid cursor position
114 //     STB_TEXTEDIT_UNDOSTATECOUNT       the number of undo states to allow
115 //     STB_TEXTEDIT_UNDOCHARCOUNT        the number of characters to store in the undo buffer
116 //
117 // Symbols you must define for implementation mode:
118 //
119 //    STB_TEXTEDIT_STRING               the type of object representing a string being edited,
120 //                                      typically this is a wrapper object with other data you need
121 //
122 //    STB_TEXTEDIT_STRINGLEN(obj)       the length of the string (ideally O(1))
123 //    STB_TEXTEDIT_LAYOUTROW(&r,obj,n)  returns the results of laying out a line of characters
124 //                                        starting from character #n (see discussion below)
125 //    STB_TEXTEDIT_GETWIDTH(obj,n,i)    returns the pixel delta from the xpos of the i'th character
126 //                                        to the xpos of the i+1'th char for a line of characters
127 //                                        starting at character #n (i.e. accounts for kerning
128 //                                        with previous char)
129 //    STB_TEXTEDIT_KEYTOTEXT(k)         maps a keyboard input to an insertable character
130 //                                        (return type is int, -1 means not valid to insert)
131 //    STB_TEXTEDIT_GETCHAR(obj,i)       returns the i'th character of obj, 0-based
132 //    STB_TEXTEDIT_NEWLINE              the character returned by _GETCHAR() we recognize
133 //                                        as manually wordwrapping for end-of-line positioning
134 //
135 //    STB_TEXTEDIT_DELETECHARS(obj,i,n)      delete n characters starting at i
136 //    STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n)   insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*)
137 //
138 //    STB_TEXTEDIT_K_SHIFT       a power of two that is or'd in to a keyboard input to represent the shift key
139 //
140 //    STB_TEXTEDIT_K_LEFT        keyboard input to move cursor left
141 //    STB_TEXTEDIT_K_RIGHT       keyboard input to move cursor right
142 //    STB_TEXTEDIT_K_UP          keyboard input to move cursor up
143 //    STB_TEXTEDIT_K_DOWN        keyboard input to move cursor down
144 //    STB_TEXTEDIT_K_LINESTART   keyboard input to move cursor to start of line  // e.g. HOME
145 //    STB_TEXTEDIT_K_LINEEND     keyboard input to move cursor to end of line    // e.g. END
146 //    STB_TEXTEDIT_K_TEXTSTART   keyboard input to move cursor to start of text  // e.g. ctrl-HOME
147 //    STB_TEXTEDIT_K_TEXTEND     keyboard input to move cursor to end of text    // e.g. ctrl-END
148 //    STB_TEXTEDIT_K_DELETE      keyboard input to delete selection or character under cursor
149 //    STB_TEXTEDIT_K_BACKSPACE   keyboard input to delete selection or character left of cursor
150 //    STB_TEXTEDIT_K_UNDO        keyboard input to perform undo
151 //    STB_TEXTEDIT_K_REDO        keyboard input to perform redo
152 //
153 // Optional:
154 //    STB_TEXTEDIT_K_INSERT              keyboard input to toggle insert mode
155 //    STB_TEXTEDIT_IS_SPACE(ch)          true if character is whitespace (e.g. 'isspace'),
156 //                                          required for default WORDLEFT/WORDRIGHT handlers
157 //    STB_TEXTEDIT_MOVEWORDLEFT(obj,i)   custom handler for WORDLEFT, returns index to move cursor to
158 //    STB_TEXTEDIT_MOVEWORDRIGHT(obj,i)  custom handler for WORDRIGHT, returns index to move cursor to
159 //    STB_TEXTEDIT_K_WORDLEFT            keyboard input to move cursor left one word // e.g. ctrl-LEFT
160 //    STB_TEXTEDIT_K_WORDRIGHT           keyboard input to move cursor right one word // e.g. ctrl-RIGHT
161 //    STB_TEXTEDIT_K_LINESTART2          secondary keyboard input to move cursor to start of line
162 //    STB_TEXTEDIT_K_LINEEND2            secondary keyboard input to move cursor to end of line
163 //    STB_TEXTEDIT_K_TEXTSTART2          secondary keyboard input to move cursor to start of text
164 //    STB_TEXTEDIT_K_TEXTEND2            secondary keyboard input to move cursor to end of text
165 //
166 // Todo:
167 //    STB_TEXTEDIT_K_PGUP        keyboard input to move cursor up a page
168 //    STB_TEXTEDIT_K_PGDOWN      keyboard input to move cursor down a page
169 //
170 // Keyboard input must be encoded as a single integer value; e.g. a character code
171 // and some bitflags that represent shift states. to simplify the interface, SHIFT must
172 // be a bitflag, so we can test the shifted state of cursor movements to allow selection,
173 // i.e. (STB_TEXTED_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow.
174 //
175 // You can encode other things, such as CONTROL or ALT, in additional bits, and
176 // then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example,
177 // my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN
178 // bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit,
179 // and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in the
180 // API below. The control keys will only match WM_KEYDOWN events because of the
181 // keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN
182 // bit so it only decodes WM_CHAR events.
183 //
184 // STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed
185 // row of characters assuming they start on the i'th character--the width and
186 // the height and the number of characters consumed. This allows this library
187 // to traverse the entire layout incrementally. You need to compute word-wrapping
188 // here.
189 //
190 // Each textfield keeps its own insert mode state, which is not how normal
191 // applications work. To keep an app-wide insert mode, update/copy the
192 // "insert_mode" field of STB_TexteditState before/after calling API functions.
193 //
194 // API
195 //
196 //    void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line)
197 //
198 //    void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
199 //    void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
200 //    int  stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
201 //    int  stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len)
202 //    void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key)
203 //
204 //    Each of these functions potentially updates the string and updates the
205 //    state.
206 //
207 //      initialize_state:
208 //          set the textedit state to a known good default state when initially
209 //          constructing the textedit.
210 //
211 //      click:
212 //          call this with the mouse x,y on a mouse down; it will update the cursor
213 //          and reset the selection start/end to the cursor point. the x,y must
214 //          be relative to the text widget, with (0,0) being the top left.
215 //
216 //      drag:
217 //          call this with the mouse x,y on a mouse drag/up; it will update the
218 //          cursor and the selection end point
219 //
220 //      cut:
221 //          call this to delete the current selection; returns true if there was
222 //          one. you should FIRST copy the current selection to the system paste buffer.
223 //          (To copy, just copy the current selection out of the string yourself.)
224 //
225 //      paste:
226 //          call this to paste text at the current cursor point or over the current
227 //          selection if there is one.
228 //
229 //      key:
230 //          call this for keyboard inputs sent to the textfield. you can use it
231 //          for "key down" events or for "translated" key events. if you need to
232 //          do both (as in Win32), or distinguish Unicode characters from control
233 //          inputs, set a high bit to distinguish the two; then you can define the
234 //          various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit
235 //          set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is
236 //          clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to
237 //          anything other type you wante before including.
238 //
239 //
240 //   When rendering, you can read the cursor position and selection state from
241 //   the STB_TexteditState.
242 //
243 //
244 // Notes:
245 //
246 // This is designed to be usable in IMGUI, so it allows for the possibility of
247 // running in an IMGUI that has NOT cached the multi-line layout. For this
248 // reason, it provides an interface that is compatible with computing the
249 // layout incrementally--we try to make sure we make as few passes through
250 // as possible. (For example, to locate the mouse pointer in the text, we
251 // could define functions that return the X and Y positions of characters
252 // and binary search Y and then X, but if we're doing dynamic layout this
253 // will run the layout algorithm many times, so instead we manually search
254 // forward in one pass. Similar logic applies to e.g. up-arrow and
255 // down-arrow movement.)
256 //
257 // If it's run in a widget that *has* cached the layout, then this is less
258 // efficient, but it's not horrible on modern computers. But you wouldn't
259 // want to edit million-line files with it.
260 
261 
262 ////////////////////////////////////////////////////////////////////////////
263 ////////////////////////////////////////////////////////////////////////////
264 ////
265 ////   Header-file mode
266 ////
267 ////
268 
269 #ifndef INCLUDE_STB_TEXTEDIT_H
270 #define INCLUDE_STB_TEXTEDIT_H
271 
272 ////////////////////////////////////////////////////////////////////////
273 //
274 //     STB_TexteditState
275 //
276 // Definition of STB_TexteditState which you should store
277 // per-textfield; it includes cursor position, selection state,
278 // and undo state.
279 //
280 
281 #ifndef STB_TEXTEDIT_UNDOSTATECOUNT
282 #define STB_TEXTEDIT_UNDOSTATECOUNT   99
283 #endif
284 #ifndef STB_TEXTEDIT_UNDOCHARCOUNT
285 #define STB_TEXTEDIT_UNDOCHARCOUNT   999
286 #endif
287 #ifndef STB_TEXTEDIT_CHARTYPE
288 #define STB_TEXTEDIT_CHARTYPE        int
289 #endif
290 #ifndef STB_TEXTEDIT_POSITIONTYPE
291 #define STB_TEXTEDIT_POSITIONTYPE    int
292 #endif
293 
294 typedef struct
295 {
296    // private data
297    STB_TEXTEDIT_POSITIONTYPE  where;
298    short           insert_length;
299    short           delete_length;
300    short           char_storage;
301 } StbUndoRecord;
302 
303 typedef struct
304 {
305    // private data
306    StbUndoRecord          undo_rec [STB_TEXTEDIT_UNDOSTATECOUNT];
307    STB_TEXTEDIT_CHARTYPE  undo_char[STB_TEXTEDIT_UNDOCHARCOUNT];
308    short undo_point, redo_point;
309    short undo_char_point, redo_char_point;
310 } StbUndoState;
311 
312 typedef struct
313 {
314    /////////////////////
315    //
316    // public data
317    //
318 
319    int cursor;
320    // position of the text cursor within the string
321 
322    int select_start;          // selection start point
323    int select_end;
324    // selection start and end point in characters; if equal, no selection.
325    // note that start may be less than or greater than end (e.g. when
326    // dragging the mouse, start is where the initial click was, and you
327    // can drag in either direction)
328 
329    unsigned char insert_mode;
330    // each textfield keeps its own insert mode state. to keep an app-wide
331    // insert mode, copy this value in/out of the app state
332 
333    /////////////////////
334    //
335    // private data
336    //
337    unsigned char cursor_at_end_of_line; // not implemented yet
338    unsigned char initialized;
339    unsigned char has_preferred_x;
340    unsigned char single_line;
341    unsigned char padding1, padding2, padding3;
342    float preferred_x; // this determines where the cursor up/down tries to seek to along x
343    StbUndoState undostate;
344 } STB_TexteditState;
345 
346 
347 ////////////////////////////////////////////////////////////////////////
348 //
349 //     StbTexteditRow
350 //
351 // Result of layout query, used by stb_textedit to determine where
352 // the text in each row is.
353 
354 // result of layout query
355 typedef struct
356 {
357    float x0,x1;             // starting x location, end x location (allows for align=right, etc)
358    float baseline_y_delta;  // position of baseline relative to previous row's baseline
359    float ymin,ymax;         // height of row above and below baseline
360    int num_chars;
361 } StbTexteditRow;
362 #endif //INCLUDE_STB_TEXTEDIT_H
363 
364 
365 ////////////////////////////////////////////////////////////////////////////
366 ////////////////////////////////////////////////////////////////////////////
367 ////
368 ////   Implementation mode
369 ////
370 ////
371 
372 
373 // implementation isn't include-guarded, since it might have indirectly
374 // included just the "header" portion
375 #ifdef STB_TEXTEDIT_IMPLEMENTATION
376 
377 #ifndef STB_TEXTEDIT_memmove
378 #include <string.h>
379 #define STB_TEXTEDIT_memmove memmove
380 #endif
381 
382 
383 /////////////////////////////////////////////////////////////////////////////
384 //
385 //      Mouse input handling
386 //
387 
388 // traverse the layout to locate the nearest character to a display position
stb_text_locate_coord(STB_TEXTEDIT_STRING * str,float x,float y)389 static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y)
390 {
391    StbTexteditRow r;
392    int n = STB_TEXTEDIT_STRINGLEN(str);
393    float base_y = 0, prev_x;
394    int i=0, k;
395 
396    r.x0 = r.x1 = 0;
397    r.ymin = r.ymax = 0;
398    r.num_chars = 0;
399 
400    // search rows to find one that straddles 'y'
401    while (i < n) {
402       STB_TEXTEDIT_LAYOUTROW(&r, str, i);
403       if (r.num_chars <= 0)
404          return n;
405 
406       if (i==0 && y < base_y + r.ymin)
407          return 0;
408 
409       if (y < base_y + r.ymax)
410          break;
411 
412       i += r.num_chars;
413       base_y += r.baseline_y_delta;
414    }
415 
416    // below all text, return 'after' last character
417    if (i >= n)
418       return n;
419 
420    // check if it's before the beginning of the line
421    if (x < r.x0)
422       return i;
423 
424    // check if it's before the end of the line
425    if (x < r.x1) {
426       // search characters in row for one that straddles 'x'
427       prev_x = r.x0;
428       for (k=0; k < r.num_chars; ++k) {
429          float w = STB_TEXTEDIT_GETWIDTH(str, i, k);
430          if (x < prev_x+w) {
431             if (x < prev_x+w/2)
432                return k+i;
433             else
434                return k+i+1;
435          }
436          prev_x += w;
437       }
438       // shouldn't happen, but if it does, fall through to end-of-line case
439    }
440 
441    // if the last character is a newline, return that. otherwise return 'after' the last character
442    if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE)
443       return i+r.num_chars-1;
444    else
445       return i+r.num_chars;
446 }
447 
448 // API click: on mouse down, move the cursor to the clicked location, and reset the selection
stb_textedit_click(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,float x,float y)449 static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
450 {
451    // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse
452    // goes off the top or bottom of the text
453    if( state->single_line )
454    {
455       StbTexteditRow r;
456       STB_TEXTEDIT_LAYOUTROW(&r, str, 0);
457       y = r.ymin;
458    }
459 
460    state->cursor = stb_text_locate_coord(str, x, y);
461    state->select_start = state->cursor;
462    state->select_end = state->cursor;
463    state->has_preferred_x = 0;
464 }
465 
466 // API drag: on mouse drag, move the cursor and selection endpoint to the clicked location
stb_textedit_drag(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,float x,float y)467 static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
468 {
469    int p = 0;
470 
471    // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse
472    // goes off the top or bottom of the text
473    if( state->single_line )
474    {
475       StbTexteditRow r;
476       STB_TEXTEDIT_LAYOUTROW(&r, str, 0);
477       y = r.ymin;
478    }
479 
480    if (state->select_start == state->select_end)
481       state->select_start = state->cursor;
482 
483    p = stb_text_locate_coord(str, x, y);
484    state->cursor = state->select_end = p;
485 }
486 
487 /////////////////////////////////////////////////////////////////////////////
488 //
489 //      Keyboard input handling
490 //
491 
492 // forward declarations
493 static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state);
494 static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state);
495 static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length);
496 static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length);
497 static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length);
498 
499 typedef struct
500 {
501    float x,y;    // position of n'th character
502    float height; // height of line
503    int first_char, length; // first char of row, and length
504    int prev_first;  // first char of previous row
505 } StbFindState;
506 
507 // find the x/y location of a character, and remember info about the previous row in
508 // case we get a move-up event (for page up, we'll have to rescan)
stb_textedit_find_charpos(StbFindState * find,STB_TEXTEDIT_STRING * str,int n,int single_line)509 static void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *str, int n, int single_line)
510 {
511    StbTexteditRow r;
512    int prev_start = 0;
513    int z = STB_TEXTEDIT_STRINGLEN(str);
514    int i=0, first;
515 
516    if (n == z) {
517       // if it's at the end, then find the last line -- simpler than trying to
518       // explicitly handle this case in the regular code
519       if (single_line) {
520          STB_TEXTEDIT_LAYOUTROW(&r, str, 0);
521          find->y = 0;
522          find->first_char = 0;
523          find->length = z;
524          find->height = r.ymax - r.ymin;
525          find->x = r.x1;
526       } else {
527          find->y = 0;
528          find->x = 0;
529          find->height = 1;
530          while (i < z) {
531             STB_TEXTEDIT_LAYOUTROW(&r, str, i);
532             prev_start = i;
533             i += r.num_chars;
534          }
535          find->first_char = i;
536          find->length = 0;
537          find->prev_first = prev_start;
538       }
539       return;
540    }
541 
542    // search rows to find the one that straddles character n
543    find->y = 0;
544 
545    for(;;) {
546       STB_TEXTEDIT_LAYOUTROW(&r, str, i);
547       if (n < i + r.num_chars)
548          break;
549       prev_start = i;
550       i += r.num_chars;
551       find->y += r.baseline_y_delta;
552    }
553 
554    find->first_char = first = i;
555    find->length = r.num_chars;
556    find->height = r.ymax - r.ymin;
557    find->prev_first = prev_start;
558 
559    // now scan to find xpos
560    find->x = r.x0;
561    i = 0;
562    for (i=0; first+i < n; ++i)
563       find->x += STB_TEXTEDIT_GETWIDTH(str, first, i);
564 }
565 
566 #define STB_TEXT_HAS_SELECTION(s)   ((s)->select_start != (s)->select_end)
567 
568 // make the selection/cursor state valid if client altered the string
stb_textedit_clamp(STB_TEXTEDIT_STRING * str,STB_TexteditState * state)569 static void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
570 {
571    int n = STB_TEXTEDIT_STRINGLEN(str);
572    if (STB_TEXT_HAS_SELECTION(state)) {
573       if (state->select_start > n) state->select_start = n;
574       if (state->select_end   > n) state->select_end = n;
575       // if clamping forced them to be equal, move the cursor to match
576       if (state->select_start == state->select_end)
577          state->cursor = state->select_start;
578    }
579    if (state->cursor > n) state->cursor = n;
580 }
581 
582 // delete characters while updating undo
stb_textedit_delete(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,int where,int len)583 static void stb_textedit_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len)
584 {
585    stb_text_makeundo_delete(str, state, where, len);
586    STB_TEXTEDIT_DELETECHARS(str, where, len);
587    state->has_preferred_x = 0;
588 }
589 
590 // delete the section
stb_textedit_delete_selection(STB_TEXTEDIT_STRING * str,STB_TexteditState * state)591 static void stb_textedit_delete_selection(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
592 {
593    stb_textedit_clamp(str, state);
594    if (STB_TEXT_HAS_SELECTION(state)) {
595       if (state->select_start < state->select_end) {
596          stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start);
597          state->select_end = state->cursor = state->select_start;
598       } else {
599          stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end);
600          state->select_start = state->cursor = state->select_end;
601       }
602       state->has_preferred_x = 0;
603    }
604 }
605 
606 // canoncialize the selection so start <= end
stb_textedit_sortselection(STB_TexteditState * state)607 static void stb_textedit_sortselection(STB_TexteditState *state)
608 {
609    if (state->select_end < state->select_start) {
610       int temp = state->select_end;
611       state->select_end = state->select_start;
612       state->select_start = temp;
613    }
614 }
615 
616 // move cursor to first character of selection
stb_textedit_move_to_first(STB_TexteditState * state)617 static void stb_textedit_move_to_first(STB_TexteditState *state)
618 {
619    if (STB_TEXT_HAS_SELECTION(state)) {
620       stb_textedit_sortselection(state);
621       state->cursor = state->select_start;
622       state->select_end = state->select_start;
623       state->has_preferred_x = 0;
624    }
625 }
626 
627 // move cursor to last character of selection
stb_textedit_move_to_last(STB_TEXTEDIT_STRING * str,STB_TexteditState * state)628 static void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
629 {
630    if (STB_TEXT_HAS_SELECTION(state)) {
631       stb_textedit_sortselection(state);
632       stb_textedit_clamp(str, state);
633       state->cursor = state->select_end;
634       state->select_start = state->select_end;
635       state->has_preferred_x = 0;
636    }
637 }
638 
639 #ifdef STB_TEXTEDIT_IS_SPACE
is_word_boundary(STB_TEXTEDIT_STRING * str,int idx)640 static int is_word_boundary( STB_TEXTEDIT_STRING *str, int idx )
641 {
642    return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1;
643 }
644 
645 #ifndef STB_TEXTEDIT_MOVEWORDLEFT
stb_textedit_move_to_word_previous(STB_TEXTEDIT_STRING * str,int c)646 static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *str, int c )
647 {
648    --c; // always move at least one character
649    while( c >= 0 && !is_word_boundary( str, c ) )
650       --c;
651 
652    if( c < 0 )
653       c = 0;
654 
655    return c;
656 }
657 #define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous
658 #endif
659 
660 #ifndef STB_TEXTEDIT_MOVEWORDRIGHT
stb_textedit_move_to_word_next(STB_TEXTEDIT_STRING * str,int c)661 static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *str, int c )
662 {
663    const int len = STB_TEXTEDIT_STRINGLEN(str);
664    ++c; // always move at least one character
665    while( c < len && !is_word_boundary( str, c ) )
666       ++c;
667 
668    if( c > len )
669       c = len;
670 
671    return c;
672 }
673 #define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next
674 #endif
675 
676 #endif
677 
678 // update selection and cursor to match each other
stb_textedit_prep_selection_at_cursor(STB_TexteditState * state)679 static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state)
680 {
681    if (!STB_TEXT_HAS_SELECTION(state))
682       state->select_start = state->select_end = state->cursor;
683    else
684       state->cursor = state->select_end;
685 }
686 
687 // API cut: delete selection
stb_textedit_cut(STB_TEXTEDIT_STRING * str,STB_TexteditState * state)688 static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
689 {
690    if (STB_TEXT_HAS_SELECTION(state)) {
691       stb_textedit_delete_selection(str,state); // implicity clamps
692       state->has_preferred_x = 0;
693       return 1;
694    }
695    return 0;
696 }
697 
698 // API paste: replace existing selection with passed-in text
stb_textedit_paste_internal(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,STB_TEXTEDIT_CHARTYPE * text,int len)699 static int stb_textedit_paste_internal(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len)
700 {
701    // if there's a selection, the paste should delete it
702    stb_textedit_clamp(str, state);
703    stb_textedit_delete_selection(str,state);
704    // try to insert the characters
705    if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) {
706       stb_text_makeundo_insert(state, state->cursor, len);
707       state->cursor += len;
708       state->has_preferred_x = 0;
709       return 1;
710    }
711    // remove the undo since we didn't actually insert the characters
712    if (state->undostate.undo_point)
713       --state->undostate.undo_point;
714    return 0;
715 }
716 
717 #ifndef STB_TEXTEDIT_KEYTYPE
718 #define STB_TEXTEDIT_KEYTYPE int
719 #endif
720 
721 // API key: process a keyboard input
stb_textedit_key(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,STB_TEXTEDIT_KEYTYPE key)722 static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key)
723 {
724 retry:
725    switch (key) {
726       default: {
727          int c = STB_TEXTEDIT_KEYTOTEXT(key);
728          if (c > 0) {
729             STB_TEXTEDIT_CHARTYPE ch = (STB_TEXTEDIT_CHARTYPE) c;
730 
731             // can't add newline in single-line mode
732             if (c == '\n' && state->single_line)
733                break;
734 
735             if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) {
736                stb_text_makeundo_replace(str, state, state->cursor, 1, 1);
737                STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1);
738                if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) {
739                   ++state->cursor;
740                   state->has_preferred_x = 0;
741                }
742             } else {
743                stb_textedit_delete_selection(str,state); // implicity clamps
744                if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) {
745                   stb_text_makeundo_insert(state, state->cursor, 1);
746                   ++state->cursor;
747                   state->has_preferred_x = 0;
748                }
749             }
750          }
751          break;
752       }
753 
754 #ifdef STB_TEXTEDIT_K_INSERT
755       case STB_TEXTEDIT_K_INSERT:
756          state->insert_mode = !state->insert_mode;
757          break;
758 #endif
759 
760       case STB_TEXTEDIT_K_UNDO:
761          stb_text_undo(str, state);
762          state->has_preferred_x = 0;
763          break;
764 
765       case STB_TEXTEDIT_K_REDO:
766          stb_text_redo(str, state);
767          state->has_preferred_x = 0;
768          break;
769 
770       case STB_TEXTEDIT_K_LEFT:
771          // if currently there's a selection, move cursor to start of selection
772          if (STB_TEXT_HAS_SELECTION(state))
773             stb_textedit_move_to_first(state);
774          else
775             if (state->cursor > 0)
776                --state->cursor;
777          state->has_preferred_x = 0;
778          break;
779 
780       case STB_TEXTEDIT_K_RIGHT:
781          // if currently there's a selection, move cursor to end of selection
782          if (STB_TEXT_HAS_SELECTION(state))
783             stb_textedit_move_to_last(str, state);
784          else
785             ++state->cursor;
786          stb_textedit_clamp(str, state);
787          state->has_preferred_x = 0;
788          break;
789 
790       case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT:
791          stb_textedit_clamp(str, state);
792          stb_textedit_prep_selection_at_cursor(state);
793          // move selection left
794          if (state->select_end > 0)
795             --state->select_end;
796          state->cursor = state->select_end;
797          state->has_preferred_x = 0;
798          break;
799 
800 #ifdef STB_TEXTEDIT_MOVEWORDLEFT
801       case STB_TEXTEDIT_K_WORDLEFT:
802          if (STB_TEXT_HAS_SELECTION(state))
803             stb_textedit_move_to_first(state);
804          else {
805             state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor);
806             stb_textedit_clamp( str, state );
807          }
808          break;
809 
810       case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT:
811          if( !STB_TEXT_HAS_SELECTION( state ) )
812             stb_textedit_prep_selection_at_cursor(state);
813 
814          state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor);
815          state->select_end = state->cursor;
816 
817          stb_textedit_clamp( str, state );
818          break;
819 #endif
820 
821 #ifdef STB_TEXTEDIT_MOVEWORDRIGHT
822       case STB_TEXTEDIT_K_WORDRIGHT:
823          if (STB_TEXT_HAS_SELECTION(state))
824             stb_textedit_move_to_last(str, state);
825          else {
826             state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor);
827             stb_textedit_clamp( str, state );
828          }
829          break;
830 
831       case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT:
832          if( !STB_TEXT_HAS_SELECTION( state ) )
833             stb_textedit_prep_selection_at_cursor(state);
834 
835          state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor);
836          state->select_end = state->cursor;
837 
838          stb_textedit_clamp( str, state );
839          break;
840 #endif
841 
842       case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT:
843          stb_textedit_prep_selection_at_cursor(state);
844          // move selection right
845          ++state->select_end;
846          stb_textedit_clamp(str, state);
847          state->cursor = state->select_end;
848          state->has_preferred_x = 0;
849          break;
850 
851       case STB_TEXTEDIT_K_DOWN:
852       case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: {
853          StbFindState find;
854          StbTexteditRow row;
855          int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;
856 
857          if (state->single_line) {
858             // on windows, up&down in single-line behave like left&right
859             key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT);
860             goto retry;
861          }
862 
863          if (sel)
864             stb_textedit_prep_selection_at_cursor(state);
865          else if (STB_TEXT_HAS_SELECTION(state))
866             stb_textedit_move_to_last(str,state);
867 
868          // compute current position of cursor point
869          stb_textedit_clamp(str, state);
870          stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);
871 
872          // now find character position down a row
873          if (find.length) {
874             float goal_x = state->has_preferred_x ? state->preferred_x : find.x;
875             float x;
876             int start = find.first_char + find.length;
877             state->cursor = start;
878             STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);
879             x = row.x0;
880             for (i=0; i < row.num_chars; ++i) {
881                float dx = STB_TEXTEDIT_GETWIDTH(str, start, i);
882                #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE
883                if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE)
884                   break;
885                #endif
886                x += dx;
887                if (x > goal_x)
888                   break;
889                ++state->cursor;
890             }
891             stb_textedit_clamp(str, state);
892 
893             state->has_preferred_x = 1;
894             state->preferred_x = goal_x;
895 
896             if (sel)
897                state->select_end = state->cursor;
898          }
899          break;
900       }
901 
902       case STB_TEXTEDIT_K_UP:
903       case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: {
904          StbFindState find;
905          StbTexteditRow row;
906          int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;
907 
908          if (state->single_line) {
909             // on windows, up&down become left&right
910             key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT);
911             goto retry;
912          }
913 
914          if (sel)
915             stb_textedit_prep_selection_at_cursor(state);
916          else if (STB_TEXT_HAS_SELECTION(state))
917             stb_textedit_move_to_first(state);
918 
919          // compute current position of cursor point
920          stb_textedit_clamp(str, state);
921          stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);
922 
923          // can only go up if there's a previous row
924          if (find.prev_first != find.first_char) {
925             // now find character position up a row
926             float goal_x = state->has_preferred_x ? state->preferred_x : find.x;
927             float x;
928             state->cursor = find.prev_first;
929             STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);
930             x = row.x0;
931             for (i=0; i < row.num_chars; ++i) {
932                float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i);
933                #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE
934                if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE)
935                   break;
936                #endif
937                x += dx;
938                if (x > goal_x)
939                   break;
940                ++state->cursor;
941             }
942             stb_textedit_clamp(str, state);
943 
944             state->has_preferred_x = 1;
945             state->preferred_x = goal_x;
946 
947             if (sel)
948                state->select_end = state->cursor;
949          }
950          break;
951       }
952 
953       case STB_TEXTEDIT_K_DELETE:
954       case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT:
955          if (STB_TEXT_HAS_SELECTION(state))
956             stb_textedit_delete_selection(str, state);
957          else {
958             int n = STB_TEXTEDIT_STRINGLEN(str);
959             if (state->cursor < n)
960                stb_textedit_delete(str, state, state->cursor, 1);
961          }
962          state->has_preferred_x = 0;
963          break;
964 
965       case STB_TEXTEDIT_K_BACKSPACE:
966       case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT:
967          if (STB_TEXT_HAS_SELECTION(state))
968             stb_textedit_delete_selection(str, state);
969          else {
970             stb_textedit_clamp(str, state);
971             if (state->cursor > 0) {
972                stb_textedit_delete(str, state, state->cursor-1, 1);
973                --state->cursor;
974             }
975          }
976          state->has_preferred_x = 0;
977          break;
978 
979 #ifdef STB_TEXTEDIT_K_TEXTSTART2
980       case STB_TEXTEDIT_K_TEXTSTART2:
981 #endif
982       case STB_TEXTEDIT_K_TEXTSTART:
983          state->cursor = state->select_start = state->select_end = 0;
984          state->has_preferred_x = 0;
985          break;
986 
987 #ifdef STB_TEXTEDIT_K_TEXTEND2
988       case STB_TEXTEDIT_K_TEXTEND2:
989 #endif
990       case STB_TEXTEDIT_K_TEXTEND:
991          state->cursor = STB_TEXTEDIT_STRINGLEN(str);
992          state->select_start = state->select_end = 0;
993          state->has_preferred_x = 0;
994          break;
995 
996 #ifdef STB_TEXTEDIT_K_TEXTSTART2
997       case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT:
998 #endif
999       case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT:
1000          stb_textedit_prep_selection_at_cursor(state);
1001          state->cursor = state->select_end = 0;
1002          state->has_preferred_x = 0;
1003          break;
1004 
1005 #ifdef STB_TEXTEDIT_K_TEXTEND2
1006       case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT:
1007 #endif
1008       case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT:
1009          stb_textedit_prep_selection_at_cursor(state);
1010          state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str);
1011          state->has_preferred_x = 0;
1012          break;
1013 
1014 
1015 #ifdef STB_TEXTEDIT_K_LINESTART2
1016       case STB_TEXTEDIT_K_LINESTART2:
1017 #endif
1018       case STB_TEXTEDIT_K_LINESTART:
1019          stb_textedit_clamp(str, state);
1020          stb_textedit_move_to_first(state);
1021          if (state->single_line)
1022             state->cursor = 0;
1023          else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE)
1024             --state->cursor;
1025          state->has_preferred_x = 0;
1026          break;
1027 
1028 #ifdef STB_TEXTEDIT_K_LINEEND2
1029       case STB_TEXTEDIT_K_LINEEND2:
1030 #endif
1031       case STB_TEXTEDIT_K_LINEEND: {
1032          int n = STB_TEXTEDIT_STRINGLEN(str);
1033          stb_textedit_clamp(str, state);
1034          stb_textedit_move_to_first(state);
1035          if (state->single_line)
1036              state->cursor = n;
1037          else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE)
1038              ++state->cursor;
1039          state->has_preferred_x = 0;
1040          break;
1041       }
1042 
1043 #ifdef STB_TEXTEDIT_K_LINESTART2
1044       case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT:
1045 #endif
1046       case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT:
1047          stb_textedit_clamp(str, state);
1048          stb_textedit_prep_selection_at_cursor(state);
1049          if (state->single_line)
1050             state->cursor = 0;
1051          else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE)
1052             --state->cursor;
1053          state->select_end = state->cursor;
1054          state->has_preferred_x = 0;
1055          break;
1056 
1057 #ifdef STB_TEXTEDIT_K_LINEEND2
1058       case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT:
1059 #endif
1060       case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: {
1061          int n = STB_TEXTEDIT_STRINGLEN(str);
1062          stb_textedit_clamp(str, state);
1063          stb_textedit_prep_selection_at_cursor(state);
1064          if (state->single_line)
1065              state->cursor = n;
1066          else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE)
1067             ++state->cursor;
1068          state->select_end = state->cursor;
1069          state->has_preferred_x = 0;
1070          break;
1071       }
1072 
1073 // @TODO:
1074 //    STB_TEXTEDIT_K_PGUP      - move cursor up a page
1075 //    STB_TEXTEDIT_K_PGDOWN    - move cursor down a page
1076    }
1077 }
1078 
1079 /////////////////////////////////////////////////////////////////////////////
1080 //
1081 //      Undo processing
1082 //
1083 // @OPTIMIZE: the undo/redo buffer should be circular
1084 
stb_textedit_flush_redo(StbUndoState * state)1085 static void stb_textedit_flush_redo(StbUndoState *state)
1086 {
1087    state->redo_point = STB_TEXTEDIT_UNDOSTATECOUNT;
1088    state->redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT;
1089 }
1090 
1091 // discard the oldest entry in the undo list
stb_textedit_discard_undo(StbUndoState * state)1092 static void stb_textedit_discard_undo(StbUndoState *state)
1093 {
1094    if (state->undo_point > 0) {
1095       // if the 0th undo state has characters, clean those up
1096       if (state->undo_rec[0].char_storage >= 0) {
1097          int n = state->undo_rec[0].insert_length, i;
1098          // delete n characters from all other records
1099          state->undo_char_point = state->undo_char_point - (short) n;  // vsnet05
1100          STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) (state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE)));
1101          for (i=0; i < state->undo_point; ++i)
1102             if (state->undo_rec[i].char_storage >= 0)
1103                state->undo_rec[i].char_storage = state->undo_rec[i].char_storage - (short) n; // vsnet05 // @OPTIMIZE: get rid of char_storage and infer it
1104       }
1105       --state->undo_point;
1106       STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) (state->undo_point*sizeof(state->undo_rec[0])));
1107    }
1108 }
1109 
1110 // discard the oldest entry in the redo list--it's bad if this
1111 // ever happens, but because undo & redo have to store the actual
1112 // characters in different cases, the redo character buffer can
1113 // fill up even though the undo buffer didn't
stb_textedit_discard_redo(StbUndoState * state)1114 static void stb_textedit_discard_redo(StbUndoState *state)
1115 {
1116    int k = STB_TEXTEDIT_UNDOSTATECOUNT-1;
1117 
1118    if (state->redo_point <= k) {
1119       // if the k'th undo state has characters, clean those up
1120       if (state->undo_rec[k].char_storage >= 0) {
1121          int n = state->undo_rec[k].insert_length, i;
1122          // move the remaining redo character data to the end of the buffer
1123          state->redo_char_point = state->redo_char_point + (short) n; // vsnet05
1124          STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((STB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE)));
1125          // adjust the position of all the other records to account for above memmove
1126          for (i=state->redo_point; i < k; ++i)
1127             if (state->undo_rec[i].char_storage >= 0)
1128                state->undo_rec[i].char_storage += (short) n; // vsnet05
1129       }
1130       // now move all the redo records towards the end of the buffer; the first one is at 'redo_point'
1131       STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, (size_t) ((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0])));
1132       // now move redo_point to point to the new one
1133       ++state->redo_point;
1134    }
1135 }
1136 
stb_text_create_undo_record(StbUndoState * state,int numchars)1137 static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars)
1138 {
1139    // any time we create a new undo record, we discard redo
1140    stb_textedit_flush_redo(state);
1141 
1142    // if we have no free records, we have to make room, by sliding the
1143    // existing records down
1144    if (state->undo_point == STB_TEXTEDIT_UNDOSTATECOUNT)
1145       stb_textedit_discard_undo(state);
1146 
1147    // if the characters to store won't possibly fit in the buffer, we can't undo
1148    if (numchars > STB_TEXTEDIT_UNDOCHARCOUNT) {
1149       state->undo_point = 0;
1150       state->undo_char_point = 0;
1151       return NULL;
1152    }
1153 
1154    // if we don't have enough free characters in the buffer, we have to make room
1155    while (state->undo_char_point + numchars > STB_TEXTEDIT_UNDOCHARCOUNT)
1156       stb_textedit_discard_undo(state);
1157 
1158    return &state->undo_rec[state->undo_point++];
1159 }
1160 
stb_text_createundo(StbUndoState * state,int pos,int insert_len,int delete_len)1161 static STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len)
1162 {
1163    StbUndoRecord *r = stb_text_create_undo_record(state, insert_len);
1164    if (r == NULL)
1165       return NULL;
1166 
1167    r->where = pos;
1168    r->insert_length = (short) insert_len;
1169    r->delete_length = (short) delete_len;
1170 
1171    if (insert_len == 0) {
1172       r->char_storage = -1;
1173       return NULL;
1174    } else {
1175       r->char_storage = state->undo_char_point;
1176       state->undo_char_point = state->undo_char_point + (short) insert_len;
1177       return &state->undo_char[r->char_storage];
1178    }
1179 }
1180 
stb_text_undo(STB_TEXTEDIT_STRING * str,STB_TexteditState * state)1181 static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
1182 {
1183    StbUndoState *s = &state->undostate;
1184    StbUndoRecord u, *r;
1185    if (s->undo_point == 0)
1186       return;
1187 
1188    // we need to do two things: apply the undo record, and create a redo record
1189    u = s->undo_rec[s->undo_point-1];
1190    r = &s->undo_rec[s->redo_point-1];
1191    r->char_storage = -1;
1192 
1193    r->insert_length = u.delete_length;
1194    r->delete_length = u.insert_length;
1195    r->where = u.where;
1196 
1197    if (u.delete_length) {
1198       // if the undo record says to delete characters, then the redo record will
1199       // need to re-insert the characters that get deleted, so we need to store
1200       // them.
1201 
1202       // there are three cases:
1203       //    there's enough room to store the characters
1204       //    characters stored for *redoing* don't leave room for redo
1205       //    characters stored for *undoing* don't leave room for redo
1206       // if the last is true, we have to bail
1207 
1208       if (s->undo_char_point + u.delete_length >= STB_TEXTEDIT_UNDOCHARCOUNT) {
1209          // the undo records take up too much character space; there's no space to store the redo characters
1210          r->insert_length = 0;
1211       } else {
1212          int i;
1213 
1214          // there's definitely room to store the characters eventually
1215          while (s->undo_char_point + u.delete_length > s->redo_char_point) {
1216             // should never happen:
1217             if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT)
1218                return;
1219             // there's currently not enough room, so discard a redo record
1220             stb_textedit_discard_redo(s);
1221          }
1222          r = &s->undo_rec[s->redo_point-1];
1223 
1224          r->char_storage = s->redo_char_point - u.delete_length;
1225          s->redo_char_point = s->redo_char_point - (short) u.delete_length;
1226 
1227          // now save the characters
1228          for (i=0; i < u.delete_length; ++i)
1229             s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i);
1230       }
1231 
1232       // now we can carry out the deletion
1233       STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length);
1234    }
1235 
1236    // check type of recorded action:
1237    if (u.insert_length) {
1238       // easy case: was a deletion, so we need to insert n characters
1239       STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length);
1240       s->undo_char_point -= u.insert_length;
1241    }
1242 
1243    state->cursor = u.where + u.insert_length;
1244 
1245    s->undo_point--;
1246    s->redo_point--;
1247 }
1248 
stb_text_redo(STB_TEXTEDIT_STRING * str,STB_TexteditState * state)1249 static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
1250 {
1251    StbUndoState *s = &state->undostate;
1252    StbUndoRecord *u, r;
1253    if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT)
1254       return;
1255 
1256    // we need to do two things: apply the redo record, and create an undo record
1257    u = &s->undo_rec[s->undo_point];
1258    r = s->undo_rec[s->redo_point];
1259 
1260    // we KNOW there must be room for the undo record, because the redo record
1261    // was derived from an undo record
1262 
1263    u->delete_length = r.insert_length;
1264    u->insert_length = r.delete_length;
1265    u->where = r.where;
1266    u->char_storage = -1;
1267 
1268    if (r.delete_length) {
1269       // the redo record requires us to delete characters, so the undo record
1270       // needs to store the characters
1271 
1272       if (s->undo_char_point + u->insert_length > s->redo_char_point) {
1273          u->insert_length = 0;
1274          u->delete_length = 0;
1275       } else {
1276          int i;
1277          u->char_storage = s->undo_char_point;
1278          s->undo_char_point = s->undo_char_point + u->insert_length;
1279 
1280          // now save the characters
1281          for (i=0; i < u->insert_length; ++i)
1282             s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i);
1283       }
1284 
1285       STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length);
1286    }
1287 
1288    if (r.insert_length) {
1289       // easy case: need to insert n characters
1290       STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length);
1291       s->redo_char_point += r.insert_length;
1292    }
1293 
1294    state->cursor = r.where + r.insert_length;
1295 
1296    s->undo_point++;
1297    s->redo_point++;
1298 }
1299 
stb_text_makeundo_insert(STB_TexteditState * state,int where,int length)1300 static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length)
1301 {
1302    stb_text_createundo(&state->undostate, where, 0, length);
1303 }
1304 
stb_text_makeundo_delete(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,int where,int length)1305 static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length)
1306 {
1307    int i;
1308    STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0);
1309    if (p) {
1310       for (i=0; i < length; ++i)
1311          p[i] = STB_TEXTEDIT_GETCHAR(str, where+i);
1312    }
1313 }
1314 
stb_text_makeundo_replace(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,int where,int old_length,int new_length)1315 static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length)
1316 {
1317    int i;
1318    STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length);
1319    if (p) {
1320       for (i=0; i < old_length; ++i)
1321          p[i] = STB_TEXTEDIT_GETCHAR(str, where+i);
1322    }
1323 }
1324 
1325 // reset the state to default
stb_textedit_clear_state(STB_TexteditState * state,int is_single_line)1326 static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line)
1327 {
1328    state->undostate.undo_point = 0;
1329    state->undostate.undo_char_point = 0;
1330    state->undostate.redo_point = STB_TEXTEDIT_UNDOSTATECOUNT;
1331    state->undostate.redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT;
1332    state->select_end = state->select_start = 0;
1333    state->cursor = 0;
1334    state->has_preferred_x = 0;
1335    state->preferred_x = 0;
1336    state->cursor_at_end_of_line = 0;
1337    state->initialized = 1;
1338    state->single_line = (unsigned char) is_single_line;
1339    state->insert_mode = 0;
1340 }
1341 
1342 // API initialize
stb_textedit_initialize_state(STB_TexteditState * state,int is_single_line)1343 static void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line)
1344 {
1345    stb_textedit_clear_state(state, is_single_line);
1346 }
1347 
1348 #if defined(__GNUC__) || defined(__clang__)
1349 #pragma GCC diagnostic push
1350 #pragma GCC diagnostic ignored "-Wcast-qual"
1351 #endif
1352 
stb_textedit_paste(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,STB_TEXTEDIT_CHARTYPE const * ctext,int len)1353 static int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len)
1354 {
1355    return stb_textedit_paste_internal(str, state, (STB_TEXTEDIT_CHARTYPE *) ctext, len);
1356 }
1357 
1358 #if defined(__GNUC__) || defined(__clang__)
1359 #pragma GCC diagnostic pop
1360 #endif
1361 
1362 #endif//STB_TEXTEDIT_IMPLEMENTATION
1363 
1364 /*
1365 ------------------------------------------------------------------------------
1366 This software is available under 2 licenses -- choose whichever you prefer.
1367 ------------------------------------------------------------------------------
1368 ALTERNATIVE A - MIT License
1369 Copyright (c) 2017 Sean Barrett
1370 Permission is hereby granted, free of charge, to any person obtaining a copy of
1371 this software and associated documentation files (the "Software"), to deal in
1372 the Software without restriction, including without limitation the rights to
1373 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
1374 of the Software, and to permit persons to whom the Software is furnished to do
1375 so, subject to the following conditions:
1376 The above copyright notice and this permission notice shall be included in all
1377 copies or substantial portions of the Software.
1378 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1379 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1380 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1381 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1382 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1383 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1384 SOFTWARE.
1385 ------------------------------------------------------------------------------
1386 ALTERNATIVE B - Public Domain (www.unlicense.org)
1387 This is free and unencumbered software released into the public domain.
1388 Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
1389 software, either in source code form or as a compiled binary, for any purpose,
1390 commercial or non-commercial, and by any means.
1391 In jurisdictions that recognize copyright laws, the author or authors of this
1392 software dedicate any and all copyright interest in the software to the public
1393 domain. We make this dedication for the benefit of the public at large and to
1394 the detriment of our heirs and successors. We intend this dedication to be an
1395 overt act of relinquishment in perpetuity of all present and future rights to
1396 this software under copyright law.
1397 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1398 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1399 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1400 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1401 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
1402 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1403 ------------------------------------------------------------------------------
1404 */
1405