wxRuby Documentation Home

# Wx::TextCtrl

A text control allows text to be displayed and edited. It may be single
line or multi-line. The multi-line version can be created with the
window style `TE_RICH` and `TE_RICH2`, in which case segments of text
can have visual styles applied to them: bold, italic, underline,
background and foreground colour, and font. Note that if the control may
need to contain longer texts – either 32k, or 64k, depending on
platform, it must be created with the `TE_RICH` styles.

TextCtrl uses native text editing components on all platforms, and this
means there are some minor inconsistencies, particularly in the
treatment of styled text. For more complex rich text editing needs,
consider using StyledTextCtrl, or for hypertext
display, HtmlWindow

## Derived from

Control

Window

EvtHandler

Object

## Window styles

`TE_PROCESS_ENTER` | The control will generate the event EVT_COMMAND_TEXT_ENTER (otherwise pressing Enter keyis either processed internally by the control or used for navigation betweendialog controls).
`TE_PROCESS_TAB` | The control will receive EVT_CHAR events for TAB pressed – normally, TAB is used for passing to thenext control in a dialog instead. For the control created with this style,you can still use Ctrl-Enter to pass to the next control from the keyboard.
`TE_MULTILINE` | The text control allows multiple lines.
`TE_PASSWORD` | The text will be echoed as asterisks.
`TE_READONLY` | The text will not be user-editable.
`TE_RICH` | Use rich text control under Win32, thisallows to have more than 64KB of text in the control even under Win9x. Thisstyle is ignored under other platforms.
`TE_RICH2` | Use rich text control version 2.0 or 3.0under Win32, this style is ignored under other platforms
`TE_AUTO_URL` | Highlight the URLs and generate theTextUrlEvents when mouse events occur over them. This style is only supported for `TE_RICH` Win32 and multi-line GTK2 text controls.
`TE_NOHIDESEL` | By default, the Windows text controldoesn’t show the selection when it doesn’t have focus – use this style to forceit to always show it. It doesn’t do anything under other platforms.
`HSCROLL` | A horizontal scrollbar will be created andused, so that text won’t be wrapped. No effect under GTK1.
`TE_LEFT` | The text in the control will be left-justified (default).
`TE_CENTRE` | The text in the control will be centered (currently MSW and GTK2 only).
`TE_RIGHT` | The text in the control will be right-justified (currently MSW and GTK2 only).
`TE_DONTWRAP` | Same as `HSCROLL` style: don’t wrap at all, show horizontal scrollbar instead.
`TE_CHARWRAP` | Wrap the lines too long to be shown entirely at any position (Univ and GTK2 only).
`TE_WORDWRAP` | Wrap the lines too long to be shown entirely at word boundaries (Univ and GTK2 only).
`TE_BESTWRAP` | Wrap the lines at word boundaries or at any other character if there are words longer than the window width (this is the default).
`TE_CAPITALIZE` | On PocketPC and Smartphone, causes the first letter to be capitalized.

See also window styles overview and TextCtrl.new.

Note that alignment styles (`TE_LEFT`,
`TE_CENTRE` and `TE_RIGHT`) can be changed
dynamically after control creation on MSW and GTK.
`TE_READONLY`, `TE_PASSWORD` and wrapping styles
can be dynamically changed under GTK but not MSW. The other styles can be
only set during control creation.

## TextCtrl text format

The multiline text controls always store the text as a sequence of lines
separated by `\n` characters, i.e. in the Unix text format even
on non-Unix platforms. This allows the user code to ignore the differences
between the platforms but at a price: the indices in the control such as those
returned by get_insertion_point or
get_selection can not be used as
indices into the string returned by get_value as
they’re going to be slightly off for platforms using
`\r\n` as separator (as Windows does), for example.

Instead, if you need to obtain a substring between the two indices obtained
from the control with the help of the functions mentioned above, you should
use get_range. And the indices themselves can
only be passed to other methods, for example
set_insertion_point or
set_selection.

To summarize: never use the indices returned by (multiline) TextCtrl as
indices into the string it contains, but only as arguments to be passed back
to the other TextCtrl methods.

## TextCtrl styles

