diff options
| author | Andrew Burgess <aburgess@redhat.com> | 2025-06-17 18:09:49 +0100 |
|---|---|---|
| committer | Andrew Burgess <aburgess@redhat.com> | 2025-10-05 13:48:06 +0100 |
| commit | 3c724596812882cc0c3b653330551fae132d6475 (patch) | |
| tree | 5607b83fa5e5fba0dd3ff4b9b0123bcb990b284b /gdb/python/python.c | |
| parent | d5214580a5f24cb1ca47f095e6d3554cb48eebbe (diff) | |
| download | binutils-3c724596812882cc0c3b653330551fae132d6475.zip binutils-3c724596812882cc0c3b653330551fae132d6475.tar.gz binutils-3c724596812882cc0c3b653330551fae132d6475.tar.bz2 | |
gdb/python: extend gdb.write to support styled output
It is already possible to produce styled output from Python by
converting the gdb.Style to its escape code sequence, and writing that
to the output stream.
But this commit adds an alternative option to the mix by extending the
existing gdb.write() function to accept a 'style' argument. The value
of this argument can be 'None' to indicate no style change should be
performed, this is the default, and matches the existing behaviour.
Or the new 'style' argument can be a gdb.Style object, in which case
the specified style is applied only for the string passed to
gdb.write, after which the default style is re-applied.
Using gdb.write with a style object more closely matches how GDB
handles styling internally, and has the benefit that the user doesn't
need to remember to restore the default style when they are done.
Reviewed-By: Eli Zaretskii <eliz@gnu.org>
Approved-By: Tom Tromey <tom@tromey.com>
Diffstat (limited to 'gdb/python/python.c')
| -rw-r--r-- | gdb/python/python.c | 30 |
1 files changed, 25 insertions, 5 deletions
diff --git a/gdb/python/python.c b/gdb/python/python.c index 740b196..51e7a0a 100644 --- a/gdb/python/python.c +++ b/gdb/python/python.c @@ -1567,12 +1567,22 @@ static PyObject * gdbpy_write (PyObject *self, PyObject *args, PyObject *kw) { const char *arg; - static const char *keywords[] = { "text", "stream", NULL }; + static const char *keywords[] = { "text", "stream", "style", nullptr }; int stream_type = 0; + PyObject *style_obj = Py_None; - if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg, - &stream_type)) - return NULL; + if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|iO", keywords, &arg, + &stream_type, &style_obj)) + return nullptr; + + if (style_obj != Py_None && !gdbpy_is_style (style_obj)) + { + PyErr_Format + (PyExc_TypeError, + _("'style' argument must be gdb.Style or None, not %s."), + Py_TYPE (style_obj)->tp_name); + return nullptr; + } try { @@ -1590,7 +1600,17 @@ gdbpy_write (PyObject *self, PyObject *args, PyObject *kw) break; } - gdb_puts (arg, stream); + if (style_obj == Py_None) + gdb_puts (arg, stream); + else + { + std::optional<ui_file_style> style + = gdbpy_style_object_to_ui_file_style (style_obj); + if (!style.has_value ()) + return nullptr; + + fputs_styled (arg, style.value (), stream); + } } catch (const gdb_exception &except) { |
