Path: blob/master/dep/imgui/include/imstb_textedit.h
7502 views
// [DEAR IMGUI]1// This is a slightly modified version of stb_textedit.h 1.14.2// Those changes would need to be pushed into nothings/stb:3// - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321)4// - Fix in stb_textedit_find_charpos to handle last line (see https://github.com/ocornut/imgui/issues/6000 + #6783)5// - Added name to struct or it may be forward declared in our code.6// - Added UTF-8 support (see https://github.com/nothings/stb/issues/188 + https://github.com/ocornut/imgui/pull/7925)7// - Changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion.8// Grep for [DEAR IMGUI] to find some changes.9// - Also renamed macros used or defined outside of IMSTB_TEXTEDIT_IMPLEMENTATION block from STB_TEXTEDIT_* to IMSTB_TEXTEDIT_*1011// stb_textedit.h - v1.14 - public domain - Sean Barrett12// Development of this library was sponsored by RAD Game Tools13//14// This C header file implements the guts of a multi-line text-editing15// widget; you implement display, word-wrapping, and low-level string16// insertion/deletion, and stb_textedit will map user inputs into17// insertions & deletions, plus updates to the cursor position,18// selection state, and undo state.19//20// It is intended for use in games and other systems that need to build21// their own custom widgets and which do not have heavy text-editing22// requirements (this library is not recommended for use for editing large23// texts, as its performance does not scale and it has limited undo).24//25// Non-trivial behaviors are modelled after Windows text controls.26//27//28// LICENSE29//30// See end of file for license information.31//32//33// DEPENDENCIES34//35// Uses the C runtime function 'memmove', which you can override36// by defining IMSTB_TEXTEDIT_memmove before the implementation.37// Uses no other functions. Performs no runtime allocations.38//39//40// VERSION HISTORY41//42// !!!! (2025-10-23) changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion.43// 1.14 (2021-07-11) page up/down, various fixes44// 1.13 (2019-02-07) fix bug in undo size management45// 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash46// 1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield47// 1.10 (2016-10-25) suppress warnings about casting away const with -Wcast-qual48// 1.9 (2016-08-27) customizable move-by-word49// 1.8 (2016-04-02) better keyboard handling when mouse button is down50// 1.7 (2015-09-13) change y range handling in case baseline is non-051// 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove52// 1.5 (2014-09-10) add support for secondary keys for OS X53// 1.4 (2014-08-17) fix signed/unsigned warnings54// 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary55// 1.2 (2014-05-27) fix some RAD types that had crept into the new code56// 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE )57// 1.0 (2012-07-26) improve documentation, initial public release58// 0.3 (2012-02-24) bugfixes, single-line mode; insert mode59// 0.2 (2011-11-28) fixes to undo/redo60// 0.1 (2010-07-08) initial version61//62// ADDITIONAL CONTRIBUTORS63//64// Ulf Winklemann: move-by-word in 1.165// Fabian Giesen: secondary key inputs in 1.566// Martins Mozeiko: STB_TEXTEDIT_memmove in 1.667// Louis Schnellbach: page up/down in 1.1468//69// Bugfixes:70// Scott Graham71// Daniel Keller72// Omar Cornut73// Dan Thompson74//75// USAGE76//77// This file behaves differently depending on what symbols you define78// before including it.79//80//81// Header-file mode:82//83// If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this,84// it will operate in "header file" mode. In this mode, it declares a85// single public symbol, STB_TexteditState, which encapsulates the current86// state of a text widget (except for the string, which you will store87// separately).88//89// To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a90// primitive type that defines a single character (e.g. char, wchar_t, etc).91//92// To save space or increase undo-ability, you can optionally define the93// following things that are used by the undo system:94//95// STB_TEXTEDIT_POSITIONTYPE small int type encoding a valid cursor position96// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow97// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer98//99// If you don't define these, they are set to permissive types and100// moderate sizes. The undo system does no memory allocations, so101// it grows STB_TexteditState by the worst-case storage which is (in bytes):102//103// [4 + 3 * sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATECOUNT104// + sizeof(STB_TEXTEDIT_CHARTYPE) * STB_TEXTEDIT_UNDOCHARCOUNT105//106//107// Implementation mode:108//109// If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it110// will compile the implementation of the text edit widget, depending111// on a large number of symbols which must be defined before the include.112//113// The implementation is defined only as static functions. You will then114// need to provide your own APIs in the same file which will access the115// static functions.116//117// The basic concept is that you provide a "string" object which118// behaves like an array of characters. stb_textedit uses indices to119// refer to positions in the string, implicitly representing positions120// in the displayed textedit. This is true for both plain text and121// rich text; even with rich text stb_truetype interacts with your122// code as if there was an array of all the displayed characters.123//124// Symbols that must be the same in header-file and implementation mode:125//126// STB_TEXTEDIT_CHARTYPE the character type127// STB_TEXTEDIT_POSITIONTYPE small type that is a valid cursor position128// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow129// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer130//131// Symbols you must define for implementation mode:132//133// STB_TEXTEDIT_STRING the type of object representing a string being edited,134// typically this is a wrapper object with other data you need135//136// STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1))137// STB_TEXTEDIT_LAYOUTROW(&r,obj,n) returns the results of laying out a line of characters138// starting from character #n (see discussion below)139// STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character140// to the xpos of the i+1'th char for a line of characters141// starting at character #n (i.e. accounts for kerning142// with previous char)143// STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable character144// (return type is int, -1 means not valid to insert)145// (not supported if you want to use UTF-8, see below)146// STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 0-based147// STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize148// as manually wordwrapping for end-of-line positioning149//150// STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i151// STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n) try to insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*)152// returns number of characters actually inserted. [DEAR IMGUI]153//154// STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key155//156// STB_TEXTEDIT_K_LEFT keyboard input to move cursor left157// STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right158// STB_TEXTEDIT_K_UP keyboard input to move cursor up159// STB_TEXTEDIT_K_DOWN keyboard input to move cursor down160// STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page161// STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page162// STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line // e.g. HOME163// STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line // e.g. END164// STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text // e.g. ctrl-HOME165// STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text // e.g. ctrl-END166// STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor167// STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor168// STB_TEXTEDIT_K_UNDO keyboard input to perform undo169// STB_TEXTEDIT_K_REDO keyboard input to perform redo170//171// Optional:172// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode173// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'),174// required for default WORDLEFT/WORDRIGHT handlers175// STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to176// STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to177// STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT178// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT179// STB_TEXTEDIT_K_LINESTART2 secondary keyboard input to move cursor to start of line180// STB_TEXTEDIT_K_LINEEND2 secondary keyboard input to move cursor to end of line181// STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text182// STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text183//184// To support UTF-8:185//186// STB_TEXTEDIT_GETPREVCHARINDEX returns index of previous character187// STB_TEXTEDIT_GETNEXTCHARINDEX returns index of next character188// Do NOT define STB_TEXTEDIT_KEYTOTEXT.189// Instead, call stb_textedit_text() directly for text contents.190//191// Keyboard input must be encoded as a single integer value; e.g. a character code192// and some bitflags that represent shift states. to simplify the interface, SHIFT must193// be a bitflag, so we can test the shifted state of cursor movements to allow selection,194// i.e. (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow.195//196// You can encode other things, such as CONTROL or ALT, in additional bits, and197// then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example,198// my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN199// bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit,200// and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in the201// API below. The control keys will only match WM_KEYDOWN events because of the202// keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN203// bit so it only decodes WM_CHAR events.204//205// STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed206// row of characters assuming they start on the i'th character--the width and207// the height and the number of characters consumed. This allows this library208// to traverse the entire layout incrementally. You need to compute word-wrapping209// here.210//211// Each textfield keeps its own insert mode state, which is not how normal212// applications work. To keep an app-wide insert mode, update/copy the213// "insert_mode" field of STB_TexteditState before/after calling API functions.214//215// API216//217// void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line)218//219// void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)220// void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)221// int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)222// int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len)223// void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key)224// void stb_textedit_text(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int text_len)225//226// Each of these functions potentially updates the string and updates the227// state.228//229// initialize_state:230// set the textedit state to a known good default state when initially231// constructing the textedit.232//233// click:234// call this with the mouse x,y on a mouse down; it will update the cursor235// and reset the selection start/end to the cursor point. the x,y must236// be relative to the text widget, with (0,0) being the top left.237//238// drag:239// call this with the mouse x,y on a mouse drag/up; it will update the240// cursor and the selection end point241//242// cut:243// call this to delete the current selection; returns true if there was244// one. you should FIRST copy the current selection to the system paste buffer.245// (To copy, just copy the current selection out of the string yourself.)246//247// paste:248// call this to paste text at the current cursor point or over the current249// selection if there is one.250//251// key:252// call this for keyboard inputs sent to the textfield. you can use it253// for "key down" events or for "translated" key events. if you need to254// do both (as in Win32), or distinguish Unicode characters from control255// inputs, set a high bit to distinguish the two; then you can define the256// various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit257// set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is258// clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to259// anything other type you want before including.260// if the STB_TEXTEDIT_KEYTOTEXT function is defined, selected keys are261// transformed into text and stb_textedit_text() is automatically called.262//263// text: (added 2025)264// call this to directly send text input the textfield, which is required265// for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT()266// cannot infer text length.267//268//269// When rendering, you can read the cursor position and selection state from270// the STB_TexteditState.271//272//273// Notes:274//275// This is designed to be usable in IMGUI, so it allows for the possibility of276// running in an IMGUI that has NOT cached the multi-line layout. For this277// reason, it provides an interface that is compatible with computing the278// layout incrementally--we try to make sure we make as few passes through279// as possible. (For example, to locate the mouse pointer in the text, we280// could define functions that return the X and Y positions of characters281// and binary search Y and then X, but if we're doing dynamic layout this282// will run the layout algorithm many times, so instead we manually search283// forward in one pass. Similar logic applies to e.g. up-arrow and284// down-arrow movement.)285//286// If it's run in a widget that *has* cached the layout, then this is less287// efficient, but it's not horrible on modern computers. But you wouldn't288// want to edit million-line files with it.289290291////////////////////////////////////////////////////////////////////////////292////////////////////////////////////////////////////////////////////////////293////294//// Header-file mode295////296////297298#ifndef INCLUDE_IMSTB_TEXTEDIT_H299#define INCLUDE_IMSTB_TEXTEDIT_H300301////////////////////////////////////////////////////////////////////////302//303// STB_TexteditState304//305// Definition of STB_TexteditState which you should store306// per-textfield; it includes cursor position, selection state,307// and undo state.308//309310#ifndef IMSTB_TEXTEDIT_UNDOSTATECOUNT311#define IMSTB_TEXTEDIT_UNDOSTATECOUNT 99312#endif313#ifndef IMSTB_TEXTEDIT_UNDOCHARCOUNT314#define IMSTB_TEXTEDIT_UNDOCHARCOUNT 999315#endif316#ifndef IMSTB_TEXTEDIT_CHARTYPE317#define IMSTB_TEXTEDIT_CHARTYPE int318#endif319#ifndef IMSTB_TEXTEDIT_POSITIONTYPE320#define IMSTB_TEXTEDIT_POSITIONTYPE int321#endif322323typedef struct324{325// private data326IMSTB_TEXTEDIT_POSITIONTYPE where;327IMSTB_TEXTEDIT_POSITIONTYPE insert_length;328IMSTB_TEXTEDIT_POSITIONTYPE delete_length;329int char_storage;330} StbUndoRecord;331332typedef struct333{334// private data335StbUndoRecord undo_rec [IMSTB_TEXTEDIT_UNDOSTATECOUNT];336IMSTB_TEXTEDIT_CHARTYPE undo_char[IMSTB_TEXTEDIT_UNDOCHARCOUNT];337short undo_point, redo_point;338int undo_char_point, redo_char_point;339} StbUndoState;340341typedef struct STB_TexteditState342{343/////////////////////344//345// public data346//347348int cursor;349// position of the text cursor within the string350351int select_start; // selection start point352int select_end;353// selection start and end point in characters; if equal, no selection.354// note that start may be less than or greater than end (e.g. when355// dragging the mouse, start is where the initial click was, and you356// can drag in either direction)357358unsigned char insert_mode;359// each textfield keeps its own insert mode state. to keep an app-wide360// insert mode, copy this value in/out of the app state361362int row_count_per_page;363// page size in number of row.364// this value MUST be set to >0 for pageup or pagedown in multilines documents.365366/////////////////////367//368// private data369//370unsigned char cursor_at_end_of_line; // not implemented yet371unsigned char initialized;372unsigned char has_preferred_x;373unsigned char single_line;374unsigned char padding1, padding2, padding3;375float preferred_x; // this determines where the cursor up/down tries to seek to along x376StbUndoState undostate;377} STB_TexteditState;378379380////////////////////////////////////////////////////////////////////////381//382// StbTexteditRow383//384// Result of layout query, used by stb_textedit to determine where385// the text in each row is.386387// result of layout query388typedef struct389{390float x0,x1; // starting x location, end x location (allows for align=right, etc)391float baseline_y_delta; // position of baseline relative to previous row's baseline392float ymin,ymax; // height of row above and below baseline393int num_chars;394} StbTexteditRow;395#endif //INCLUDE_IMSTB_TEXTEDIT_H396397398////////////////////////////////////////////////////////////////////////////399////////////////////////////////////////////////////////////////////////////400////401//// Implementation mode402////403////404405406// implementation isn't include-guarded, since it might have indirectly407// included just the "header" portion408#ifdef IMSTB_TEXTEDIT_IMPLEMENTATION409410#ifndef IMSTB_TEXTEDIT_memmove411#include <string.h>412#define IMSTB_TEXTEDIT_memmove memmove413#endif414415// [DEAR IMGUI]416// Functions must be implemented for UTF8 support417// Code in this file that uses those functions is modified for [DEAR IMGUI] and deviates from the original stb_textedit.418// There is not necessarily a '[DEAR IMGUI]' at the usage sites.419#ifndef IMSTB_TEXTEDIT_GETPREVCHARINDEX420#define IMSTB_TEXTEDIT_GETPREVCHARINDEX(OBJ, IDX) ((IDX) - 1)421#endif422#ifndef IMSTB_TEXTEDIT_GETNEXTCHARINDEX423#define IMSTB_TEXTEDIT_GETNEXTCHARINDEX(OBJ, IDX) ((IDX) + 1)424#endif425426/////////////////////////////////////////////////////////////////////////////427//428// Mouse input handling429//430431// traverse the layout to locate the nearest character to a display position432static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y, int* out_side_on_line)433{434StbTexteditRow r;435int n = STB_TEXTEDIT_STRINGLEN(str);436float base_y = 0, prev_x;437int i=0, k;438439r.x0 = r.x1 = 0;440r.ymin = r.ymax = 0;441r.num_chars = 0;442*out_side_on_line = 0;443444// search rows to find one that straddles 'y'445while (i < n) {446STB_TEXTEDIT_LAYOUTROW(&r, str, i);447if (r.num_chars <= 0)448return n;449450if (i==0 && y < base_y + r.ymin)451return 0;452453if (y < base_y + r.ymax)454break;455456i += r.num_chars;457base_y += r.baseline_y_delta;458}459460// below all text, return 'after' last character461if (i >= n)462{463*out_side_on_line = 1;464return n;465}466467// check if it's before the beginning of the line468if (x < r.x0)469return i;470471// check if it's before the end of the line472if (x < r.x1) {473// search characters in row for one that straddles 'x'474prev_x = r.x0;475for (k=0; k < r.num_chars; k = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, i + k) - i) {476float w = STB_TEXTEDIT_GETWIDTH(str, i, k);477if (x < prev_x+w) {478*out_side_on_line = (k == 0) ? 0 : 1;479if (x < prev_x+w/2)480return k+i;481else482return IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, i + k);483}484prev_x += w;485}486// shouldn't happen, but if it does, fall through to end-of-line case487}488489// if the last character is a newline, return that. otherwise return 'after' the last character490*out_side_on_line = 1;491if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE)492return i+r.num_chars-1;493else494return i+r.num_chars;495}496497// API click: on mouse down, move the cursor to the clicked location, and reset the selection498static void stb_textedit_click(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)499{500// In single-line mode, just always make y = 0. This lets the drag keep working if the mouse501// goes off the top or bottom of the text502int side_on_line;503if( state->single_line )504{505StbTexteditRow r;506STB_TEXTEDIT_LAYOUTROW(&r, str, 0);507y = r.ymin;508}509510state->cursor = stb_text_locate_coord(str, x, y, &side_on_line);511state->select_start = state->cursor;512state->select_end = state->cursor;513state->has_preferred_x = 0;514str->LastMoveDirectionLR = (ImS8)(side_on_line ? ImGuiDir_Right : ImGuiDir_Left);515}516517// API drag: on mouse drag, move the cursor and selection endpoint to the clicked location518static void stb_textedit_drag(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)519{520int p = 0;521int side_on_line;522523// In single-line mode, just always make y = 0. This lets the drag keep working if the mouse524// goes off the top or bottom of the text525if( state->single_line )526{527StbTexteditRow r;528STB_TEXTEDIT_LAYOUTROW(&r, str, 0);529y = r.ymin;530}531532if (state->select_start == state->select_end)533state->select_start = state->cursor;534535p = stb_text_locate_coord(str, x, y, &side_on_line);536state->cursor = state->select_end = p;537str->LastMoveDirectionLR = (ImS8)(side_on_line ? ImGuiDir_Right : ImGuiDir_Left);538}539540/////////////////////////////////////////////////////////////////////////////541//542// Keyboard input handling543//544545// forward declarations546static void stb_text_undo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state);547static void stb_text_redo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state);548static void stb_text_makeundo_delete(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length);549static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length);550static void stb_text_makeundo_replace(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length);551552typedef struct553{554float x,y; // position of n'th character555float height; // height of line556int first_char, length; // first char of row, and length557int prev_first; // first char of previous row558} StbFindState;559560// find the x/y location of a character, and remember info about the previous row in561// case we get a move-up event (for page up, we'll have to rescan)562static void stb_textedit_find_charpos(StbFindState *find, IMSTB_TEXTEDIT_STRING *str, int n, int single_line)563{564StbTexteditRow r;565int prev_start = 0;566int z = STB_TEXTEDIT_STRINGLEN(str);567int i=0, first;568569if (n == z && single_line) {570// special case if it's at the end (may not be needed?)571STB_TEXTEDIT_LAYOUTROW(&r, str, 0);572find->y = 0;573find->first_char = 0;574find->length = z;575find->height = r.ymax - r.ymin;576find->x = r.x1;577return;578}579580// search rows to find the one that straddles character n581find->y = 0;582583for(;;) {584STB_TEXTEDIT_LAYOUTROW(&r, str, i);585if (n < i + r.num_chars)586break;587if (str->LastMoveDirectionLR == ImGuiDir_Right && str->Stb->cursor > 0 && str->Stb->cursor == i + r.num_chars && STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) != STB_TEXTEDIT_NEWLINE) // [DEAR IMGUI] Wrapping point handling588break;589if (i + r.num_chars == z && z > 0 && STB_TEXTEDIT_GETCHAR(str, z - 1) != STB_TEXTEDIT_NEWLINE) // [DEAR IMGUI] special handling for last line590break; // [DEAR IMGUI]591prev_start = i;592i += r.num_chars;593find->y += r.baseline_y_delta;594if (i == z) // [DEAR IMGUI]595{596r.num_chars = 0; // [DEAR IMGUI]597break; // [DEAR IMGUI]598}599}600601find->first_char = first = i;602find->length = r.num_chars;603find->height = r.ymax - r.ymin;604find->prev_first = prev_start;605606// now scan to find xpos607find->x = r.x0;608for (i=0; first+i < n; i = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, first + i) - first)609find->x += STB_TEXTEDIT_GETWIDTH(str, first, i);610}611612#define STB_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end)613614// make the selection/cursor state valid if client altered the string615static void stb_textedit_clamp(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state)616{617int n = STB_TEXTEDIT_STRINGLEN(str);618if (STB_TEXT_HAS_SELECTION(state)) {619if (state->select_start > n) state->select_start = n;620if (state->select_end > n) state->select_end = n;621// if clamping forced them to be equal, move the cursor to match622if (state->select_start == state->select_end)623state->cursor = state->select_start;624}625if (state->cursor > n) state->cursor = n;626}627628// delete characters while updating undo629static void stb_textedit_delete(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len)630{631stb_text_makeundo_delete(str, state, where, len);632STB_TEXTEDIT_DELETECHARS(str, where, len);633state->has_preferred_x = 0;634}635636// delete the section637static void stb_textedit_delete_selection(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state)638{639stb_textedit_clamp(str, state);640if (STB_TEXT_HAS_SELECTION(state)) {641if (state->select_start < state->select_end) {642stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start);643state->select_end = state->cursor = state->select_start;644} else {645stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end);646state->select_start = state->cursor = state->select_end;647}648state->has_preferred_x = 0;649}650}651652// canoncialize the selection so start <= end653static void stb_textedit_sortselection(STB_TexteditState *state)654{655if (state->select_end < state->select_start) {656int temp = state->select_end;657state->select_end = state->select_start;658state->select_start = temp;659}660}661662// move cursor to first character of selection663static void stb_textedit_move_to_first(STB_TexteditState *state)664{665if (STB_TEXT_HAS_SELECTION(state)) {666stb_textedit_sortselection(state);667state->cursor = state->select_start;668state->select_end = state->select_start;669state->has_preferred_x = 0;670}671}672673// move cursor to last character of selection674static void stb_textedit_move_to_last(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state)675{676if (STB_TEXT_HAS_SELECTION(state)) {677stb_textedit_sortselection(state);678stb_textedit_clamp(str, state);679state->cursor = state->select_end;680state->select_start = state->select_end;681state->has_preferred_x = 0;682}683}684685// [DEAR IMGUI] Extracted this function so we can more easily add support for word-wrapping.686#ifndef STB_TEXTEDIT_MOVELINESTART687static int stb_textedit_move_line_start(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int cursor)688{689if (state->single_line)690return 0;691while (cursor > 0) {692int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, cursor);693if (STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE)694break;695cursor = prev;696}697return cursor;698}699#define STB_TEXTEDIT_MOVELINESTART stb_textedit_move_line_start700#endif701#ifndef STB_TEXTEDIT_MOVELINEEND702static int stb_textedit_move_line_end(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int cursor)703{704int n = STB_TEXTEDIT_STRINGLEN(str);705if (state->single_line)706return n;707while (cursor < n && STB_TEXTEDIT_GETCHAR(str, cursor) != STB_TEXTEDIT_NEWLINE)708cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, cursor);709return cursor;710}711#define STB_TEXTEDIT_MOVELINEEND stb_textedit_move_line_end712#endif713714#ifdef STB_TEXTEDIT_IS_SPACE715static int is_word_boundary( IMSTB_TEXTEDIT_STRING *str, int idx )716{717return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1;718}719720#ifndef STB_TEXTEDIT_MOVEWORDLEFT721static int stb_textedit_move_to_word_previous( IMSTB_TEXTEDIT_STRING *str, int c )722{723c = IMSTB_TEXTEDIT_GETPREVCHARINDEX( str, c ); // always move at least one character724while (c >= 0 && !is_word_boundary(str, c))725c = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, c);726727if( c < 0 )728c = 0;729730return c;731}732#define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous733#endif734735#ifndef STB_TEXTEDIT_MOVEWORDRIGHT736static int stb_textedit_move_to_word_next( IMSTB_TEXTEDIT_STRING *str, int c )737{738const int len = STB_TEXTEDIT_STRINGLEN(str);739c = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, c); // always move at least one character740while( c < len && !is_word_boundary( str, c ) )741c = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, c);742743if( c > len )744c = len;745746return c;747}748#define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next749#endif750751#endif752753// update selection and cursor to match each other754static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state)755{756if (!STB_TEXT_HAS_SELECTION(state))757state->select_start = state->select_end = state->cursor;758else759state->cursor = state->select_end;760}761762// API cut: delete selection763static int stb_textedit_cut(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state)764{765if (STB_TEXT_HAS_SELECTION(state)) {766stb_textedit_delete_selection(str,state); // implicitly clamps767state->has_preferred_x = 0;768return 1;769}770return 0;771}772773// API paste: replace existing selection with passed-in text774static int stb_textedit_paste_internal(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, IMSTB_TEXTEDIT_CHARTYPE *text, int len)775{776// if there's a selection, the paste should delete it777stb_textedit_clamp(str, state);778stb_textedit_delete_selection(str,state);779// try to insert the characters780len = STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len);781if (len) {782stb_text_makeundo_insert(state, state->cursor, len);783state->cursor += len;784state->has_preferred_x = 0;785return 1;786}787// note: paste failure will leave deleted selection, may be restored with an undo (see https://github.com/nothings/stb/issues/734 for details)788return 0;789}790791#ifndef STB_TEXTEDIT_KEYTYPE792#define STB_TEXTEDIT_KEYTYPE int793#endif794795// API key: process text input796// [DEAR IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility.797static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len)798{799// can't add newline in single-line mode800if (text[0] == '\n' && state->single_line)801return;802803if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) {804stb_text_makeundo_replace(str, state, state->cursor, 1, 1);805STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1);806text_len = STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len);807if (text_len) {808state->cursor += text_len;809state->has_preferred_x = 0;810}811} else {812stb_textedit_delete_selection(str, state); // implicitly clamps813text_len = STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len);814if (text_len) {815stb_text_makeundo_insert(state, state->cursor, text_len);816state->cursor += text_len;817state->has_preferred_x = 0;818}819}820}821822// API key: process a keyboard input823static void stb_textedit_key(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key)824{825retry:826switch (key) {827default: {828#ifdef STB_TEXTEDIT_KEYTOTEXT829// This is not suitable for UTF-8 support.830int c = STB_TEXTEDIT_KEYTOTEXT(key);831if (c > 0) {832IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE)c;833stb_textedit_text(str, state, &ch, 1);834}835#endif836break;837}838839#ifdef STB_TEXTEDIT_K_INSERT840case STB_TEXTEDIT_K_INSERT:841state->insert_mode = !state->insert_mode;842break;843#endif844845case STB_TEXTEDIT_K_UNDO:846stb_text_undo(str, state);847state->has_preferred_x = 0;848break;849850case STB_TEXTEDIT_K_REDO:851stb_text_redo(str, state);852state->has_preferred_x = 0;853break;854855case STB_TEXTEDIT_K_LEFT:856// if currently there's a selection, move cursor to start of selection857if (STB_TEXT_HAS_SELECTION(state))858stb_textedit_move_to_first(state);859else860if (state->cursor > 0)861state->cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor);862state->has_preferred_x = 0;863break;864865case STB_TEXTEDIT_K_RIGHT:866// if currently there's a selection, move cursor to end of selection867if (STB_TEXT_HAS_SELECTION(state))868stb_textedit_move_to_last(str, state);869else870state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor);871stb_textedit_clamp(str, state);872state->has_preferred_x = 0;873break;874875case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT:876stb_textedit_clamp(str, state);877stb_textedit_prep_selection_at_cursor(state);878// move selection left879if (state->select_end > 0)880state->select_end = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->select_end);881state->cursor = state->select_end;882state->has_preferred_x = 0;883break;884885#ifdef STB_TEXTEDIT_MOVEWORDLEFT886case STB_TEXTEDIT_K_WORDLEFT:887if (STB_TEXT_HAS_SELECTION(state))888stb_textedit_move_to_first(state);889else {890state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor);891stb_textedit_clamp( str, state );892}893break;894895case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT:896if( !STB_TEXT_HAS_SELECTION( state ) )897stb_textedit_prep_selection_at_cursor(state);898899state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor);900state->select_end = state->cursor;901902stb_textedit_clamp( str, state );903break;904#endif905906#ifdef STB_TEXTEDIT_MOVEWORDRIGHT907case STB_TEXTEDIT_K_WORDRIGHT:908if (STB_TEXT_HAS_SELECTION(state))909stb_textedit_move_to_last(str, state);910else {911state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor);912stb_textedit_clamp( str, state );913}914break;915916case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT:917if( !STB_TEXT_HAS_SELECTION( state ) )918stb_textedit_prep_selection_at_cursor(state);919920state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor);921state->select_end = state->cursor;922923stb_textedit_clamp( str, state );924break;925#endif926927case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT:928stb_textedit_prep_selection_at_cursor(state);929// move selection right930state->select_end = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->select_end);931stb_textedit_clamp(str, state);932state->cursor = state->select_end;933state->has_preferred_x = 0;934break;935936case STB_TEXTEDIT_K_DOWN:937case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT:938case STB_TEXTEDIT_K_PGDOWN:939case STB_TEXTEDIT_K_PGDOWN | STB_TEXTEDIT_K_SHIFT: {940StbFindState find;941StbTexteditRow row;942int i, j, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;943int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGDOWN;944int row_count = is_page ? state->row_count_per_page : 1;945946if (!is_page && state->single_line) {947// on windows, up&down in single-line behave like left&right948key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT);949goto retry;950}951952if (sel)953stb_textedit_prep_selection_at_cursor(state);954else if (STB_TEXT_HAS_SELECTION(state))955stb_textedit_move_to_last(str, state);956957// compute current position of cursor point958stb_textedit_clamp(str, state);959stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);960961for (j = 0; j < row_count; ++j) {962float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x;963int start = find.first_char + find.length;964965if (find.length == 0)966break;967968// [DEAR IMGUI]969// going down while being on the last line shouldn't bring us to that line end970//if (STB_TEXTEDIT_GETCHAR(str, find.first_char + find.length - 1) != STB_TEXTEDIT_NEWLINE)971// break;972973// now find character position down a row974state->cursor = start;975STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);976x = row.x0;977for (i=0; i < row.num_chars; ) {978float dx = STB_TEXTEDIT_GETWIDTH(str, start, i);979int next = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor);980#ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE981if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE)982break;983#endif984x += dx;985if (x > goal_x)986break;987i += next - state->cursor;988state->cursor = next;989}990stb_textedit_clamp(str, state);991992if (state->cursor == find.first_char + find.length)993str->LastMoveDirectionLR = ImGuiDir_Left;994state->has_preferred_x = 1;995state->preferred_x = goal_x;996997if (sel)998state->select_end = state->cursor;9991000// go to next line1001find.first_char = find.first_char + find.length;1002find.length = row.num_chars;1003}1004break;1005}10061007case STB_TEXTEDIT_K_UP:1008case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT:1009case STB_TEXTEDIT_K_PGUP:1010case STB_TEXTEDIT_K_PGUP | STB_TEXTEDIT_K_SHIFT: {1011StbFindState find;1012StbTexteditRow row;1013int i, j, prev_scan, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;1014int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGUP;1015int row_count = is_page ? state->row_count_per_page : 1;10161017if (!is_page && state->single_line) {1018// on windows, up&down become left&right1019key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT);1020goto retry;1021}10221023if (sel)1024stb_textedit_prep_selection_at_cursor(state);1025else if (STB_TEXT_HAS_SELECTION(state))1026stb_textedit_move_to_first(state);10271028// compute current position of cursor point1029stb_textedit_clamp(str, state);1030stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);10311032for (j = 0; j < row_count; ++j) {1033float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x;10341035// can only go up if there's a previous row1036if (find.prev_first == find.first_char)1037break;10381039// now find character position up a row1040state->cursor = find.prev_first;1041STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);1042x = row.x0;1043for (i=0; i < row.num_chars; ) {1044float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i);1045int next = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor);1046#ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE1047if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE)1048break;1049#endif1050x += dx;1051if (x > goal_x)1052break;1053i += next - state->cursor;1054state->cursor = next;1055}1056stb_textedit_clamp(str, state);10571058if (state->cursor == find.first_char)1059str->LastMoveDirectionLR = ImGuiDir_Right;1060else if (state->cursor == find.prev_first)1061str->LastMoveDirectionLR = ImGuiDir_Left;1062state->has_preferred_x = 1;1063state->preferred_x = goal_x;10641065if (sel)1066state->select_end = state->cursor;10671068// go to previous line1069// (we need to scan previous line the hard way. maybe we could expose this as a new API function?)1070prev_scan = find.prev_first > 0 ? find.prev_first - 1 : 0;1071while (prev_scan > 0)1072{1073int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, prev_scan);1074if (STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE)1075break;1076prev_scan = prev;1077}1078find.first_char = find.prev_first;1079find.prev_first = STB_TEXTEDIT_MOVELINESTART(str, state, prev_scan);1080}1081break;1082}10831084case STB_TEXTEDIT_K_DELETE:1085case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT:1086if (STB_TEXT_HAS_SELECTION(state))1087stb_textedit_delete_selection(str, state);1088else {1089int n = STB_TEXTEDIT_STRINGLEN(str);1090if (state->cursor < n)1091stb_textedit_delete(str, state, state->cursor, IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor) - state->cursor);1092}1093state->has_preferred_x = 0;1094break;10951096case STB_TEXTEDIT_K_BACKSPACE:1097case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT:1098if (STB_TEXT_HAS_SELECTION(state))1099stb_textedit_delete_selection(str, state);1100else {1101stb_textedit_clamp(str, state);1102if (state->cursor > 0) {1103int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor);1104stb_textedit_delete(str, state, prev, state->cursor - prev);1105state->cursor = prev;1106}1107}1108state->has_preferred_x = 0;1109break;11101111#ifdef STB_TEXTEDIT_K_TEXTSTART21112case STB_TEXTEDIT_K_TEXTSTART2:1113#endif1114case STB_TEXTEDIT_K_TEXTSTART:1115state->cursor = state->select_start = state->select_end = 0;1116state->has_preferred_x = 0;1117break;11181119#ifdef STB_TEXTEDIT_K_TEXTEND21120case STB_TEXTEDIT_K_TEXTEND2:1121#endif1122case STB_TEXTEDIT_K_TEXTEND:1123state->cursor = STB_TEXTEDIT_STRINGLEN(str);1124state->select_start = state->select_end = 0;1125state->has_preferred_x = 0;1126break;11271128#ifdef STB_TEXTEDIT_K_TEXTSTART21129case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT:1130#endif1131case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT:1132stb_textedit_prep_selection_at_cursor(state);1133state->cursor = state->select_end = 0;1134state->has_preferred_x = 0;1135break;11361137#ifdef STB_TEXTEDIT_K_TEXTEND21138case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT:1139#endif1140case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT:1141stb_textedit_prep_selection_at_cursor(state);1142state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str);1143state->has_preferred_x = 0;1144break;114511461147#ifdef STB_TEXTEDIT_K_LINESTART21148case STB_TEXTEDIT_K_LINESTART2:1149#endif1150case STB_TEXTEDIT_K_LINESTART:1151stb_textedit_clamp(str, state);1152stb_textedit_move_to_first(state);1153state->cursor = STB_TEXTEDIT_MOVELINESTART(str, state, state->cursor);1154state->has_preferred_x = 0;1155break;11561157#ifdef STB_TEXTEDIT_K_LINEEND21158case STB_TEXTEDIT_K_LINEEND2:1159#endif1160case STB_TEXTEDIT_K_LINEEND: {1161stb_textedit_clamp(str, state);1162stb_textedit_move_to_last(str, state);1163state->cursor = STB_TEXTEDIT_MOVELINEEND(str, state, state->cursor);1164state->has_preferred_x = 0;1165break;1166}11671168#ifdef STB_TEXTEDIT_K_LINESTART21169case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT:1170#endif1171case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT:1172stb_textedit_clamp(str, state);1173stb_textedit_prep_selection_at_cursor(state);1174state->cursor = STB_TEXTEDIT_MOVELINESTART(str, state, state->cursor);1175state->select_end = state->cursor;1176state->has_preferred_x = 0;1177break;11781179#ifdef STB_TEXTEDIT_K_LINEEND21180case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT:1181#endif1182case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: {1183stb_textedit_clamp(str, state);1184stb_textedit_prep_selection_at_cursor(state);1185state->cursor = STB_TEXTEDIT_MOVELINEEND(str, state, state->cursor);1186state->select_end = state->cursor;1187state->has_preferred_x = 0;1188break;1189}1190}1191}11921193/////////////////////////////////////////////////////////////////////////////1194//1195// Undo processing1196//1197// @OPTIMIZE: the undo/redo buffer should be circular11981199static void stb_textedit_flush_redo(StbUndoState *state)1200{1201state->redo_point = IMSTB_TEXTEDIT_UNDOSTATECOUNT;1202state->redo_char_point = IMSTB_TEXTEDIT_UNDOCHARCOUNT;1203}12041205// discard the oldest entry in the undo list1206static void stb_textedit_discard_undo(StbUndoState *state)1207{1208if (state->undo_point > 0) {1209// if the 0th undo state has characters, clean those up1210if (state->undo_rec[0].char_storage >= 0) {1211int n = state->undo_rec[0].insert_length, i;1212// delete n characters from all other records1213state->undo_char_point -= n;1214IMSTB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) (state->undo_char_point*sizeof(IMSTB_TEXTEDIT_CHARTYPE)));1215for (i=0; i < state->undo_point; ++i)1216if (state->undo_rec[i].char_storage >= 0)1217state->undo_rec[i].char_storage -= n; // @OPTIMIZE: get rid of char_storage and infer it1218}1219--state->undo_point;1220IMSTB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) (state->undo_point*sizeof(state->undo_rec[0])));1221}1222}12231224// discard the oldest entry in the redo list--it's bad if this1225// ever happens, but because undo & redo have to store the actual1226// characters in different cases, the redo character buffer can1227// fill up even though the undo buffer didn't1228static void stb_textedit_discard_redo(StbUndoState *state)1229{1230int k = IMSTB_TEXTEDIT_UNDOSTATECOUNT-1;12311232if (state->redo_point <= k) {1233// if the k'th undo state has characters, clean those up1234if (state->undo_rec[k].char_storage >= 0) {1235int n = state->undo_rec[k].insert_length, i;1236// move the remaining redo character data to the end of the buffer1237state->redo_char_point += n;1238IMSTB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((IMSTB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(IMSTB_TEXTEDIT_CHARTYPE)));1239// adjust the position of all the other records to account for above memmove1240for (i=state->redo_point; i < k; ++i)1241if (state->undo_rec[i].char_storage >= 0)1242state->undo_rec[i].char_storage += n;1243}1244// now move all the redo records towards the end of the buffer; the first one is at 'redo_point'1245// [DEAR IMGUI]1246size_t move_size = (size_t)((IMSTB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point - 1) * sizeof(state->undo_rec[0]));1247const char* buf_begin = (char*)state->undo_rec; (void)buf_begin;1248const char* buf_end = (char*)state->undo_rec + sizeof(state->undo_rec); (void)buf_end;1249IM_ASSERT(((char*)(state->undo_rec + state->redo_point)) >= buf_begin);1250IM_ASSERT(((char*)(state->undo_rec + state->redo_point + 1) + move_size) <= buf_end);1251IMSTB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, move_size);12521253// now move redo_point to point to the new one1254++state->redo_point;1255}1256}12571258static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars)1259{1260// any time we create a new undo record, we discard redo1261stb_textedit_flush_redo(state);12621263// if we have no free records, we have to make room, by sliding the1264// existing records down1265if (state->undo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT)1266stb_textedit_discard_undo(state);12671268// if the characters to store won't possibly fit in the buffer, we can't undo1269if (numchars > IMSTB_TEXTEDIT_UNDOCHARCOUNT) {1270state->undo_point = 0;1271state->undo_char_point = 0;1272return NULL;1273}12741275// if we don't have enough free characters in the buffer, we have to make room1276while (state->undo_char_point + numchars > IMSTB_TEXTEDIT_UNDOCHARCOUNT)1277stb_textedit_discard_undo(state);12781279return &state->undo_rec[state->undo_point++];1280}12811282static IMSTB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len)1283{1284StbUndoRecord *r = stb_text_create_undo_record(state, insert_len);1285if (r == NULL)1286return NULL;12871288r->where = pos;1289r->insert_length = (IMSTB_TEXTEDIT_POSITIONTYPE) insert_len;1290r->delete_length = (IMSTB_TEXTEDIT_POSITIONTYPE) delete_len;12911292if (insert_len == 0) {1293r->char_storage = -1;1294return NULL;1295} else {1296r->char_storage = state->undo_char_point;1297state->undo_char_point += insert_len;1298return &state->undo_char[r->char_storage];1299}1300}13011302static void stb_text_undo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state)1303{1304StbUndoState *s = &state->undostate;1305StbUndoRecord u, *r;1306if (s->undo_point == 0)1307return;13081309// we need to do two things: apply the undo record, and create a redo record1310u = s->undo_rec[s->undo_point-1];1311r = &s->undo_rec[s->redo_point-1];1312r->char_storage = -1;13131314r->insert_length = u.delete_length;1315r->delete_length = u.insert_length;1316r->where = u.where;13171318if (u.delete_length) {1319// if the undo record says to delete characters, then the redo record will1320// need to re-insert the characters that get deleted, so we need to store1321// them.13221323// there are three cases:1324// there's enough room to store the characters1325// characters stored for *redoing* don't leave room for redo1326// characters stored for *undoing* don't leave room for redo1327// if the last is true, we have to bail13281329if (s->undo_char_point + u.delete_length >= IMSTB_TEXTEDIT_UNDOCHARCOUNT) {1330// the undo records take up too much character space; there's no space to store the redo characters1331r->insert_length = 0;1332} else {1333int i;13341335// there's definitely room to store the characters eventually1336while (s->undo_char_point + u.delete_length > s->redo_char_point) {1337// should never happen:1338if (s->redo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT)1339return;1340// there's currently not enough room, so discard a redo record1341stb_textedit_discard_redo(s);1342}1343r = &s->undo_rec[s->redo_point-1];13441345r->char_storage = s->redo_char_point - u.delete_length;1346s->redo_char_point = s->redo_char_point - u.delete_length;13471348// now save the characters1349for (i=0; i < u.delete_length; ++i)1350s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i);1351}13521353// now we can carry out the deletion1354STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length);1355}13561357// check type of recorded action:1358if (u.insert_length) {1359// easy case: was a deletion, so we need to insert n characters1360u.insert_length = STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length);1361s->undo_char_point -= u.insert_length;1362}13631364state->cursor = u.where + u.insert_length;13651366s->undo_point--;1367s->redo_point--;1368}13691370static void stb_text_redo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state)1371{1372StbUndoState *s = &state->undostate;1373StbUndoRecord *u, r;1374if (s->redo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT)1375return;13761377// we need to do two things: apply the redo record, and create an undo record1378u = &s->undo_rec[s->undo_point];1379r = s->undo_rec[s->redo_point];13801381// we KNOW there must be room for the undo record, because the redo record1382// was derived from an undo record13831384u->delete_length = r.insert_length;1385u->insert_length = r.delete_length;1386u->where = r.where;1387u->char_storage = -1;13881389if (r.delete_length) {1390// the redo record requires us to delete characters, so the undo record1391// needs to store the characters13921393if (s->undo_char_point + u->insert_length > s->redo_char_point) {1394u->insert_length = 0;1395u->delete_length = 0;1396} else {1397int i;1398u->char_storage = s->undo_char_point;1399s->undo_char_point = s->undo_char_point + u->insert_length;14001401// now save the characters1402for (i=0; i < u->insert_length; ++i)1403s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i);1404}14051406STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length);1407}14081409if (r.insert_length) {1410// easy case: need to insert n characters1411r.insert_length = STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length);1412s->redo_char_point += r.insert_length;1413}14141415state->cursor = r.where + r.insert_length;14161417s->undo_point++;1418s->redo_point++;1419}14201421static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length)1422{1423stb_text_createundo(&state->undostate, where, 0, length);1424}14251426static void stb_text_makeundo_delete(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length)1427{1428int i;1429IMSTB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0);1430if (p) {1431for (i=0; i < length; ++i)1432p[i] = STB_TEXTEDIT_GETCHAR(str, where+i);1433}1434}14351436static void stb_text_makeundo_replace(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length)1437{1438int i;1439IMSTB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length);1440if (p) {1441for (i=0; i < old_length; ++i)1442p[i] = STB_TEXTEDIT_GETCHAR(str, where+i);1443}1444}14451446// reset the state to default1447static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line)1448{1449state->undostate.undo_point = 0;1450state->undostate.undo_char_point = 0;1451state->undostate.redo_point = IMSTB_TEXTEDIT_UNDOSTATECOUNT;1452state->undostate.redo_char_point = IMSTB_TEXTEDIT_UNDOCHARCOUNT;1453state->select_end = state->select_start = 0;1454state->cursor = 0;1455state->has_preferred_x = 0;1456state->preferred_x = 0;1457state->cursor_at_end_of_line = 0;1458state->initialized = 1;1459state->single_line = (unsigned char) is_single_line;1460state->insert_mode = 0;1461state->row_count_per_page = 0;1462}14631464// API initialize1465static void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line)1466{1467stb_textedit_clear_state(state, is_single_line);1468}14691470#if defined(__GNUC__) || defined(__clang__)1471#pragma GCC diagnostic push1472#pragma GCC diagnostic ignored "-Wcast-qual"1473#endif14741475static int stb_textedit_paste(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, IMSTB_TEXTEDIT_CHARTYPE const *ctext, int len)1476{1477return stb_textedit_paste_internal(str, state, (IMSTB_TEXTEDIT_CHARTYPE *) ctext, len);1478}14791480#if defined(__GNUC__) || defined(__clang__)1481#pragma GCC diagnostic pop1482#endif14831484#endif//IMSTB_TEXTEDIT_IMPLEMENTATION14851486/*1487------------------------------------------------------------------------------1488This software is available under 2 licenses -- choose whichever you prefer.1489------------------------------------------------------------------------------1490ALTERNATIVE A - MIT License1491Copyright (c) 2017 Sean Barrett1492Permission is hereby granted, free of charge, to any person obtaining a copy of1493this software and associated documentation files (the "Software"), to deal in1494the Software without restriction, including without limitation the rights to1495use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies1496of the Software, and to permit persons to whom the Software is furnished to do1497so, subject to the following conditions:1498The above copyright notice and this permission notice shall be included in all1499copies or substantial portions of the Software.1500THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR1501IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,1502FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE1503AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER1504LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,1505OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE1506SOFTWARE.1507------------------------------------------------------------------------------1508ALTERNATIVE B - Public Domain (www.unlicense.org)1509This is free and unencumbered software released into the public domain.1510Anyone is free to copy, modify, publish, use, compile, sell, or distribute this1511software, either in source code form or as a compiled binary, for any purpose,1512commercial or non-commercial, and by any means.1513In jurisdictions that recognize copyright laws, the author or authors of this1514software dedicate any and all copyright interest in the software to the public1515domain. We make this dedication for the benefit of the public at large and to1516the detriment of our heirs and successors. We intend this dedication to be an1517overt act of relinquishment in perpetuity of all present and future rights to1518this software under copyright law.1519THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR1520IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,1521FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE1522AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN1523ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION1524WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.1525------------------------------------------------------------------------------1526*/152715281529