Multi-line text controls support the styles, i.e. provide a possibility to set
colours and font for individual characters in it (note that under Windows
`TE_RICH` style is required for style support). To use the styles you can
either call set_default_style before
inserting the text or call set_style later to
change the style of the text already in the control (the first solution is
much more efficient).

In either case, if the style doesn’t specify some of the attributes (for
example you only want to set the text colour but without changing the font nor
the text background), the values of the default style will be used for them.
If there is no default style, the attributes of the text control itself are
used.

So the following code correctly describes what it does: the second call
to set_default_style doesn’t change the
text foreground colour (which stays red) while the last one doesn’t change the
background colour (which stays grey):

text.set_default_style( Wx::TextAttr.new(Wx::RED) ) text.append_text(“Red text\n”) text.set_default_style( Wx::TextAttr.new(nil, Wx::LIGHT_GREY) ) text.append_text(“Red on grey text\n”) text.set_default_style( Wx::TextAttr.new(Wx::BLUE) ) text.append_text(“Blue on grey text\n”)

## Constants

The values below are the possible return codes of the
hit_test method:

Wx::TE_HT_UNKNOWN = -2 # this means HitTest() is simply not implemented Wx::TE_HT_BEFORE # either to the left or upper Wx::TE_HT_ON_TEXT # directly on Wx::TE_HT_BELOW # below [the last line] Wx::TE_HT_BEYOND # after [the end of line]

## Event handling

The following commands are processed by default event handlers in
TextCtrl: `Wx::ID_CUT`, `Wx::ID_COPY`, `Wx::ID_PASTE`, `Wx::ID_UNDO`,
`Wx::ID_REDO`. The associated UI update events are also processed
automatically, when the control has the focus.

To process input from a text control, use these event handler methods to
direct the events to a block that takes a CommandEvent
argument.

evt_text(id) { | event | … } | Respond to a EVT_COMMAND_TEXT_UPDATED event,generated when the text changes. Notice that this event will be sentwhen the text controls contents changes – whether this is due to user input orcomes from the program itself (for example, if SetValue() is called); see ChangeValue() fora function which does not send this event.
evt_text_enter(id) { | event | … } | Respond to a EVT_COMMAND_TEXT_ENTER event,generated when enter is pressed in a text control (which must haveTE_PROCESS_ENTER style for this event to be generated).
evt_text_maxlen(id) { | event | … } | User tried to enter more textinto the control than the limit set by set_max_length.

The following event handler works similarly for textctrls created with the
`TE_AUTO_URL` style, but the block will instead receive a
TextUrlEvent with additional information about the
URL.

evt_text_url(id) { | event | … } | A mouse event occurred over an URL in the text control (MSW and GTK2 only)

## Methods

- TextCtrl.new
- TextCtrl#append_text
- TextCtrl#can_copy
- TextCtrl#can_cut
- TextCtrl#can_paste
- TextCtrl#can_redo
- TextCtrl#can_undo
- TextCtrl#clear
- TextCtrl#copy
- TextCtrl#create
- TextCtrl#cut
- TextCtrl#discard_edits
- TextCtrl#emulate_key_press
- TextCtrl#get_default_style
- TextCtrl#get_insertion_point
- TextCtrl#get_last_position
- TextCtrl#get_line_length
- TextCtrl#get_line_text
- TextCtrl#get_number_of_lines
- TextCtrl#get_range
- TextCtrl#get_selection
- TextCtrl#get_string_selection
- TextCtrl#get_style
- TextCtrl#get_value
- TextCtrl#hit_test
- TextCtrl#is_editable
- TextCtrl#is_empty
- TextCtrl#is_modified
- TextCtrl#is_multi_line
- TextCtrl#is_single_line
- TextCtrl#load_file
- TextCtrl#mark_dirty
- TextCtrl#on_drop_files
- TextCtrl#paste
- TextCtrl#position_to_xy
- TextCtrl#redo
- TextCtrl#remove
- TextCtrl#replace
- TextCtrl#save_file
- TextCtrl#set_default_style
- TextCtrl#set_editable
- TextCtrl#set_insertion_point
- TextCtrl#set_insertion_point_end
- TextCtrl#set_max_length
- TextCtrl#set_modified
- TextCtrl#set_selection
- TextCtrl#set_style
- TextCtrl#set_value
- TextCtrl#change_value
- TextCtrl#show_position
- TextCtrl#undo
- TextCtrl#write_text
- TextCtrl#xy_to_position

