0

I am writing a text editor using the wxWidgets framework. I need to get the word under caret from the text control. Here is what I came up with.

static bool IsWordBoundary(wxString& text)
{
    return (text.Cmp(wxT(" "))  == 0 || 
            text.Cmp(wxT('\n')) == 0 ||
            text.Cmp(wxT('\t')) == 0 ||
            text.Cmp(wxT('\r')) == 0);
}

static wxString GetWordUnderCaret(wxTextCtrl* control)
{
    int insertion_point = control->GetInsertionPoint();
    wxTextPos last_position = control->GetLastPosition();
    int start_at, ends_at = 0;

    // Finding starting position: 
    //   from the current caret position, move back each character until 
    //   we hit a word boundary.
    int caret_pos = insertion_point;
    start_at = caret_pos;
    while (caret_pos)
    {        
        wxString text = control->GetRange (caret_pos - 1, caret_pos);
        if (IsWordBoundary (text)) {
            break;
        }

        start_at = --caret_pos;
    }

    // Finding ending position: 
    //   from the current caret position, move forward each character until 
    //   we hit a word boundary.
    caret_pos = ends_at = insertion_point;    
    while (caret_pos < last_position)
    {
        wxString text = control->GetRange (caret_pos, caret_pos + 1);
        if (IsWordBoundary (text)) {
            break;
        }

        ends_at = ++caret_pos;
    }

    return (control->GetRange (start_at, ends_at));
}

This code works as expected. But I am wondering is this the best way to approach the problem? Do you see any possible fixes on the above code?

Any help would be great!

Navaneeth K N
  • 15,295
  • 38
  • 126
  • 184

2 Answers2

1

Is punctuation part of a word? It is in your code -- is that what you want?

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
0

Here is how I would do it:

wxString word_boundary_marks = " \n\t\r";
wxString text_in_control     = control->GetValue();
int ends_at                  = text_in_control.find_first_of( word_boundary_marks, insertion_point) - 1;
int start_at                 = text_in_control.Mid(0,insertion_point).find_last_of(word_boundary_marks) + 1;

I haven't tested this, so there likely are one or two "off-by-one" errors and you should add checks for "not found", end of string, and any other word markers. My code should give you the basis for what you need.

ravenspoint
  • 19,093
  • 6
  • 57
  • 103