GDB index cache for faster debugging

Developing LibreOffice requires debugging. But, with the default settings, it takes a long time to load GDB and use it. Here I discuss GDB index cache to improve the debugging experience with a faster startup.

GDB Debugging

Whether you want to fix a bug or add a feature to LibreOffice, debugging is an essential part of the task. Running LibreOffice in debug mode, going step by step and checking the value of a variable and checking the stack trace and threads is among the thing that developers do in a debug session.

But, if you have ever tried to debug LibreOffice using GDB, you may have noticed the big delay before you can use LibreOffice in a debug session.

To start a debug session, you need to have a working build environment for LibreOffice. Then, invoke:

$ make debugrun

You will see a few things written on the screen, and then gdb prompt. Enter run to run LibreOffice, after setting the VCL plugin to gen, which starts faster:

(gdb) set env SAL_USE_VCLPLUGIN=gen
(gdb) run

It may even take something like 30 seconds or more before you see LibreOffice running. But, there are ways to improve the situation, and GDB index caching is one of them.

To benchmark the required time for startup and shutdown of Writer, you may set OOO_EXIT_POST_STARTUP environment variable to 1:

(gdb) set env SAL_USE_VCLPLUGIN=gen
(gdb) set OOO_EXIT_POST_STARTUP=1
(gdb) run --writer

In this way, LibreOffice exits immediately after startup. Further environment variables are listed in TDF Wiki:

GDB Index Caching

GDB needs to read symbol files to create its internal symbols, and provide symbols while you debug instead of simple memory addresses. That requires scanning of many files, and increases startup time. In order to improve that, GDB can automatically cache symbol indexes for a faster next startups.

Using this feature requires at least GDB 8.3, which is usually true in recent Linux distributions.

Suggested Configuration

This is a suggested configuration file for GDB, which you may store in ~/.config/gdb/gdbinit:

add-auto-load-safe-path ~/core/instdir
add-auto-load-safe-path ~/core/workdir
set print pretty on
set debuginfod enabled off
set index-cache enabled on

It enables index caching, alongside pretty printing, and some related scripts in instdir/ and workdir/, and it disables fetching debug symbols from internet through debuginfod.

Checking the GDB Index Cache Status

To check the status of caching, first start a debug session:

$ make debugrun

Then, invoke this command in the GDB prompt:

show index-cache directory

show index-cache stats

This will show you the cache directory, and the statistics, which will be useful only after a debug session, to asses the number of cache hits and misses.

gdb index cache status
gdb index cache status

You may check the size of the cache:

$ du -hs ~/.cache/gdb/

Please be aware that there is no limit for the size of GDB cache, therefore it may grow over time. You may remove the cache, and it will be re-created after first use, which is a cold start. The next debug sessions will start faster, as the cache is already built.

Final Notes

Debugging is an essential part of LibreOffice development, but it has its own tips and tricks. If you want to get better debugging experience, make sure that you tune your debugging environment and read a few notes for improving your debug session. This is one of the previous posts on debugging LibreOffice:

Debugging tips for LibreOffice

Webview for LibreOffice

While LibreOffice is (mostly) in C++ and uses native GUI toolkit on different platforms, it is still possible to use web technologies with LibreOffice. Here I discuss how.

Webview

Webview is a small web browser widget that is inside an application. There are many ways to use web technologies with LibreOffice. But, using a webview widget like pywebview is probably the easiest way to link a webview with LibreOffice. The idea is to display a web page in a webview widget that Python provides, and link that to LibreOffice via the connection of Python to LibreOffice and the connection of JavaScript in webview to Python, and send UNO commands to interact with LibreOffice via network.

Minimal Example

This is a minimal example to show a minimal web page that contains a text box to write the UNO commands like .uno:Bold, and see it working in LibreOffice:

import uno
import webview


