Skip to content

ImGui::InputText Max Length with Text Selection Replacement #9029

Closed

Description

@Wangbull

Version/Branch of Dear ImGui:

Version 1.92.3

Back-ends:

imgui_impl_win32.h + imgui_impl_dx11.h

Compiler, OS:

Windows11+MSVC 2022

Full config/build information:

No response

Details:

ImGui::InputText Max Length with Text Selection Replacement

I'm trying to create an ImGui input box that meets two requirements:

  1. Limit the maximum number of characters (max_chars).
  2. Allow selecting text and replacing it directly (e.g., select a portion and type new characters to replace the selection).

Currently, my implementation (C++/ImGui) looks like this:

Screenshots/Video:

No response

Minimal, Complete and Verifiable Example code:

bool InputTextCentered(const char *label, std::string* str, float width, int max_chars)
{
    ImVec2 text_size = ImGui::CalcTextSize(str->c_str());
    float text_offset_x = (width - text_size.x) * 0.5f;
    if (text_offset_x < 0) text_offset_x = 0;

    ImGui::SetNextItemWidth(width);
    ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(text_offset_x, ImGui::GetStyle().FramePadding.y));

    InputTextUserData user_data{str, max_chars};

    bool changed = ImGui::InputText(label, str,
        ImGuiInputTextFlags_CallbackCharFilter | ImGuiInputTextFlags_CallbackEdit,
        [](ImGuiInputTextCallbackData* data) -> int {
            auto* user = (InputTextUserData*)data->UserData;

            if (data->EventFlag == ImGuiInputTextFlags_CallbackCharFilter) {
                if (data->EventChar < 32) return 1;
            }
            else if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit) {
                int selectionStart = data->SelectionStart;
                int selectionEnd   = data->SelectionEnd;
                int sel_len        = selectionEnd - selectionStart;
                int current_len    = (int)user->str->size();
                int allowed        = user->max_chars - (current_len - sel_len);

                if (allowed < 0) {
                    user->str->erase(user->max_chars);
                    data->BufTextLen = user->str->size();
                }
            }

            return 0;
        }, &user_data);

    ImGui::PopStyleVar();
    return changed;
}

Activity

  1. Wangbull commented on Oct 23, 2025

    @Wangbull
    Author

    The problem:

    When text is selected, replacing it does not properly respect the length limit.

    I'm not sure whether to use CallbackCharFilter, CallbackEdit, or some combination to enforce max length while handling text replacement.

    Looking for a solution that enforces a maximum character limit while correctly supporting selection replacement in an InputText callback.

  2. ocornut commented on Oct 23, 2025

    @ocornut
    Owner

    FYI specifying a fixed buf size works:

    static char buf[32] = "ABCDE00000";
    ImGui::InputText("test", buf, 10+1);

    But a paste that goes beyond limit is cancelled out.

  3. ocornut commented on Oct 23, 2025

    @ocornut
    Owner

    If you want newly pasted content to have priority (always insert), that's a possibility:

    static char buf[32] = "ABCDE00000";
    auto callback = [](ImGuiInputTextCallbackData* data)
    {
        if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit)
        {
            const int max_len = 10;
            if (data->BufTextLen > max_len)
            {
                data->BufTextLen = max_len;
                data->Buf[max_len] = 0;
                data->BufDirty = true;
                if (data->CursorPos > max_len)
                    data->CursorPos = max_len;
            }
        }
        return 0;
    };
    ImGui::InputText("test", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CallbackEdit, callback);

    PS: clamping CursorPos (if (data->CursorPos > max_len) data->CursorPos = max_len;) is currently required but it is a bug IMHO which I will fix right away to auto-clamp.

  4. ocornut commented on Oct 23, 2025

    @ocornut
    Owner

    PS: clamping CursorPos (if (data->CursorPos > max_len) data->CursorPos = max_len;) is currently required but it is a bug IMHO which I will fix right away to auto-clamp.

    Pushed a small change 750c5d2 so the code above doesn't need the if (data->CursorPos > max_len) data->CursorPos = max_len; part.

  5. ocornut commented on Oct 23, 2025

    @ocornut
    Owner

    I guess the best solution is to use this:

    for char[]:

    static char buf[32] = "ABCDE00000";
    ImGui::InputText("test", buf, 10+1);

    for std::string rely on enforcing the limit:

    static std::string str;
    str.reserve(10);
    ImGui::InputText("str", (char*)str.data(), 10);

    With this setup, you can have a 10-long string, select 5 characters and paste 5 characters.


    However you will hit the current limitation:

    • If you have a 8 long string, try to paste 5 characters: pasting will be cancelled.
    • If you have a 10 long string, select 2 character, try to paste 5 characters: selection will be deleted, pasting will be cancelled.

    For this to work we will need to rework STB_TEXTEDIT_INSERTCHARS() to return a count instead of a bool and allow partial append.

  6. ocornut commented on Oct 23, 2025

    @ocornut
    Owner

    However you will hit the current limitation:
    If you have a 8 long string, try to paste 5 characters: pasting will be cancelled.
    If you have a 10 long string, select 2 character, try to paste 5 characters: selection will be deleted, pasting will be cancelled.
    For this to work we will need to rework STB_TEXTEDIT_INSERTCHARS() to return a count instead of a bool and allow partial append.

    I have decided to rework this:

    I believe it is more consistent with typing text and therefore a better behavior for InputText().

    To answer your precise problem, use code in #9029 (comment) and if you want clipboard paste truncating you should update the code.

  7. added a commit that references this issue on Oct 29, 2025
  8. ocornut commented on Oct 29, 2025

    @ocornut
    Owner

    I have reverted the truncation behavior with 2a194e2 because it can truncate in the middle of a UTF-8 sequence which is quite undesirable. Will investigate.

  9. ocornut commented on Oct 29, 2025

    @ocornut
    Owner

    Truncation is now performed between UTF-8 codepoints with 3c578fa + pushed a new widgets_inputtext_insert_truncate_2 test: ocornut/imgui_test_engine@46a98fb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      ⌂ 换网址