1 // stb_textedit.h - v1.13  - 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.13 (2019-02-07) fix bug in undo size management
33 //   1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash
34 //   1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield
35 //   1.10 (2016-10-25) supress warnings about casting away const with -Wcast-qual
36 //   1.9  (2016-08-27) customizable move-by-word
37 //   1.8  (2016-04-02) better keyboard handling when mouse button is down
38 //   1.7  (2015-09-13) change y range handling in case baseline is non-0
39 //   1.6  (2015-04-15) allow STB_TEXTEDIT_memmove
40 //   1.5  (2014-09-10) add support for secondary keys for OS X
41 //   1.4  (2014-08-17) fix signed/unsigned warnings
42 //   1.3  (2014-06-19) fix mouse clicking to round to nearest char boundary
43 //   1.2  (2014-05-27) fix some RAD types that had crept into the new code
44 //   1.1  (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE )
45 //   1.0  (2012-07-26) improve documentation, initial public release
46 //   0.3  (2012-02-24) bugfixes, single-line mode; insert mode
47 //   0.2  (2011-11-28) fixes to undo/redo
48 //   0.1  (2010-07-08) initial version
49 //
50 // ADDITIONAL CONTRIBUTORS
51 //
52 //   Ulf Winklemann: move-by-word in 1.1
53 //   Fabian Giesen: secondary key inputs in 1.5
54 //   Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6
55 //
56 //   Bugfixes:
57 //      Scott Graham
58 //      Daniel Keller
59 //      Omar Cornut
60 //      Dan Thompson
61 //
62 // USAGE
63 //
64 // This file behaves differently depending on what symbols you define
65 // before including it.
66 //
67 //
68 // Header-file mode:
69 //
70 //   If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this,
71 //   it will operate in "header file" mode. In this mode, it declares a
72 //   single public symbol, STB_TexteditState, which encapsulates the current
73 //   state of a text widget (except for the string, which you will store
74 //   separately).
75 //
76 //   To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a
77 //   primitive type that defines a single character (e.g. char, wchar_t, etc).
78 //
79 //   To save space or increase undo-ability, you can optionally define the
80 //   following things that are used by the undo system:
81 //
82 //      STB_TEXTEDIT_POSITIONTYPE         small int type encoding a valid cursor position
83 //      STB_TEXTEDIT_UNDOSTATECOUNT       the number of undo states to allow
84 //      STB_TEXTEDIT_UNDOCHARCOUNT        the number of characters to store in the undo buffer
85 //
86 //   If you don't define these, they are set to permissive types and
87 //   moderate sizes. The undo system does no memory allocations, so
88 //   it grows STB_TexteditState by the worst-case storage which is (in bytes):
89 //
90 //        [4 + 3 * sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATE_COUNT
91 //      +          sizeof(STB_TEXTEDIT_CHARTYPE)      * STB_TEXTEDIT_UNDOCHAR_COUNT
92 //
93 //
94 // Implementation mode:
95 //
96 //   If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it
97 //   will compile the implementation of the text edit widget, depending
98 //   on a large number of symbols which must be defined before the include.
99 //
100 //   The implementation is defined only as static functions. You will then
101 //   need to provide your own APIs in the same file which will access the
102 //   static functions.
103 //
104 //   The basic concept is that you provide a "string" object which
105 //   behaves like an array of characters. stb_textedit uses indices to
106 //   refer to positions in the string, implicitly representing positions
107 //   in the displayed textedit. This is true for both plain text and
108 //   rich text; even with rich text stb_truetype interacts with your
109 //   code as if there was an array of all the displayed characters.
110 //
111 // Symbols that must be the same in header-file and implementation mode:
112 //
113 //     STB_TEXTEDIT_CHARTYPE             the character type
114 //     STB_TEXTEDIT_POSITIONTYPE         small type that is a valid cursor position
115 //     STB_TEXTEDIT_UNDOSTATECOUNT       the number of undo states to allow
116 //     STB_TEXTEDIT_UNDOCHARCOUNT        the number of characters to store in the undo buffer
117 //
118 // Symbols you must define for implementation mode:
119 //
120 //    STB_TEXTEDIT_STRING               the type of object representing a string being edited,
121 //                                      typically this is a wrapper object with other data you need
122 //
123 //    STB_TEXTEDIT_STRINGLEN(obj)       the length of the string (ideally O(1))
124 //    STB_TEXTEDIT_LAYOUTROW(&r,obj,n)  returns the results of laying out a line of characters
125 //                                        starting from character #n (see discussion below)
126 //    STB_TEXTEDIT_GETWIDTH(obj,n,i)    returns the pixel delta from the xpos of the i'th character
127 //                                        to the xpos of the i+1'th char for a line of characters
128 //                                        starting at character #n (i.e. accounts for kerning
129 //                                        with previous char)
130 //    STB_TEXTEDIT_KEYTOTEXT(k)         maps a keyboard input to an insertable character
131 //                                        (return type is int, -1 means not valid to insert)
132 //    STB_TEXTEDIT_GETCHAR(obj,i)       returns the i'th character of obj, 0-based
133 //    STB_TEXTEDIT_NEWLINE              the character returned by _GETCHAR() we recognize
134 //                                        as manually wordwrapping for end-of-line positioning
135 //
136 //    STB_TEXTEDIT_DELETECHARS(obj,i,n)      delete n characters starting at i
137 //    STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n)   insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*)
138 //
139 //    STB_TEXTEDIT_K_SHIFT       a power of two that is or'd in to a keyboard input to represent the shift key
140 //
141 //    STB_TEXTEDIT_K_LEFT        keyboard input to move cursor left
142 //    STB_TEXTEDIT_K_RIGHT       keyboard input to move cursor right
143 //    STB_TEXTEDIT_K_UP          keyboard input to move cursor up
144 //    STB_TEXTEDIT_K_DOWN        keyboard input to move cursor down
145 //    STB_TEXTEDIT_K_LINESTART   keyboard input to move cursor to start of line  // e.g. HOME
146 //    STB_TEXTEDIT_K_LINEEND     keyboard input to move cursor to end of line    // e.g. END
147 //    STB_TEXTEDIT_K_TEXTSTART   keyboard input to move cursor to start of text  // e.g. ctrl-HOME
148 //    STB_TEXTEDIT_K_TEXTEND     keyboard input to move cursor to end of text    // e.g. ctrl-END
149 //    STB_TEXTEDIT_K_DELETE      keyboard input to delete selection or character under cursor
150 //    STB_TEXTEDIT_K_BACKSPACE   keyboard input to delete selection or character left of cursor
151 //    STB_TEXTEDIT_K_UNDO        keyboard input to perform undo
152 //    STB_TEXTEDIT_K_REDO        keyboard input to perform redo
153 //
154 // Optional:
155 //    STB_TEXTEDIT_K_INSERT              keyboard input to toggle insert mode
156 //    STB_TEXTEDIT_IS_SPACE(ch)          true if character is whitespace (e.g. 'isspace'),
157 //                                          required for default WORDLEFT/WORDRIGHT handlers
158 //    STB_TEXTEDIT_MOVEWORDLEFT(obj,i)   custom handler for WORDLEFT, returns index to move cursor to
159 //    STB_TEXTEDIT_MOVEWORDRIGHT(obj,i)  custom handler for WORDRIGHT, returns index to move cursor to
160 //    STB_TEXTEDIT_K_WORDLEFT            keyboard input to move cursor left one word // e.g. ctrl-LEFT
161 //    STB_TEXTEDIT_K_WORDRIGHT           keyboard input to move cursor right one word // e.g. ctrl-RIGHT
162 //    STB_TEXTEDIT_K_LINESTART2          secondary keyboard input to move cursor to start of line
163 //    STB_TEXTEDIT_K_LINEEND2            secondary keyboard input to move cursor to end of line
164 //    STB_TEXTEDIT_K_TEXTSTART2          secondary keyboard input to move cursor to start of text
165 //    STB_TEXTEDIT_K_TEXTEND2            secondary keyboard input to move cursor to end of text
166 //
167 // Todo:
168 //    STB_TEXTEDIT_K_PGUP        keyboard input to move cursor up a page
169 //    STB_TEXTEDIT_K_PGDOWN      keyboard input to move cursor down a page
170 //
171 // Keyboard input must be encoded as a single integer value; e.g. a character code
172 // and some bitflags that represent shift states. to simplify the interface, SHIFT must
173 // be a bitflag, so we can test the shifted state of cursor movements to allow selection,
174 // i.e. (STB_TEXTED_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow.
175 //
176 // You can encode other things, such as CONTROL or ALT, in additional bits, and
177 // then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example,
178 // my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN
179 // bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit,
180 // and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in the
181 // API below. The control keys will only match WM_KEYDOWN events because of the
182 // keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN
183 // bit so it only decodes WM_CHAR events.
184 //
185 // STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed
186 // row of characters assuming they start on the i'th character--the width and
187 // the height and the number of characters consumed. This allows this library
188 // to traverse the entire layout incrementally. You need to compute word-wrapping
189 // here.
190 //
191 // Each textfield keeps its own insert mode state, which is not how normal
192 // applications work. To keep an app-wide insert mode, update/copy the
193 // "insert_mode" field of STB_TexteditState before/after calling API functions.
194 //
195 // API
196 //
197 //    void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line)
198 //
199 //    void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
200 //    void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
201 //    int  stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
202 //    int  stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len)
203 //    void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key)
204 //
205 //    Each of these functions potentially updates the string and updates the
206 //    state.
207 //
208 //      initialize_state:
209 //          set the textedit state to a known good default state when initially
210 //          constructing the textedit.
211 //
212 //      click:
213 //          call this with the mouse x,y on a mouse down; it will update the cursor
214 //          and reset the selection start/end to the cursor point. the x,y must
215 //          be relative to the text widget, with (0,0) being the top left.
216 //
217 //      drag:
218 //          call this with the mouse x,y on a mouse drag/up; it will update the
219 //          cursor and the selection end point
220 //
221 //      cut:
222 //          call this to delete the current selection; returns true if there was
223 //          one. you should FIRST copy the current selection to the system paste buffer.
224 //          (To copy, just copy the current selection out of the string yourself.)
225 //
226 //      paste:
227 //          call this to paste text at the current cursor point or over the current
228 //          selection if there is one.
229 //
230 //      key:
231 //          call this for keyboard inputs sent to the textfield. you can use it
232 //          for "key down" events or for "translated" key events. if you need to
233 //          do both (as in Win32), or distinguish Unicode characters from control
234 //          inputs, set a high bit to distinguish the two; then you can define the
235 //          various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit
236 //          set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is
237 //          clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to
238 //          anything other type you wante before including.
239 //
240 //
241 //   When rendering, you can read the cursor position and selection state from
242 //   the STB_TexteditState.
243 //
244 //
245 // Notes:
246 //
247 // This is designed to be usable in IMGUI, so it allows for the possibility of
248 // running in an IMGUI that has NOT cached the multi-line layout. For this
249 // reason, it provides an interface that is compatible with computing the
250 // layout incrementally--we try to make sure we make as few passes through
251 // as possible. (For example, to locate the mouse pointer in the text, we
252 // could define functions that return the X and Y positions of characters
253 // and binary search Y and then X, but if we're doing dynamic layout this
254 // will run the layout algorithm many times, so instead we manually search
255 // forward in one pass. Similar logic applies to e.g. up-arrow and
256 // down-arrow movement.)
257 //
258 // If it's run in a widget that *has* cached the layout, then this is less
259 // efficient, but it's not horrible on modern computers. But you wouldn't
260 // want to edit million-line files with it.
261 
262 
263 ////////////////////////////////////////////////////////////////////////////
264 ////////////////////////////////////////////////////////////////////////////
265 ////
266 ////   Header-file mode
267 ////
268 ////
269 
270 #ifndef INCLUDE_STB_TEXTEDIT_H
271 #define INCLUDE_STB_TEXTEDIT_H
272 
273 ////////////////////////////////////////////////////////////////////////
274 //
275 //     STB_TexteditState
276 //
277 // Definition of STB_TexteditState which you should store
278 // per-textfield; it includes cursor position, selection state,
279 // and undo state.
280 //
281 
282 #ifndef STB_TEXTEDIT_UNDOSTATECOUNT
283 #define STB_TEXTEDIT_UNDOSTATECOUNT   99
284 #endif
285 #ifndef STB_TEXTEDIT_UNDOCHARCOUNT
286 #define STB_TEXTEDIT_UNDOCHARCOUNT   999
287 #endif
288 #ifndef STB_TEXTEDIT_CHARTYPE
289 #define STB_TEXTEDIT_CHARTYPE        int
290 #endif
291 #ifndef STB_TEXTEDIT_POSITIONTYPE
292 #define STB_TEXTEDIT_POSITIONTYPE    int
293 #endif
294 
295 typedef struct
296 {
297    // private data
298    STB_TEXTEDIT_POSITIONTYPE  where;
299    STB_TEXTEDIT_POSITIONTYPE  insert_length;
300    STB_TEXTEDIT_POSITIONTYPE  delete_length;
301    int                        char_storage;
302 } StbUndoRecord;
303 
304 typedef struct
305 {
306    // private data
307    StbUndoRecord          undo_rec [STB_TEXTEDIT_UNDOSTATECOUNT];
308    STB_TEXTEDIT_CHARTYPE  undo_char[STB_TEXTEDIT_UNDOCHARCOUNT];
309    short undo_point, redo_point;
310    int undo_char_point, redo_char_point;
311 } StbUndoState;
312 
313 typedef struct
314 {
315    /////////////////////
316    //
317    // public data
318    //
319 
320    int cursor;
321    // position of the text cursor within the string
322 
323    int select_start;          // selection start point
324    int select_end;
325    // selection start and end point in characters; if equal, no selection.
326    // note that start may be less than or greater than end (e.g. when
327    // dragging the mouse, start is where the initial click was, and you
328    // can drag in either direction)
329 
330    unsigned char insert_mode;
331    // each textfield keeps its own insert mode state. to keep an app-wide
332    // insert mode, copy this value in/out of the app state
333 
334    /////////////////////
335    //
336    // private data
337    //
338    unsigned char cursor_at_end_of_line; // not implemented yet
339    unsigned char initialized;
340    unsigned char has_preferred_x;
341    unsigned char single_line;
342    unsigned char padding1, padding2, padding3;
343    float preferred_x; // this determines where the cursor up/down tries to seek to along x
344    StbUndoState undostate;
345 } STB_TexteditState;
346 
347 
348 ////////////////////////////////////////////////////////////////////////
349 //
350 //     StbTexteditRow
351 //
352 // Result of layout query, used by stb_textedit to determine where
353 // the text in each row is.
354 
355 // result of layout query
356 typedef struct
357 {
358    float x0,x1;             // starting x location, end x location (allows for align=right, etc)
359    float baseline_y_delta;  // position of baseline relative to previous row's baseline
360    float ymin,ymax;         // height of row above and below baseline
361    int num_chars;
362 } StbTexteditRow;
363 #endif //INCLUDE_STB_TEXTEDIT_H
364 
365 
366 ////////////////////////////////////////////////////////////////////////////
367 ////////////////////////////////////////////////////////////////////////////
368 ////
369 ////   Implementation mode
370 ////
371 ////
372 
373 
374 // implementation isn't include-guarded, since it might have indirectly
375 // included just the "header" portion
376 #ifdef STB_TEXTEDIT_IMPLEMENTATION
377 
378 #ifndef STB_TEXTEDIT_memmove
379 #include <string.h>
380 #define STB_TEXTEDIT_memmove memmove
381 #endif
382 
383 
384 /////////////////////////////////////////////////////////////////////////////
385 //
386 //      Mouse input handling
387 //
388 
389 // traverse the layout to locate the nearest character to a display position
stb_text_locate_coord(STB_TEXTEDIT_STRING * str,float x,float y)390 static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y)
391 {
392    StbTexteditRow r;
393    int n = STB_TEXTEDIT_STRINGLEN(str);
394    float base_y = 0, prev_x;
395    int i=0, k;
396 
397    r.x0 = r.x1 = 0;
398    r.ymin = r.ymax = 0;
399    r.num_chars = 0;
400 
401    // search rows to find one that straddles 'y'
402    while (i < n) {
403       STB_TEXTEDIT_LAYOUTROW(&r, str, i);
404       if (r.num_chars <= 0)
405          return n;
406 
407       if (i==0 && y < base_y + r.ymin)
408          return 0;
409 
410       if (y < base_y + r.ymax)
411          break;
412 
413       i += r.num_chars;
414       base_y += r.baseline_y_delta;
415    }
416 
417    // below all text, return 'after' last character
418    if (i >= n)
419       return n;
420 
421    // check if it's before the beginning of the line
422    if (x < r.x0)
423       return i;
424 
425    // check if it's before the end of the line
426    if (x < r.x1) {
427       // search characters in row for one that straddles 'x'
428       prev_x = r.x0;
429       for (k=0; k < r.num_chars; ++k) {
430          float w = STB_TEXTEDIT_GETWIDTH(str, i, k);
431          if (x < prev_x+w) {
432             if (x < prev_x+w/2)
433                return k+i;
434             else
435                return k+i+1;
436          }
437          prev_x += w;
438       }
439       // shouldn't happen, but if it does, fall through to end-of-line case
440    }
441 
442    // if the last character is a newline, return that. otherwise return 'after' the last character
443    if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE)
444       return i+r.num_chars-1;
445    else
446       return i+r.num_chars;
447 }
448 
449 // 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)450 static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
451 {
452    // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse
453    // goes off the top or bottom of the text
454    if( state->single_line )
455    {
456       StbTexteditRow r;
457       STB_TEXTEDIT_LAYOUTROW(&r, str, 0);
458       y = r.ymin;
459    }
460 
461    state->cursor = stb_text_locate_coord(str, x, y);
462    state->select_start = state->cursor;
463    state->select_end = state->cursor;
464    state->has_preferred_x = 0;
465 }
466 
467 // 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)468 static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
469 {
470    int p = 0;
471 
472    // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse
473    // goes off the top or bottom of the text
474    if( state->single_line )
475    {
476       StbTexteditRow r;
477       STB_TEXTEDIT_LAYOUTROW(&r, str, 0);
478       y = r.ymin;
479    }
480 
481    if (state->select_start == state->select_end)
482       state->select_start = state->cursor;
483 
484    p = stb_text_locate_coord(str, x, y);
485    state->cursor = state->select_end = p;
486 }
487 
488 /////////////////////////////////////////////////////////////////////////////
489 //
490 //      Keyboard input handling
491 //
492 
493 // forward declarations
494 static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state);
495 static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state);
496 static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length);
497 static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length);
498 static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length);
499 
500 typedef struct
501 {
502    float x,y;    // position of n'th character
503    float height; // height of line
504    int first_char, length; // first char of row, and length
505    int prev_first;  // first char of previous row
506 } StbFindState;
507 
508 // find the x/y location of a character, and remember info about the previous row in
509 // 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)510 static void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *str, int n, int single_line)
511 {
512    StbTexteditRow r;
513    int prev_start = 0;
514    int z = STB_TEXTEDIT_STRINGLEN(str);
515    int i=0, first;
516 
517    if (n == z) {
518       // if it's at the end, then find the last line -- simpler than trying to
519       // explicitly handle this case in the regular code
520       if (single_line) {
521          STB_TEXTEDIT_LAYOUTROW(&r, str, 0);
522          find->y = 0;
523          find->first_char = 0;
524          find->length = z;
525          find->height = r.ymax - r.ymin;
526          find->x = r.x1;
527       } else {
528          find->y = 0;
529          find->x = 0;
530          find->height = 1;
531          while (i < z) {
532             STB_TEXTEDIT_LAYOUTROW(&r, str, i);
533             prev_start = i;
534             i += r.num_chars;
535          }
536          find->first_char = i;
537          find->length = 0;
538          find->prev_first = prev_start;
539       }
540       return;
541    }
542 
543    // search rows to find the one that straddles character n
544    find->y = 0;
545 
546    for(;;) {
547       STB_TEXTEDIT_LAYOUTROW(&r, str, i);
548       if (n < i + r.num_chars)
549          break;
550       prev_start = i;
551       i += r.num_chars;
552       find->y += r.baseline_y_delta;
553    }
554 
555    find->first_char = first = i;
556    find->length = r.num_chars;
557    find->height = r.ymax - r.ymin;
558    find->prev_first = prev_start;
559 
560    // now scan to find xpos
561    find->x = r.x0;
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); // implicitly 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); // implicitly 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 -= n;
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 -= n; // @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 += n;
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 += n;
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 = (STB_TEXTEDIT_POSITIONTYPE) insert_len;
1169    r->delete_length = (STB_TEXTEDIT_POSITIONTYPE) 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 += 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 - 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