class UnoBridge:
    def __init__(self):
        self.ctx = self.desktop = None

    def connect(self):
        if self.ctx is not None:
            return
        component_ctx = uno.getComponentContext()
        resolver = component_ctx.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", component_ctx)
        self.ctx = resolver.resolve("uno:socket,host=127.0.0.1,port=2083;urp;StarOffice.ComponentContext")
        self.desktop = self.ctx.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", self.ctx)

    def dispatch(self, command):
        self.connect()
        frame = self.desktop.getCurrentFrame()
        dispatch_helper = self.ctx.ServiceManager.createInstanceWithContext("com.sun.star.frame.DispatchHelper", self.ctx)
        dispatch_helper.executeDispatch(frame, command.strip(), "", 0, ())


HTML = r'''<input id=c value=".uno:Bold"><button onclick="pywebview.api.dispatch(c.value)">OK</button>'''

webview.create_window("LibreOffice UNO", html=HTML, js_api=UnoBridge())
webview.start()

To use this example, first you should start LibreOffice and make it listen on the port that is written in the code, 2083:

$ libreoffice26.8 "--accept=socket,host=localhost,port=2083;urp;StarOffice.ServiceManager"

You may open Writer, and write a small text and select it. Then, you can run the Python code. You may use LibreOffice internal Python or external Python with uno package. But, you have to install pywebview package anyway: (the command might be different according to your operating system, etc.)

$ pip install pywebview

Then, by running the Python code you should be able to see a window similar to the below screenshot:

$ python3 webuno.py

You can edit the command and after clicking on “OK”, you should be able to see the result in LibreOffice.

WebUNO
WebUNO: connecting webview to LibreOffice

How the Python Code Works?

The Python code essentially consist of two important functions: connect and dispatch. The connect function uses uno.getComponentContext() to get the component context, and then finds service manager to execute executeDispatch() with the give UNO dispatch command.

You may read more about service manager in LibreOffice DevGuide chapter 1. This is an illustration from the same chapter of DevGuide:

Service Manager
Service Manager

Final Words

A comprehensive list of UNO dispatch commands are available in the Wiki link below:

Please note that some UNO commands work in every LibreOffice application, but there are many that only work inside a specific application like Writer, Calc, etc. Also, many of the UNO commands require parameters, and we don’t pass any parameters to LibreOffice yet, although it is possible to do that in Python.

This approach to use webview can be helpful in extensions, as usual native GUIs created with com.sun.star.awt for extensions are somehow limited and hard to create.

NotebookBar part 2: icons, text and the code

The NotebookBar (NBB) or tabbed interface is an alternative user interface for LibreOffice. In the second part of this series, I explain the way the NotebookBar takes icons and text to create the final output that you see on the screen.

Creating NotebookBar is LibreOffice Code

Currently, the NotebookBar is not exactly like the other UI files that in LibreOffice with weld mechanism. In the first part of the series of blog posts on this topic, I discussed the custom widgets in notebookbars and how to edit them using Glade.

The custom widgets rely on C++ code, especially for sizing and other characteristics. For example, Priority Merged Horizontal Box (sfxlo-PriorityMergedHBox) is a “horizontal box hiding children depending on its priorities”. It needs C++ code to implement the priority display of the children. If you search for it in C++ files, you will reach builder.cxx:

$ git grep -l sfxlo-PriorityMergedHBox "*.cxx"
vcl/source/window/builder.cxx

The above file is a huge > 100 KB C++ source code  that handles NotebookBar custom widgets, but also handles every other VCL widget.

The other parts of the relevant code for the NotebookBar resides in below files. Search for both “Notebookbar” and “notebookbar” in C++ files:

$ git ls-files "*otebook*cxx"
sfx2/source/notebookbar/NotebookbarTabControl.cxx
sfx2/source/notebookbar/SfxNotebookBar.cxx
vcl/qt5/QtInstanceNotebook.cxx
vcl/qt6/QtInstanceNotebook.cxx
vcl/source/control/NotebookbarPopup.cxx
vcl/source/control/notebookbar.cxx
vcl/source/window/NotebookBarAddonsMerger.cxx