### TextCtrl.new

TextCtrl.new(%(arg-type)Window% parent, Integer id, String value = "", Point pos = DEFAULT_POSITION, Size size = DEFAULT_SIZE, Integer style = 0, Validator validator = DEFAULT_VALIDATOR, String name = TextCtrlNameStr)

Constructor, creating and showing a text control.

#### Parameters

- parent Parent window. Should not be NULL.
- id Control identifier. A value of -1 denotes a default value.
- value Default text value.
- pos Text control position.
- size Text control size.
- style Window style. See TextCtrl.
- validator Window validator.
- name Window name.

#### Remarks

The horizontal scrollbar (HSCROLL style flag) will only be created
for multi-line text controls.
Without a horizontal scrollbar, text lines that don’t fit in the control’s
size will be wrapped (but no newline character is inserted). Single line
controls don’t have a horizontal scrollbar, the text is automatically scrolled
so that the insertion point is always
visible.

#### See also

TextCtrl#create, Validator

### TextCtrl#append_text

append_text(%(arg-type)String% text)

Appends the text to the end of the text control.

After the text is appended, the insertion point will be at the end of
the text control. If this behaviour is not desired, the programmer
should use get_insertion_point and
set_insertion_point.

Note also that this means that appending text will normally auto-scroll
a multiline TextCtrl to the end. However, the exact scrolling behaviour
may vary by platform and by the presence of styles such as
`Wx::TE_WORDWRAP` and `Wx::TE_RICH`, as different native controls are
being used underneath. Scrolling behaviour can be controlled more
precisely by using methods such as
get_last_position,
show_position, and
scroll_lines after calling append_text. For
displaying a log of, for example, events, ListCtrl may
also be a more suitable alternative.

#### Parameters

- text Text to write to the text control.

#### See also

TextCtrl#write_text

### TextCtrl#can_copy

Boolean can_copy()

Returns `true` if the selection can be copied to the clipboard.

### TextCtrl#can_cut

Boolean can_cut()

Returns `true` if the selection can be cut to the clipboard.

### TextCtrl#can_paste

Boolean can_paste()

Returns `true` if the contents of the clipboard can be pasted into the
text control. On some platforms (Motif, GTK) this is an approximation
and returns `true` if the control is editable, `false` otherwise.

### TextCtrl#can_redo

Boolean can_redo()

Returns `true` if there is a redo facility available and the last operation
can be redone.

### TextCtrl#can_undo

Boolean can_undo()

Returns `true` if there is an undo facility available and the last operation
can be undone.

### TextCtrl#clear

clear()

Clears the text in the control.

Note that this function will generate a `EVT_COMMAND_TEXT_UPDATED`
event.

### TextCtrl#copy

copy()

Copies the selected text to the clipboard under Motif and MS Windows.

### TextCtrl#create

Boolean create(%(arg-type)Window% parent, Integer id, String value = "", Point pos = DEFAULT_POSITION, Size size = DEFAULT_SIZE, Integer style = 0, Validator validator = DEFAULT_VALIDATOR, String name = TextCtrlNameStr)

Creates the text control for two-step construction. Derived classes
should call or replace this function. See TextCtrl.new for further details.

### TextCtrl#cut

cut()

Copies the selected text to the clipboard and removes the selection.

### TextCtrl#discard_edits

discard_edits()

Resets the internal `modified’ flag as if the current edits had been saved.

### TextCtrl#emulate_key_press

Boolean emulate_key_press(%(arg-type)KeyEvent% event)

This functions inserts into the control the character which would have been
inserted if the given key event had occurred in the text control. The
event object should be the same as the one passed to `EVT_KEY_DOWN`
handler previously by Widgets.

Please note that this function doesn’t currently work correctly for all keys
under any platform but MSW.

#### Return value

`true` if the event resulted in a change to the control, `false`
otherwise.

### TextCtrl#get_default_style

TextAttr get_default_style()

Returns the style currently used for the new text.

#### See also

set_default_style

### TextCtrl#get_insertion_point

Integer get_insertion_point()

Returns the insertion point. This is defined as the zero based index of the
character position to the right of the insertion point. For example, if
the insertion point is at the end of the text control, it is equal to
both get_value and
get_last_position.

The following code snippet returns the character at the insertion
point or an empty string if the point is at the end of the control.

if textctrl.get_last_position == textctrl.get_insertion_point return ’’ else

return textctrl.get_value[ textctrl.get_insertion_point, 1]
end

### TextCtrl#get_last_position

TextPos get_last_position()

Returns the zero based index of the last position in the text control,
which is equal to the number of characters in the control.

### TextCtrl#get_line_length

Integer get_line_length(%(arg-type)Integer% line_num)

Gets the length of the specified line, not including any trailing newline
character(s).

#### Parameters

- line_num Line number (starting from zero).

#### Return value

The length of the line, or -1 if line_num was invalid.

### TextCtrl#get_line_text

String get_line_text(%(arg-type)Integer% line_num)

Returns the contents of a given line in the text control, not including
any trailing newline character(s).

#### Parameters

- line_num The line number, starting from zero.

#### Return value

The contents of the line.

### TextCtrl#get_number_of_lines

Integer get_number_of_lines()

Returns the number of lines in the text control buffer.

#### Remarks

Note that even empty text controls have one line (where the insertion point
is), so GetNumberOfLines() never returns $0$.

For GTK using GTK+ 1.2.x and earlier, the number of lines in a multi-line
text control is calculated by actually counting newline characters in the
buffer, i.e. this function returns the number of logical lines and doesn’t
depend on whether any of them are wrapped. For all the other platforms, the
number of physical lines in the control is returned.

Also note that you may wish to avoid using functions that work with line
numbers if you are working with controls that contain large amounts of text as
this function has $O(N)$ complexity for $N$ being the number of lines.

### TextCtrl#get_range

String get_range(%(arg-type)Integer% from, Integer to)

Returns the string containing the text starting in the positions from and
up to to in the control. The positions must have been returned by another
TextCtrl method.

Please note that the positions in a multiline TextCtrl do not
correspond to the indices in the string returned by
get_value because of the different new line
representations (`CR` or `CR LF`) and so this method should be used to
obtain the correct results instead of extracting parts of the entire value. It
may also be more efficient, especially if the control contains a lot of data.

### TextCtrl#get_selection

[ Integer from, Integer to ] = get_selection()

Gets the current selection span and returns the start (`from`) and end
(`to`) points as a two-element array. These two values are integer
offsets within the TextCtrl’s text. If the returned values are equal,
there was no selection.

Note that on some platforms, if the selection was made by click-dragging
from right to left, `from` may be larger than `to`. In other words, you
should not assume that `from` is earlier in the sequence of characters
in the TextCtrl. Using ruby’s `sort` method should correct this.

Please note that the indices returned may be used with the other
Textctrl methods but don’t necessarily represent the correct indices
into the string returned by get_value for
all multiline controls under Windows (at least,)

This problem appears to be avoided if the TextCtrl is created with the
`Wx::TE_RICH2` style, or you can use
get_string_selection to get a string
containing the selected text.

### TextCtrl#get_string_selection

String get_string_selection()

Gets the text currently selected in the control. If there is no selection, the
returned string is empty.

### TextCtrl#get_style

Boolean get_style(%(arg-type)Integer% position, TextAttr style)

Returns the style at this position in the text control. Not all platforms
support this function.

#### Return value

`true` on success, `false` if an error occurred – it may also mean that
the styles are not supported under this platform.

#### See also

TextCtrl#set_style, TextAttr

### TextCtrl#get_value

String get_value()

Gets the contents of the control. Notice that for a multiline text control,
the lines will be separated by (Unix-style) $$n characters, even
under Windows where they are separated by a $$r$$n
sequence in the native control.

### TextCtrl#hit_test

[ Integer result, Integer col, Integer row ] = hit_test(%(arg-type)Point% pt)

This function finds the character at the specified position expressed in
pixels. If the return code is not `TE_HT_UNKNOWN` the row and column
of the character closest to this position are returned in the col and
row arguments.

Please note that this function is currently only implemented in Univ,
MSW and GTK2 ports. It functionality can be faked on OS X.

#### See also

position_to_xy, XYToPosition

### TextCtrl#is_editable

Boolean is_editable()

Returns `true` if the controls contents may be edited by user (note that it
always can be changed by the program), i.e. if the control hasn’t been put in
read-only mode by a previous call to
set_editable.

### TextCtrl#is_empty

Boolean is_empty()

Returns if the control is currently empty. This is the same as
`GetValue().empty()` but can be much more efficient for the multiline
controls containing big amounts of text.

2.7.1

### TextCtrl#is_modified

Boolean is_modified()

Returns `true` if the text has been modified by user. Note that calling
set_value doesn’t make the control modified.

#### See also

mark_dirty

### TextCtrl#is_multi_line

Boolean is_multi_line()

Returns `true` if this is a multi line edit control and `false`
otherwise.

#### See also

is_single_line

### TextCtrl#is_single_line

Boolean is_single_line()

Returns `true` if this is a single line edit control and `false`
otherwise.

#### See also

is_multi_line

### TextCtrl#load_file

Boolean load_file(%(arg-type)String% filename, Integer fileType = TEXT_TYPE_ANY)

Loads and displays the named file, if it exists.

#### Parameters

- filename The filename of the file to load.
- fileType The type of file to load. This is currently ignored in TextCtrl.

#### Return value

`true` if successful, `false` otherwise.

### TextCtrl#mark_dirty

mark_dirty()

Mark text as modified (dirty).

#### See also

is_modified

### TextCtrl#on_drop_files

on_drop_files(%(arg-type)DropFilesEvent% event)

This event handler function implements default drag and drop behaviour, which
is to load the first dropped file into the control.

#### Parameters

- event The drop files event.

#### Remarks

This is not implemented on non-Windows platforms.

#### See also

DropFilesEvent

### TextCtrl#paste

paste()

Pastes text from the clipboard to the text item.

### TextCtrl#position_to_xy

[ Integer x, Integer y ] = position_to_xy(pos)

Converts given position to a zero-based column, line number pair. If the
position requested is less than 0 or greater than the length of the
TextCtrl, the single value `nil` will be returned.

#### Parameters

- pos Position.

#### See also

TextCtrl#xy_to_position

### TextCtrl#redo

redo()

If there is a redo facility and the last operation can be redone, redoes the last operation. Does nothing
if there is no redo facility.

### TextCtrl#remove

remove(%(arg-type)Integer% from, Integer to)

Removes the text starting at the first given position up to (but not including)
the character at the last position.

#### Parameters

- from The first position.
- to The last position.

### TextCtrl#replace

replace(%(arg-type)Integer% from, Integer to, String value)

Replaces the text starting at the first position up to (but not including)
the character at the last position with the given text.

#### Parameters

- from The first position.
- to The last position.
- value The value to replace the existing text with.

### TextCtrl#save_file

Boolean save_file(%(arg-type)String% filename, Integer fileType = TEXT_TYPE_ANY)

Saves the contents of the control in a text file.

#### Parameters

- filename The name of the file in which to save the text.
- fileType The type of file to save. This is currently ignored in TextCtrl.

#### Return value

`true` if the operation was successful, `false` otherwise.

### TextCtrl#set_default_style

Boolean set_default_style(%(arg-type)TextAttr% style)

Changes the default style to use for the new text which is going to be added
to the control using write_text or append_text.

If either of the font, foreground, or background colour is not set in style, the values of the previous default style are used for them. If
the previous default style didn’t set them neither, the global font or colours
of the text control itself are used as fall back.

However if the style parameter is the default TextAttr, then the
default style is just reset (instead of being combined with the new style which
wouldn’t change it at all).

#### Parameters

- style The style for the new text.

#### Return value

`true` on success, `false` if an error occurred – may also mean that
the styles are not supported under this platform.

#### See also

get_default_style

### TextCtrl#set_editable

set_editable(%(arg-type)Boolean% editable)

Makes the text item editable or read-only, overriding the TE_READONLY flag.

#### Parameters

- editable If `true`, the control is editable. If `false`, the control is read-only.

#### See also

is_editable

### TextCtrl#set_insertion_point

set_insertion_point(%(arg-type)Integer% pos)

Sets the insertion point at the given position.

#### Parameters

- pos Position to set.

### TextCtrl#set_insertion_point_end

set_insertion_point_end()

Sets the insertion point at the end of the text control.

### TextCtrl#set_max_length

set_max_length(%(arg-type)Integer% length)

This function sets the maximum number of characters the user can enter into the
control. In other words, it limits the text value length to length.

If length is 0, the previously set max length limit, if any, is discarded
and the user may enter as much text as the underlying native text control
widget supports (typically at least 32Kb).

If the user tries to enter more characters into the text control when it
already is filled up to the maximal length, a
`EVT_COMMAND_TEXT_MAXLEN` event is sent to notify the program about it
(giving it the possibility to show an explanatory message, for example) and the
extra input is discarded.

Note that under GTK+, this function may only be used with single line text controls.

#### Compatibility

Only implemented in MSW/GTK starting with Widgets 2.3.2.

### TextCtrl#set_modified

set_modified(%(arg-type)Boolean% modified)

Marks the control as being modified by the user or not.

#### See also

mark_dirty, discard_edits

### TextCtrl#set_selection

set_selection(%(arg-type)Integer% from, Integer to)

Selects the text starting at the first position up to (but not including) the
character at the last position. If both parameters are equal to -1 all text
in the control is selected.

Note that on Windows, by default, if the TextCtrl does not have focus
the selection is not shown as highlighted. Therefore the results of
calling this method may not be immediately visible. If you wish the
selection always to be shown, create the TextCtrl with the style
`Wx::TE_NOHIDESEL`.

#### Parameters

- from The first position.
- to The last position.

### TextCtrl#set_style

Boolean set_style(%(arg-type)Integer% start, Integer end, TextAttr style)

Changes the style of the given range. If any attribute within style is
not set, the corresponding attribute from get_default_style is used.

#### Parameters

- start The start of the range to change.
- end The end of the range to change.
- style The new style for the range.

#### Return value

`true` on success, `false` if an error occurred – it may also mean that
the styles are not supported under this platform.

#### See also

TextCtrl#get_style, TextAttr

### TextCtrl#set_value

set_value(%(arg-type)String% value)

Sets the text value and marks the control as not-modified (which means that
is_modified would return `false` immediately
after the call to set_value).

Note that this function will generate a `EVT_COMMAND_TEXT_UPDATED`
event.

This function is deprecated and should not be used in new code. Please use the
change_value function instead.

#### Parameters

- value The new value to set. It may contain newline characters if the text control is multi-line.

### TextCtrl#change_value

change_value(%(arg-type)String% value)

Sets the text value and marks the control as not-modified (which means that
is_modified would return `false` immediately
after the call to SetValue).

Note that this function will not generate the `EVT_COMMAND_TEXT_UPDATED`
event.
This is the only difference with set_value.
See this topic for more information.

2.7.1

#### Parameters

- value The new value to set. It may contain newline characters if the text control is multi-line.

### TextCtrl#show_position

show_position(%(arg-type)Integer% pos)

Makes the line containing the given position visible.

#### Parameters

- pos The position that should be visible.

### TextCtrl#undo

undo()

If there is an undo facility and the last operation can be undone,
undoes the last operation. Does nothing if there is no undo facility.

### TextCtrl#write_text

write_text(%(arg-type)String% text)

Writes the text into the text control at the current insertion position.

#### Parameters

- text Text to write to the text control.

#### Remarks

Newlines in the text string
are the only control characters allowed, and they will cause appropriate
line breaks. See TextCtrl:: and TextCtrl#append_text for more convenient ways of writing to the window.

After the write operation, the insertion point will be at the end of the inserted text, so subsequent write operations will be appended. To append text after the user may have interacted with the control, call TextCtrl#set_insertion_point_end before writing.

### TextCtrl#xy_to_position

Integer xy_to_position(%(arg-type)Integer% x, Integer y)

Converts the given zero based column and line number to a position.

#### Parameters

- x The column number.
- y The line number.

#### Return value

The position value, or -1 if `x` or `y` was invalid.

### TextCtrl#<<

TextCtrl << String str TextCtrl << Integer int TextCtrl << Float float

Operator for appending to a text control, for example:

textctrl = Wx::TextCtrl.new(parent, -1, ’’) textctrl << "Welcome to text control number " << 1 << “.\n”

[This page automatically generated from the Textile source at 2023-06-09 00:45:29 +0000]