On 24.07.2017 13:49 Svets wrote:
>
> I'm having some problems with this.
> As per the below example, the Bold Button on the Window serves to bold
> selected text in the Text_Editor.
>
> The problem is that when text has been formatted, it pushes all the
> formatting one or two spaces to the right, depending
> on how many characters I am reformatting.
> [...]
See my attached test file for improved and (almost?) working code. After
my code was ready I realized that Greg had already posted his version.
The modifications we made to the code are very similar, but here are
some notes:
I left some test statements in the code to show the params and outcome
of change_cback() and change_text().
I *thought* that change_cback() could be called with both nDeleted and
nInserted > 0 in the case you select text and paste another text from
the clipboard over the selected text, but as you can see with my test
code it is called twice (first with nDeleted > 0, then with nInserted >
0). I don't think that this is documented (please check!), so I'd prefer
my version that would handle both > 0 in a single call as well.
I also removed unused variables, updated the style table, and put the
highlight_data() call into main.
I found some strange behavior when you:
(a) select some text
(b) click "Bold"
(c) click anywhere in the editor to unselect the text
(d) click "Bold" again w/o text selection.
In this case buf->primary_selection() returns the old selection, but
strlen(buf->selection_text()) == 0. The former seems to be wrong [1],
the latter is IMHO correct.
The following code in change_text() handles this correctly:
int start_pos = ts->start();
int end_pos = ts->start() + n_chars_selected; // should be: ts->end();
if (n_chars_selected > 0)
style_buffer->replace(start_pos, end_pos, s_char.c_str());
Instead of using ts->end() directly the end() is calculated, and then
the condition (n_chars_selected > 0) prevents calling the replacement
with an empty string. You could also just return if n_chars_selected == 0.
I didn't test Greg's code for this special behavior - I'll leave it to
the OP to compare and test...
[1] I wonder if the fact that primary_selection() returns a valid
selection (the old one) even if the selection has been "clicked away" is
a bug. Maybe we should check that in FLTK or file an STR at least...