Icons in Notebookbar

If you open the NotebookBar UI for LibreOffice Writer or other components like Calc, etc., what you see lacks two important things: icons and text.

Notebookbar widgets
Notebookbar widgets

First, let’s look into icons. The icon files come from the set of icon themes that are available with LibreOffice. The icon theme of LibreOffice is configurable, therefore you do not see some specific LibreOffice icon in the design. That makes the work of UI designers harder, but lets LibreOffice choose among different icon themes.

You may find more information in the icon-themes/ module README.md file, which describes how to create new icon themes, and how to link the icons to specific icons via .xcu files. For example, in officecfg/registry/data/org/openoffice/Office/UI/CalcCommands.xcu you see:

<node oor:name=".uno:OpenFromCalc" oor:op="replace">
    <prop oor:name="Label" oor:type="xs:string">
        <value xml:lang="en-US">~Open...</value>
    </prop>
    <prop oor:name="Properties" oor:type="xs:int">
        <value>1</value>
    </prop>
</node>

This is defined for the UNO dispatch command, .uno:OpenFromCalc, which opens a file for Calc. The complete list of UNO dispatch commands is available here:

For each command, two icon sizes are created, one small and one big icon. lc_<command name>.png and sc_<command name>.png, if not in SVG format. At first, one should add the icons for a new command to the colibre theme, in order to be usable also with other themes.

Here, the filenames will be lc_openfromcalc.png and sc_openfromcalc.png, which are available in the instdir/cache/ folder. In this case, these icon files do not exist in LibreOffice source repository, as they use fallback icons sc_open.png and sc_open.png.

Text in Notebookbar

The text for the commands can be found alongside the other details about the command in the .xcu file. For the UNO dispatch command .uno:OpenFromCalc, you can see the text “~Open…” is used. “~O” is for activating the shortcut “O” for this command, and “…” shows that this command will open a dialog, as a usual convention.

Some other properties of this command are defined in .sdi file scalc.sdi, as shown below:

SfxStringItem OpenFromCalc SID_OPEN_CALC
()
[
    AutoUpdate = FALSE,
    FastCall = FALSE,
    ReadOnlyDoc = TRUE,
    Toggle = FALSE,
    Container = FALSE,
    RecordAbsolute = FALSE,
    RecordPerSet;
    Asynchron;

    AccelConfig = TRUE,
    MenuConfig = TRUE,
    ToolBoxConfig = FALSE,
    GroupId = SfxGroupId::Options;
]

Following the SID_OPEN_CALC symbolic constant in C++ code shows where the implementation resides.

As another example, you may follow .uno:AddDirect, and then SID_NEWDOCDIRECT to find the place where the menu that shows the possible new files is created. This menu becomes visible when you click on the v button on “New Document” in the File section of the notebookbar.

$ git grep -l SID_NEWDOCDIRECT
basctl/sdi/baside.sdi
basctl/source/basicide/basides1.cxx
dbaccess/source/ui/app/AppController.cxx
include/sfx2/sfxsids.hrc
sfx2/sdi/appslots.sdi
sfx2/sdi/frmslots.sdi
sfx2/sdi/sfx.sdi
sfx2/source/appl/appopen.cxx
sfx2/source/view/viewfrm2.cxx
sw/source/uibase/app/apphdl.cxx
sw/source/uibase/utlui/glbltree.cxx

There are both common and application specific C++ files in the above results. I will write more about the details of creating the final “New Document” menu and its menu items, in later posts.

Final Notes

The NotebookBar is a complex part of the LibreOffice user interface. If you want to modify and change it, it is important to understand how to create .ui files for notebookbar, how to use them in the code, and how to display the desired UI elements in notebookbar on the screen.

There are plans to improve the NotebookBar and make it more like other weld UIs. But, that is yet to be implemented:

Validating ODF and OOXML files

In LibreOffice development, there are many cases where you want to validate some documents against standards: either Open Document Format (ODF) or MS Office Open XML (OOXML). Here I discuss how to do that.

Update: Article updated to reflect that odfvalidator 0.13.0 has just released.

Open Document Format (ODF) Validation

ODF is the native document file format that LibreOffice and many other open source applications use. It is basically set of XML files that are zipped together, and can describe various aspects of the document, from the content itself to the way it should be displayed. These XML files have to conform to ODF standard, which is presented in XML schemas. The latest version of ODF is 1.4, which is yet to be implemented in LibreOffice.

You can find more about ODF in these links:

There are various tools to do the validation, but the preferred one is the ODF Toolkit Validator:

Compiled binaries of ODF Toolkit can be downloaded from the above Github project:

Then, you can use the ODF validator this way:

$ java -jar odfvalidator-0.13.0-jar-with-dependencies.jar test.odt

You may also use the online validator, odfvalidator.org, to do a validation.

odfvalidator
Online odfvalidator tool

Please read this disclaimer before using:

This service does not cover all conformance criteria of the OpenDocument Format specification. It is not applicable for formal validation proof. Problems reported by this service only indicate that a document may not conform to the specification. It must not be concluded from errors that are reported that the document does not conform to the specification without further investigation of the error report, and it must not be concluded from the absence of error reports that the OpenDocument Format document conforms to the OpenDocument Format specification.

Office Open XML (OOXML) Validation

MS Office Open XML (OOXML) is the native standard for Microsoft documents format. It is also a set of XML files zipped together, and conform to some XML schemas.

You can find out more about OOXML here:

There are tools to do the validation, and the one is used in LibreOffice is Office-o-tron. One can use it with below command to validate an example file, test.docx:

$ java -jar officeotron-0.8.8.jar ~/test.docx

Office-o-tron can be downloaded from dev-www.libreoffice.org server of LibreOffice, and this is currently the latest version:

It is worth noting that Office-o-tron can be also used to validate ODT files.

Extensions to ODF Standard

To go beyond the current ODF standard, new features are sometimes introduced as “ODF extensions”, then are gradually added to the standard. You can read more in TDF Wiki:

In these cases, you may see validation errors for such extensions. For example:

test.odt/styles.xml[2,3347]: Error: unexpected attribute “loext:tab-stop-distance”
test.odt/styles.xml[2,4849]: Error: unexpected attribute “loext:opacity”

You may avoid such errors by using -e option, which ignores such unknown markups:

-e: Check extended conformance (ODF 1.2 and 1.3 documents only)

If you want to use the latest features from ODF validator, you should build ODF Toolkit from source. You can then run it with this command:

$ java -jar ./validator/target/odfvalidator-0.14.0-SNAPSHOT-jar-with-dependencies.jar test.odt

ODF Toolkit developers have recently (23 January 2026) published the new release 0.13. If you do not build from sources, you can use this new version which contains ODF 1.4 support.

Final Words

When you want to make sure that the ODT or OOXML document you generate is valid according to the standards, then you need validation. Sometimes, it is the opposite: you want to make sure that the input document is valid before processing it, or when you want to know if the problem is from LibreOffice (or other processors), or the document itself. Then, again, the validator is the right tool to use.

Outlook for the new year 2026

Happy new year 2026! I hope that this year will be great for you, and the global LibreOffice community, and the software itself! I hereby discuss the past year 2025, and the outlook for 2026 in the development blog.

At The Document Foundation (TDF), our aim is to improve LibreOffice, the leading free/open source office suite that has millions of users around the world. Our work is community-driven, and the software needs your contribution to become better, and work in a way that you like.

My goal here, is to help people understand LibreOffice code easier via EasyHacks and tutorials, and eventually participate in LibreOffice core development to make LibreOffice better for everyone. In 2025, I wrote 14 posts around LibreOffice development in the dev blog (4 of them are unpublished drafts).

Outlook For the New Year

Focus of the development blog for 2026 in this blog will be:

  • Introducing new EasyHacks
    • Using new C++20 constructs
    • Difficulty Interesting EasyHacks
  • Describing user interface creation with VCL
    • VCL weld mechanism
    • Various weld widgets
  • Describing UNO Components

You can provide feedback simply by leaving a comment here, or sending me an email to hossein AT libreoffice DOT org.

We provide mentoring support to the individuals who want to start LibreOffice development. You are welcome to contact me if you need help to build LibreOffice and do some EasyHacks via the above email address. You may also refer to our Getting Involved Wiki page:

Let’s hope a better year for LibreOffice (and the world) in 2026.

Handling CI build failures

After submitting a patch to LibreOffice Gerrit, one has to wait for the continuous integration (CI) to build and test the changed source code to make sure that the build is OK and the tests pass successfully. Here we discuss the situation when one or more CI builds fail, and how to handle that.

Why Build and Test on CI?

After you submit code to LibreOffice Gerrit, reviewers have to make sure that it builds, and the tests pass with the new source code. But, it is not possible for the reviewers to test the code on each and every platform that LibreOffice supports. Therefore, Jenkins CI does that job of building and testing LibreOffice on various platforms.

This can take a while, usually 1 hour or so, but sometimes can take longer than that. If everything is OK, then your submission will get     Verified +1    .

CI Platforms for LibreOffice

Currently, these are the platforms used in CI:

  • Linux / GCC:  gerrit_linux_gcc_release
  • Linux / Clang: gerrit_linux_clang_dbgutil
  • Android Viewer: gerrit_android_x86_64 and gerrit_android_arm
  • Windows: gerrit_windows_wsl
  • macOS: gerrit_mac

Some of the tests are more extensive, for example Linux / Clang also performs additional code quality checks with clang compiler plugins. Also, UITests are not run on each and every platform.

Jenkins LibreOffice CI
LibreOffice CI uses Jenkins

Why Failures Happen and How to Fix?

There can be multiple reasons for why a CI build fails, and give your submission    Verified -1   . These are some of the reasons, and depending on the reason, solution can be different.

1. Your code’s syntax is wrong and compile fails

In this case, you should fix your code, and then submit a new patch set. You have to wait again for a new CI build.

2. The code’s syntax is OK, but it is not properly formatted

You should refer to the below TDF Wiki article and use clang-format tool to format your code properly.

3. Your code’s syntax is OK, but it logically not OK and fails some tests.

In this case, you should try fixing your code logic, and run the tests that fail and make sure they pass. After that, you may send a new patch set and wait for a new CI build.

4. Your code’s syntax and logic is OK, but some machine fails for other reasons like their disk being full or other software/hardware failures or hiccups

In this case, usually resuming the build can be a good option. You may ask on #libreoffice-dev or #tdf-infra IRC rooms for such a resume, or request access, if you submit many patches.

Resume CI build
Resume build in LibreOffice CI

5. Your code’s syntax and logic is OK, but there are issues from other patches.

In this case, intervention from other LibreOffice developers is needed. Informing people on #libreoffice-dev can help, and then you have to re-base your submission in case new patches fix the build issue.

Final Notes

The best way to know the reason of the build failure is to look into the CI log files. Sometimes it needs more detailed look to understand the issue, but sometimes the reason is easily provided on Gerrit as a comment.

But, in the end your submission should have     Verified +1     before it is suitable for merge in the LibreOffice code. This +1 as verified, does not guarantee that your patch will work as expected, but it is an important requirement.

enumarray for better data arrays – EasyHack

In LibreOffice C++ code, there are many cases where developers want to use string literals in their code. If these are messages in the graphical user interface (GUI), they should add them to the translatable messages. But, there are many cases where the string literals has nothing to do with other languages, and there will not be any further translations. In these cases, enumarray is helpful. Although enumarray can be used beyond string literals, for any kind of data.

Using Symbolic Constants

In old C code, using #define was the preferred way one could give a name to a string literal or other kinds of data. For example, consider this code:

const char[] FRAME_PROPNAME_ASCII_DISPATCHRECORDERSUPPLIER = "DispatchRecorderSupplier";
const char[] FRAME_PROPNAME_ASCII_ISHIDDEN = "IsHidden";
inline constexpr OUString FRAME_PROPNAME_ASCII_LAYOUTMANAGER = "LayoutManager";
const char[] FRAME_PROPNAME_ASCII_TITLE = "Title"_ustr;
const char[] FRAME_PROPNAME_ASCII_INDICATORINTERCEPTION = "IndicatorInterception";
const char[] FRAME_PROPNAME_ASCII_URL = "URL";

And also, the relevant states:

#define FRAME_PROPHANDLE_DISPATCHRECORDERSUPPLIER 0
#define FRAME_PROPHANDLE_ISHIDDEN 1
#define FRAME_PROPHANDLE_LAYOUTMANAGER 2
#define FRAME_PROPHANDLE_TITLE 3
#define FRAME_PROPHANDLE_INDICATORINTERCEPTION 4
#define FRAME_PROPHANDLE_URL 5

Although this C code still works in C++, it is not the desired approach in modern C++.

Using enumarrays

In modern C++ code, you can use enumarry from o3tl library in LibreOffice. The above code becomes:

enum class FramePropNameASCII
{
    DispatcherRecorderSupplier,
    IsHidden,
    LayoutManager,
    Title,
    IndicatorInterception,
    URL,
    LAST=URL
};

And also, the string literal definitions:

constexpr o3tl::enumarray<FramePropNameASCII, OUString> FramePropName = {
    u"DispatchRecorderSupplier"_ustr,
    u"IsHidden"_ustr,
    u"LayoutManager"_ustr,
    u"Title"_ustr,
    u"IndicatorInterception"_ustr,
    u"URL"_ustr
};

Why an enumarray?

The names are much more readable, as they do not have to be ALL_CAPPS, as per convention for symbolic constants in C. Their usage is also quite easy. For example, one can use [] to access the relevant string literal:

- xPropSet->getPropertyValue( FRAME_PROPNAME_ASCII_LAYOUTMANAGER ) >>= xLayoutManager;
+ xPropSet->getPropertyValue( FramePropName[FramePropNameASCII::LayoutManager] ) >>= xLayoutManager;

Final Notes

In LibreOffice, enumarrays are not limited to string literals, and they can be used with other data. This task is tdf#169155, and if you like, you may try finding some instances in the code and modernize it using enumarrays.

To learn more about LibreOffice development, you can refer to the development section of the TDF Wiki. You may follow this blog to read about EasyHacks, tutorials and announcements related to LibreOffice development.

enum class instead of unscoped enum – EasyHack

Since C++11 when enum class (also named scoped enum) is introduced, it is preferred to plain enum which is inherited from C programming languages. The task here is to convert the old enum instances to enum class.

Rationale

enum class has many benefits when compared to plain enum, as it provides better type safety among other things. Implicit conversion to integers, lack of ability to define the underlying data type and compatibility issues were some of the problems with plain enum that enum class solved in C++11. Although since then enum has improved and one can specify underlying type in the scoped enumerations.

Plain enums pollute namespace, and you have to pick names that are too long, and have to carry the context inside their names. For example: INETMSG_RFC822_BEGIN inside enum _ImplINetRFC822MessageHeaderState. With an enum class, it is simply written as HeaderState::BEGIN. When placed inside a file/class/namespace that makes it relevant, it is much easier to use: it is more readable, and causes no issues for other identifiers with possible similar names.,

See this change:

You can read more about that in:

Finding Instances

You may find some of the instances with:

$ git grep -w enum *.cxx *.hxx|grep -v "enum class"

When you count it with wc -l, it shows something more than 2k instances.

Examples Commits

You can see some of the previous conversions here, which is around 1k changes:

$ git log --oneline -i -E --grep="convert enum|scoped enum"

This is a good, but lengthy example of such a conversion:

Implementation

First of all, please choose good names for the new enum class and values. For example, you may convert APPLICATION_WINDOW_TITLE into Application::WindowTitle. Therefore, do not use the old names as they were.

Converting enum to enum class is not always straightforward. You should try to understand the code using the enum, and then try to replace it with enum class. You may need to add extra state/values for situations where 0 or -1 or some default value was used. There are cases where a numerical value is used for different conflicting purposes, and then you have to do some sort of conflict resolution to separate those cases.

You may end up modifying more and more files, and a few static_casts where they are absolutely necessary because you are interpreting some integer value read from input. These are the places where you should check the values yourself in the code. You have to make sure that the numerical value is appropriate before casting it to the enum class.

If you want to do bitwise operations, you should use o3tl::typed_flags, for example:

enum class FileViewFlags
{
    None = 0x00,
    MultiSelection = 0x02,
    ShowType = 0x04,
    ShowNone = 0x20,
};

template<> struct o3tl::typed_flags : o3tl::is_typed_flags<FileViewFlags, 0x26> {}

Then, you may use it like this:

    if (nFlags & FileViewFlags::MULTISELECTION)
        mxTreeView->set_selection_mode(SelectionMode::Multiple);

Please note that 0x26 is the mask, and is calculated by applying OR over all possible values. All the values must be non-negative.

Final Notes

This is a simple development task for LibreOffice also known as EasyHack, which is filed in Bugzilla as tdf#168771. These small tasks are defined to help newcomers to LibreOffice development community to improve their skills with LibreOffice coding.

You may find other instances related to C++ here:

Using C++ STL functions instead of loops – EasyHack

C++ Standard library, which resides in std:: namespace provides common classes and functions which can be used by developers. Among them, Standard Template Library (STL) provides classes and functions to better manage data through data structures named containers. Here I discuss how to use STL functions for better processing of data, and avoid loops.

Checking Conditions

To iterate over a container to see if some specific condition is valid for all, any, or none of the elements in that container, C/C++ developers traditionally used loops.

On the other hand, since C++11, there are functions that can handle such cases: all_of, any_of and none_of. These functions process STL containers, and can replace loops. If you want to know if a function returns true for all, any, or none of the items of the container, then you can simply use these functions. This is the EasyHack dedicated to such a change:

Here is an example patch which uses any_of instead of a loop:

-    bool bFound = false;
     // convert ASCII apostrophe to the typographic one
     const OUString aText( rOrig.indexOf( '\'' ) > -1 ? rOrig.replace('\'', u'’') : rOrig );
-    size_t nCnt = aVec.size();
-    for (size_t i = 0;  !bFound && i < nCnt;  ++i)
-    {
-        if (aVec[i] == aText)
-            bFound = true;
-    }
+    const bool bFound = std::any_of(aVec.begin(), aVec.end(),
+        [&aText](const OUString& n){ return n == aText; });

As you can see, the new code is more concise, and avoids using loops.

Conditional Copying, Removing and Finding

If you want to copy, remove or simply find a value in a container which conforms to a specific functions, you may use copy_if, remove_if or find_if.

Again, this is an example patch:

-  for ( size_t i = 0; i < SAL_N_ELEMENTS( arrOEMCP ); ++i )
-        if ( arrOEMCP[i] == codepage )
-            return true;
-
-    return false;
+    return std::find(std::begin(arrOEMCP), std::end(arrOEMCP), codepage) != std::end(arrOEMCP);

Final Words

Refactoring code is a good way to improve knowledge on LibreOffice development. The above EasyHacks are among EasyHacks that everyone can try.

More information about EasyHacks, and how to start working on them can be found on TDF Wiki: