Discover libreOffice 2020: Become a LibreOffice Expert

Explore the free office suite used by busy professionals around the world! https://www.linux-magazine.com/Resources/Spe

828 162 11MB

English Pages [100] Year 2020

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Discover libreOffice 2020: Become a LibreOffice Expert

Citation preview

FREE DVD! LibreOffice Full Version

Become a LibreOffice Expert! 2020 Edition

LibreOffice Dive deep into the world’s greatest free office suite Write Your Own LO Macros Save time and automate common tasks

Digital Signatures Lock down your private documents

Edit and Save MS Office Files Create Professional: QText Documents QSpreadsheets QPresentations QDatabases

Replace MS Office and Google Docs! Includes full versions for Windows, macOS, and Linux WWW.LINUX- MAGAZINE.COM

EDITORIAL Welcome

2  I´FH(QJLQH The brilliant and highly motivated developers of the open source community have created an amazing menagerie of free tools for doing things that computer users around the world used to have to pay for: video editors, photo processors, web browsers, and development platforms. The centerpiece of this ambitious collection is the versatile LibreOffice office suite – an enterprise-ready toolset for composing and managing word-processing documents, databases, spreadsheets, presentations, and much more. LibreOffice runs on Windows, macOS, and Linux, and, if you don’t already have it, you can download it for free or install it from the DVD attached to this issue. The LibreOffice user interface is very intuitive, and most users just see the edges of it. They start it up and learn what they need to know for a few common tasks. But there is so much more! If you’re ready to explore the possibilities, get productive, and dial up the quality of your documents, this single-volume special edition will serve as your guide! Read on for tutorials on all the core tools of the LibreOffice suite: Writer, Calc, Impress, Draw, Base, and Math. You’ll also find insightful articles on working with LibreOffice extensions, templates, and macros, as well as bonus articles on advanced layout, migration, digital signatures, and XML scripting. If you’re new to LibreOffice, or if you are ready to take your LibreOffice skills to another level of power and efficiency, look inside!

LIBREOFFICE SPECIAL – 2020 EDITION

3

LIBREOFFICE SPECIAL

LibreOffice Dive deep into the world’s greatest free office suite

Get Started 8 Introducing LibreOffice Why pay for an office productivity suite? LibreOffice is totally free, and it runs on Windows, macOS, and Linux. 14 LibreOffice Writer Writer, LibreOffice’s word-processor component, is more than just a text editor. With its powerful styles system, you can build detailed and elegant documents for business and personal use. 20 LibreOffice Calc LibreOffice Calc offers the functionality of Excel with added benefits.

Service 3 Welcome 6 DVD 98 Masthead 4

28 LibreOffice Impress Need to impress your boss with the latest sales stats? Or just show off some holiday photos in an eye-catching format? Impress is the tool you need. 34 LibreOffice Draw With LibreOffice Draw, you can create attractive and informative vector-based drawings. 40 LibreOffice Base We show you how to set up a database in LibreOffice Base and search it with SQL queries embedded in forms. 46 LibreOffice Math The LibreOffice Math package lets you display simple and complex formulas.

LIBREOFFICE SPECIAL – 2020 EDITION

LIBREOFFICE SPECIAL

Get Productive 50 Open Document Format The Open Document Format standard is an important reason for the success of LibreOffice.

66 LibreOffice Typography LibreOffice Writer is a serviceable desktop publisher with more typography features than most users imagine.

53 LibreOffice Extensions You can extend the power of LibreOffice with over 350 useful extensions.

70 Digital Signatures By adding a digital signature, you can boost your document’s security.

56 LibreOffice Templates LibreOffice templates can save you time ZLWKIRUPDWWLQJ\RXUGRFXPHQWVVR¢\RX can focus on the important stuff.

74 ODF XML You may have heard that LibreOffice files “are XML-based” or “use XML,” but when you try to open a Writer document in a text editor, you only see a binary blob. Learn how to access and modify the hidden XML content using scripts.

60 LibreOffice Macros LibreOffice packs a built-in Basic-like scripting language that can be used to automate repetitive tasks and extend the suite’s default functionality.

82 Hidden Gems of LibreOffice Discover some hidden and lesser known LibreOffice features.

Community 88 LibreOffice Community Who makes LibreOffice? How does everyone work together? And what are they working on? Here’s an update on what’s happening in the global LibreOffice community.

92 Get Involved Join the LibreOffice community and help to improve the software. You don’t need to be a programmer; there are lots of ways to dive in and build your skills!

LiEreOI´ce 7.0.2 IQVtaOOatiRQ ´OeV IRr Linux, Windows, and macOS Lots of extras inside! ■ Clip Art ■ Extensions ■ Handbooks ■ Templates ■ Videos

LIBREOFFICE SPECIAL – 2020 EDITION

5

SERVICE On the DVD

On the DVD LIBREOFFICE INSTALLATION FILES The DVD attached to this issue includes installation files for setting up the full version of LibreOffice on the following systems: Q 64-bit Windows Q 32-bit Windows Q 64-bit macOS Q 64-bit Linux for deb systems Q 64-bit Linux for RPM systems Installation packages for the latest version are included in separate files/directories. Consult the documentation for your package manager or see “Introducing LibreOffice” on page 8 of this issue for more on installing LibreOffice.

LOTS MORE! As an extra bonus, this DVD also includes a collection of other valuable resources to help you extend and learn about LibreOffice. Look inside for: Q Handbooks – the complete set of LibreOffice Handbooks with hundreds of pages of help and reference in PDF format Q Extensions – the top 20 LibreOffice extensions available online, including several language dictionaries, spellcheckers, icon and gallery collections, and a barcode generator Q Templates – 100+ ready-made presentation templates covering all kinds of presentation situations Q Clip Art – an Openclipart library containing thousands of clip art graphics for any occasion Q Videos – Take a video tour of new LibreOffice features, and learn about the LibreOffice project and personal success stories from top project leaders and volunteers

Defective discs will be replaced. Please send an email to [email protected] Although this Linux Magazine disc has been tested and is to the best of our knowledge free of malicious software and defects, Linux Magazine cannot be held responsible, and is not liable for any disruption, loss, or damage to data and computer systems related to the use of this disc.

6

LIBREOFFICE 7.0.2 DOWNLOAD LINK https://www.libreoffice.org/download/ download/?version=7.0.2

LIBREOFFICE SPECIAL – 2020 EDITION

GET STARTED ,QWURGXFLQJ/LEUH2I´FH

:KDWLV/LEUH2I´FHDQGKRZGR,LQVWDOOLW"

Introducing LiEreOI´ce Why pay for an office productivity suite? LibreOffice is totally free, and it runs RQ¢:LQGRZVPDF26DQG/LQX[

A

complete, feature-rich office suite, compatible with Microsoft documents, and totally free – such a thing can’t really exist, right? There must be a catch somewhere! Well, no. There’s no catch. No hidden costs. Nothing to be suspicious about. LibreOffice [1] is indeed a complete suite of office tools, for zero cost, and it doesn’t make money through adverts or selling your data.

Figure 1:+HUH­V:ULWHUWKHZRUGSURFHVVRU¡

8

The reason it is free is simple: It’s made by a worldwide community, driven by volunteers, who are passionate about high-quality productivity software that’s free for everyone to use. LibreOffice’s goal is to bridge “digital divides,” making powerful tools available to everyone, regardless of their income, location, or language. Indeed, LibreOffice’s user interface has been translated into over 100 languages, making the software usable for many people in countries where other software vendors don’t have a presence. Now, that’s not to say that all LibreOffice developers work on the software for purely philanthropic reasons. There are many “certified developers” [2] who have customers using LibreOffice (such as companies or local government departments) and are paid to provide support packages, fix bugs, and implement new features. LibreOffice itself is (and will always be) completely free, but it still supports a viable commercial ecosystem around it. If LibreOffice really is totally free (yes!) and compatible with Microsoft Office (indeed!), then why hasn’t the whole world moved

LIBREOFFICE SPECIAL – 2020 EDITION

/HDG,PDJH&&8QLYHUVDO3XEOLF'RPDLQ'HGLFDWLRQ

By Mike Saunders

GET STARTED ,QWURGXFLQJ/LEUH2I´FH over to it? Why is MS Office still around? There are various reasons for this, such as: Q Familiarity: Lots of people still aren’t aware that LibreOffice exists. The Document Foundation, the nonprofit entity behind it, is working to improve this through marketing and events, but more needs to be done to spread the word. Q Resistance to change: Even when people discover LibreOffice, they’re often reticent to change, especially if they’ve already paid for another office suite. LibreOffice is familiar but looks and works slightly differently in places, and some more conservative users aren’t in a rush to switch over. Q Features: LibreOffice has the vast majority of features that everyday users need, and indeed even more than MS Office in some areas [3]. But some specific workflows designed for MS Office require macros or special feature sets that don’t quite match up with LibreOffice. Still, with new LibreOffice releases arriving every six months, this changes quickly, and LibreOffice often takes the lead with rolling out new features that haven’t appeared in MS Office yet. The LibreOffice suite includes several tools, including: Q Writer – the word processor (Figure 1) Q Calc – the spreadsheet (Figure 2) Q Impress – the presentation tool (Figure 3) Q Draw – for diagrams, flowcharts, leaflets, etc. (Figure 4) Q Base – for databases (Figure 5) Q Math – to create formulae Over the next few pages, I’ll provide a bit more background on LibreOffice and the community behind it, and I’ll show you how to install it. If you’re really itching to begin, skip ahead to the installation section – but don’t forget to come back here later and discover more about the suite! By learning about its history and background, you can help advocate for LibreOffice and spread the word to other potential users.

the origins of what is today called LibreOffice, you have to go back to the 1980s, to a program called StarWriter

(Figure 6). StarWriter was a commercial word processing application, created by German programmer Marco

Figure 2:¡ZKLOHWKLVLV&DOFWKHVSUHDGVKHHWWRRO

Figure 3:/LEUH2IILFHLQFOXGHVDSUHVHQWDWLRQSURJUDPFDOOHG,PSUHVV

$48,&.+,6725< LibreOffice came to life in 2010, but its history actually goes back many years before that. Indeed, to explore

Figure 4:'UDZFDQEHXVHGIRUGLDJUDPVIORZFKDUWVDQGOHDIOHWV

LIBREOFFICE SPECIAL – 2020 EDITION

9

GET STARTED ,QWURGXFLQJ/LEUH2I´FH

Figure 5:%DVHLV/LEUH2IILFH­VGDWDEDVHIURQWHQG

impressive $73.5 million. The reasoning behind this? Many speculated that for Sun, which had over 20,000 employees at the time, buying Star Division was a cheaper way of equipping all its workers with an office suite than buying MS Office licenses. Others speculate that Sun was eager to get more involved in the home/personal computing space. In any case, this suddenly meant that StarOffice had a much bigger company behind it – more resources and developers were available to work on it. In 2000, Sun released StarOffice 5.2 as a free download for personal use; the suite was also provided on many magazine cover discs. Microsoft suddenly had a lot more competition, and many people found StarOffice more than good enough for their daily tasks. Then another major change occurred. The Free and Open Source Software movement was gaining a lot of traction at the time, promoting the benefits of software for which the source code (the humanreadable recipe) is freely available. With open source programs, anyone can tinker “under Figure 6:6WDU:ULWHULVWKHDQFHVWRURIPRGHUQ/LEUH2IILFH the hood,” make LPDJH0DVWHUKLW&&% cdot

Two gray boxes with a dot appear in the preview (Figure 1). When you replace the placeholders in the command area () with numbers or variables such as x and y, they appear in the preview instead of the gray squares. The first placeholder in the Commands pane is already selected after you insert the new formula, and you can overwrite it by entering your character. Press F4 to go to the next placeholder and Shift+F4 to move back to the previous one. By default, Math updates the formula automatically, but you can deactivate the feature with View | AutoUpdate Display and update everything manually by pressing F9. Clicking View | Toolbars | Tools adds to the toolbar icons that enlarge and reduce the view with a mouse click or fill the window optimally. The second

Figure 2: The Symbols dialog lets you insert Greek letters into your formulas.

LIBREOFFICE SPECIAL – 2020 EDITION

47

GETTING STARTED LibreOffice Math

Figure 4: The size of brackets can adapt to the enclosed formula.

perthousand. Selecting the equals-hat sign from the field of characters above changes this value to Ux2259 (the “corresponds to” Unicode designation). The Symbol set field contains the name of the collection in which the edited symbol resides, in this case Special. To add the equals-hat character to this collection, click Add. Alternatively, you can enter your own choice of name in the Symbol set field to create a new collection.

BRACKETED

Figure 3: The Edit Symbols dialog lets you add existing symbols to a symbol set or create new symbol sets with often-used special characters.

new ones that you often need in formulas. The tools required for this can be found when you click the Edit button. If, for example, you want to add the special character for “corresponds to” (an equals sign with a hat) to the Special symbol set, select Special from

the drop-down menu at the top and click Edit to call the Edit Symbols dialog (Figure 3). Note the five drop-down menus below the displayed character set. The Symbol field contains the name of the character to edit, which was originally

Fences (parentheses, brackets, braces, vertical lines) are indispensable for building formulas. In the left sidebar they have their own entry, Brackets, in the drop-down. LibreOffice Math distinguishes between: Q Group Brackets. They enclose related expressions but do not appear in the formula. Q Braces. If you type curly brackets in the Commands pane from the keyboard, Math will understand them as Group Brackets. Instead, clicking the curly brackets icon in the Braces drop-down enters lbrace and rbrace in the Commands window and a set

Figure 5: The upper formula, typed into the Commands window as a long line, has no structure. The same formula created with spaces and wraps make it much more manageable. The results (right) are the same.

48

LIBREOFFICE SPECIAL – 2020 EDITION

GETTING STARTED LibreOffice Math ditional hints appear, such as Unexpected character. Explanatory comments that only appear in the Commands pane and not in the document are useful, especially in long and complicated formulas. A comment starts with double percent signs (%%). Comments run to the end of a line, so to end a comment, press Enter. Some symbols (e.g., #, %, ^, &, _, |) have special meanings in Math. If they need to appear in the formula in the document, you have to use double quotes around the characters in the Commands pane.

LAST BUT NOT LEAST

Figure 6: When printing formulas, you can tweak all kinds of settings in the Print dialog.

of curly brackets in the preview window. Q Round Brackets and Square Brackets. These have organizing properties just like the Group Brackets, but Math displays them in the preview formula. Fences usually appear in pairs. If you enter an opening round or square bracket in the command window, the formula editor automatically adds the closing bracket. If you want to use a single parentheses without its partner, however, place a backslash (\) in front of the character. Math then interprets it as a symbol instead of a fence. All types of brackets are available in a scalable form, as well. They dwell in the section just below the unscaled bracket choices. Scalable brackets automatically appear at the required size (Figure 4) and appear with left or right before the character in the command window. The command for the formula in Figure 4 is therefore: left( (a + b) over c + d right) = e

You also can enter scalable brackets individually. Use the keyword none to suppress the second parentheses: left lbrace right none

The preview prints a large left curly bracket only and informs Math that the right side is meant to be missing.

MORE STRUCTURE! Group Brackets give structure to formulas, but spaces and line breaks inserted by pressing Enter have no influence on the layout. Math simply ignores them, which means you can structure long and complicated formulas in the Commands pane with spaces and line breaks to make them easier to read without affecting the presentation in the preview. Figure 5 shows a matrix formula in the upper Commands pane that appears as a long line. The bottom Commands pane shows a far clearer version of the same formula with breaks and spaces, and it produces the same results in the document (right). While creating complicated and long formulas, it is easy to mistype. If you accidentally insert a syntax error somewhere, LibreOffice Math will notify you. An inverted, dark red question mark in the preview pane indicates that something is wrong. Double-click on the question mark to go directly to the matching position in the Commands pane. Press F3 to go to the next error or Shift+F3 to go to the previous error. At the bottom of the window, ad-

If you decide to print a formula, LibreOffice offers some practical options in the LibreOffice Math tab of the Print dialog. For example, you can activate the Title checkbox to print the file name at the top. If you check Formula text, the program prints the contents of the Commands pane. Optionally, you can use borders and print the formula at the original size, fit to the page, or otherwise scaled. A preview shows how the results will print (Figure 6). If you created your formula directly in the Math module, you can save it as a separate object with the *.odf (Open Document Formula) extension by selecting File | Save as. If you have embedded a formula object in Writer or Calc, you can save the formula together with the text or spreadsheet document, or you can export it as a separate object. To export it, right-click the formula and select Save Copy As from the context menu. Conversely, you can load a finished formula file into a LibreOffice file with Insert | Object | Formula. You will now see the Math formula editor again; select Tools | Import Formula to import the desired file, which you can then change or accept without modification. As soon as you click on the text or table document in the upper area, LibreOffice closes the Math window. Q Q Q

INFO [1] Math manual: https://documentation. libreoffice.org/assets/ Uploads/Documentation/en/ GS5.2/PDF/GS5209GettingStartedWithMath.pdf

LIBREOFFICE SPECIAL – 2020 EDITION

49

GET PRODUCTIVE Open Document Format

Open standards keep documents compatible across different applications and versions

Keep It Open The Open Document Format standard is an important reason

T

he Open Document Format (ODF) is the native format used for LibreOffice word processing files, spreadsheets, charts, and presentations. ODF is an open format developed as a standard for office applications. ODF was released by a Technical Committee (TC) at the Organization for the Advancement of Struc-

tured Information Standards (OASIS) consortium in 2005 and approved as an ISO/IEC International Standard in 2006 as ISO/IEC 26300:2006. At the time ODF was developed, the most popular format for office documents was the MS Office format set. At the time, the MS formats were closed and proprietary, yet these formats were so common that they became a pseudo-standard for saving, sharing, and transmitting document files. (See the box entitled “Standards and Pseudo-Standards.”) The widespread use of these proprietary file formats increased Microsoft’s power over the market, allowing them to dominate and eliminate competitors. Open Document Format evolved from the XML specification for the OpenOffice.org office suite, a forerunner to LibreOffice. The OpenOffice developers wanted a free and open office format that could compete with Microsoft’s file formats. Since then, ODF has become popular throughout the world as a free alternative for storing and transmitting document data. Legal issues, and competition from other tools, eventually caused Microsoft to bring more openness to their once-hidden formats. The Microsoft Office Open XML format (OOXML or MOX) is open enough to see and write programs with, but Microsoft continues to maintain some control over the standard. Open Document Format, on the other hand, is independent of LibreOffice or any other software project. The open standard process means that ODF is now supported by dozens of other office tools in addition to LibreOffice.

WHAT IS IT? A document format describes the structure for data saved in a document file. The data inside a modern office doc consists of much more than letters and numbers. The document must store information on fonts, character tags, paragraph tags, and pagination, as well as headers and footers, footnotes, tables of contents, and revision tracking. The format also records information on document encryption, digital signatures, and macros. In addition, the format must be resilient, because each file will be read and edited multiple times by different applications, including applications that

50

LIBREOFFICE SPECIAL – 2020 EDITION

Lead Image © Igor Zakharevich, 123RF.com

for the success of LibreOffice. By Italo Vignoli and Joe Casad

GET PRODUCTIVE Open Document Format TABLE 1: ODF File Types and Extensions

STANDARDS AND PSEUDO-STANDARDS

File Type Text Spreadsheet Presentation Drawing Chart Formula Image Database

When software is forced to adapt its format to a dominant product that is not based on open standards, the dominant vendor can use this power position to influence the market. Often the dominant product becomes a de facto, pseudo-standard that has never been vetted or approved but is merely adopted by the market out of necessity. Any flaws in the dominant product are then echoed out to the whole industry. For instance, the 40-year-old “leap year bug,” which was inherited from VisiCalc and Lotus 1-2-3 and passed to Excel, causes the market-lead-

Extension .odt .ods .odp .odg .odc .odf .odi .odb

were not involved in creating it. At the end of the process, the file must preserve its integrity and characteristics, and – most importantly – guarantee that contents are preserved independently from the application. ODF is not a single format but a collection of formats for the various file types needed in an office productivity suite. See Table 1 for a list of ODF file types and file extensions.

A SHORT HISTORY OF ODF The first meeting to discuss the ODF standard was held on December 16,

2002. ODF 1.0 specifications were published on May 1, 2005 and then submitted to ISO/IEC Joint Technical Committee 1 (JTC1) on November 16, 2005 under a Publicly Available Specification (PAS). After a six-month review period, on May 3, 2006, OpenDocument unani-

ing spreadsheet to incorrectly represent the year 1900 as a leap year, which can cause errors for applications that count days or measure time ranges. Developers of other office suites had to replicate the bug for compatibility. According to the vendor, the faulty state has to be maintained, even across new releases of the product, because fixing it would cause too many problems. So, users are encouraged to keep the faulty spreadsheets, because the vendor protects its commercial interests in spite of the needs of users who have paid for a software license. mously passed its six-month Draft International Standard (DIS) ballot in JTC1 (ISO/IEC JTC1/SC34), with broad participation, and was “approved for release as an ISO and IEC International Standard” under the name ISO/IEC 26300:2006. ODF 1.2, approved as ISO/IEC 26300:2015

GET PRODUCTIVE Open Document Format adopting ODF in the public sphere, and other governments are exploring ODF as well.

ODF FUTURE

Figure 1: To view the contents of an ODF file, give the file name a .zip extension and open it with a ZIP archive tool.

on June 17, 2015, adds accessibility features, RDF-based metadata, a spreadsheet formula description based on OpenFormula, support for digital signatures, and some features suggested by the public. Open Document Format 1.3 was approved as an OASIS committee specification on Janary 21, 2020, thus opening the way to future implementation of an ODF 1.3 standard, which will include improvements to document security.

rity checks than older binary and pseudo-standard formats. Because of its advantages, ODF has been selected by several governments as the standard for document exchange within the public administration. The United Kingdom, the Netherlands, France, Sweden, and Taiwan are leading with

In a world where most documents are exchanged in digital format, an open standard should be a priority in schools and all educational institutions. Governments need to take a more proactive role in promoting open standards in education and the public sphere. Free software organizations are doing as much as they can to fill the gap, but the cause of open standards requires active advocacy. The Document Foundation has re-launched the ODF Adoption Technical Committee (Figure 2), with the support of other Free Software Foundation projects, companies, and public administrations. Continued investment in open standards will help protect users and developers from the security, interoperability, and efficiency problems associated with closed formats. Q Q Q

INSIDE ODF An ODF file is typically stored and distributed in a ZIP container, which includes several XML files and the associated binary content, such as images or other media. Each ODF file contains four key embedded XML files: manifest. xml, the table of contents for the ZIP container; meta.xml, with documentlevel metadata; styles.xml, with style definitions for the document; and content.xml, with all the document’s structured content. ODF provides a flexible container that can embed almost any existing digital object and allow it to be used in an office document. If you want to see what an ODF file really looks like, start with a LibreOffice Writer document and change the .odt extension at the end of the file name to .zip. Then use a ZIP archive tool to look inside the container (Figure 1).

ODF ADVANTAGES The open XML format used with ODF means that software vendors can develop applications that are interoperable by design. Open XML-based formats like ODF also allow stricter secu-

52

Figure 2: The OASIS ODF Technical Committee provides information for organizations that are considering adopting ODF-based tools.

LIBREOFFICE SPECIAL – 2020 EDITION

GET PRODUCTIVE /LEUH2I´FH([WHQVLRQV

([WHQGLQJWKHIXQFWLRQDOLW\RI/LEUH2I´FH

Customizing LiEreOf´ce

You can extend the power of LibreOffice with over 350 useful extensions. By Bruce Byfield

Photo by The Creative Exchange on Unsplash

E

xtensions are unofficial add-ons to the basic LibreOffice office suite. Some make extra resources available, such as images for the Gallery or dictionaries for different languages. Others offer alternative dialog windows with additional features or different layouts, such as an alternative spellchecker or grammar checker. A few even offer new features that will eventually become part of the standard installation. Just as with Mozilla Firefox or Gimp, extensions are a major reason for LibreOffice’s popularity. Today, over 350 extensions exist. Some extensions are a collection of resources, such as replacement icons. Others are macros written in LibreOffice’s Basic scripting language or in standard programming languages such as Java – and, increasingly these days, Python. This versatility means that developers can begin to contribute to LibreOffice without familiarizing themselves with the codebase. A finished extension is a standalone piece of code that is plugged into the basic code when it is installed.

FINDING EXTENSIONS LibreOffice maintains a separate website for both templates and extensions [1]. Developers can create an account on the site for uploading their work, while users can use the site to scan for extensions and to see brief descriptions, licensing information, and screenshots of extensions. With over 350 ex-

tensions – plus many updates – finding an extension may take a while, but along the right pane of every page are links for viewing the most recent extensions, as well as for browsing by categories.

INSTALLING EXTENSIONS All LibreOffice extensions’ file names end with OXT. Regardless of whether they are resources or programs, the procedure for installing them is the same: 1. Download the extension to your system. 2. Click on Tools | Extension Manager | Add and navigate to the download (Figure 1). 3. Select the extension and click Open. If the extension is already on your system, you are asked whether you want to overwrite it. Click OK to continue. 4. A confirmation dialog asks whether you want to install the extension for all users on the system, or only for yourself. To install for all users, you must be able to log in as root. Choose one of these two options. 5. You may be asked to accept the license. Read and scroll down to the end of the license and click to accept it. 6. Click the Options button in the Extension Manager and customize the extension. Not all extensions will have options. 7. Close and restart LibreOffice, and the extension is ready for use.

LIBREOFFICE SPECIAL – 2020 EDITION

53

GET PRODUCTIVE /LEUH2I´FH([WHQVLRQV You may have to search to find the extension in the editing window. Resources such as dictionaries are likely to be in Tools | Language, while Gallery images will be visible in Insert | Media | Gallery. Other languages may be somewhere in the menus, often at the bottom of the Tools menu. Others may be in the toolbars, especially on the left side. There is no standard place to put extensions, and many extension developers do not mention where to find the installed extension, so you sometimes need to be inventive in your search.

A VARIETY OF EXTENSIONS Over the years, extensions have become the preferred way to install spelling and hyphenation dictionaries. Of these, the majority are for Writer and Calc, the most widely used LibreOffice modules. Unless specified, most extensions will work on any operating system that LibreOffice supports. The most interesting are those that add or extend functionality. While there are too many to detail, the most generally useful extensions are discussed below.

ALTERNATIVE DIALOG FIND & REPLACE This extension replaces the standard Find and Replace dialog in the Edit menu. It adds the ability to search in countless new ways, including Bookmarks, Notes, Cross-References, Pictures and Text Frames. For those who have endured the default Find and Replace function, an especially important addition is the ability to search by Character Styles, rather than design features. In addition, built-in regular expressions make advanced searches easy even for beginners. Users can also search for multiple paragraphs and run multiple searches at the same time. The Alternative Find & Replace dialogue may take a while to master, but don’t let the primitive-looking dropdown lists fool you: it’s an extension that is long overdue for becoming a default tool. The longer the documents you write, the more you will appreciate it (Figure 2).

CODE HIGHLIGHTER LibreOffice Writer is not most people’s first choice as a programming tool. It has far too many features to distract

54

Figure 1: The Extension Manager is used for adding, deleting, disabling, and modifying extensions.

you, and you need to be sure that you save in Text format. However, some users may include code snippets in articles, manuals, or whitepapers. Code Highlighter simplifies the task by placing a drop-down list in the Tools menu for highlighting code according to dozens of conventions (Figure 3).

COPY ONLY VISIBLE CELLS In Calc spreadsheets, you can hide rows or columns, but if you copy them, you also copy the hidden ones. With Copy Only Visible Cells, only the visible cells are copied, saving some extra steps after you paste.

MULTIFORMATSAVE-DRAW MultiFormatSave-Draw replaces an earlier extension called simply MultiFormatSave, which lacked support for the Draw module. It is useful because, in a Microsoft-dominated world, you often need to make multiple copies of the same file in a different format. OpenDocument Format (ODF, LibreOffice’s format), traditional and modern Microsoft Office formats, and PDF are supported, with each format created in the same directory. You will find the extension when you go to save a document (Figure 5).

EXPORT AS IMAGES Both Draw and Impress include multiple pages or styles. This extension produces images of the pages in JPG, PNG, GIF, BMP or TIFF formats in one action. It is especially useful if you want to post slides online after giving a presentation (Figure 4).

Figure 2: The Alternative Dialog Find & Replace greatly enhances LibreOffice’s default search capacities.

LIBREOFFICE SPECIAL – 2020 EDITION

GET PRODUCTIVE /LEUH2I´FH([WHQVLRQV

Figure 3: The Code Highlighter extension is useful for formatting code as it would appear in IDEs.

REVIEW TOOLBAR The Review toolbar does not add any new features. However, it does make editing easier by collecting useful features in a single toolbar, such as those for tracking changes, inserting comments, and numbering and highlighting lines. With the Review toolbar, all these tools are a single click away.

its major advantage is that it allows easy formatting in all the major bibliographical styles.

CAUTIONARY NOTES

These examples should give you some sense of the variety of features that are available. Start browsing through the available extensions, and you can frequently find tools that you never realized you needed before. ZOTERO LIBREOFFICE For users, extensions are a simple INTEGRATION way to customize LibreOffice and to Writer’s Bibliography tool is badly outadd useful features. However, you dated and clumsy to use. This extenshould remember that there are hunsion lets you replace the standard tool dreds of extensions, and they are not with Zotero, a web-based tool. Perhaps reviewed systematically. As a result, while resources like dictionaries or gallery images are unlikely to do more harm than fill up your hard drive, other extensions are more of an unknown. You can use the thumbs up or thumbs down rating as a rough guide to an extension’s reliability, but ultimately this does not tell you about any problems. Similarly, there is no way to tell what happens when extensions are used Figure 4: Export as Images converts Draw and Impress together, especially slides to images.

when they affect the same functions. Using multiple extensions is like taking multiple prescription drugs – there is no way to be certain how one extension might interact with others in advance. Also, with LibreOffice in constant development, an extension that works with one release may not work with another. Unfortunately, while each page has a tab to list compatibility, not all developers use it – and, in any event, the only way to be sure whether an extension works is to install it. If it does not work, you can subscribe to the RSS feed on the official site to be informed when a new version is released. To their credit, many developers do make an effort to update their extensions. However, data loss is extremely unlikely, although you should constantly save and backup to be absolutely safe. Probably, too, problems are less likely if you only download from LibreOffices’s official extension site. But if you do run into problems, you should be able to delete misbehaving extensions with nothing worse than the loss of a favorite add-on or resource. The point is, do not let worries about unexpected behavior scare you away from using extensions. Take a few basic precautions, and using extensions can greatly improve your LibreOffice experience. The worst that is likely to happen is that you waste a little time downloading and checking out an extension before you remove it from your system. Q Q Q

Figure 5: MultiformatSave-Draw saves dozens of keystrokes when you need the same file in more than one format.

INFO [1] LibreOffice extensions: https:// extensions.libreoffice.org/

LIBREOFFICE SPECIAL – 2020 EDITION

55

GET PRODUCTIVE /LEUH2I´FH7HPSODWHV

Document formatting made easy

Model Document LibreOffice templates can save you time with formatting your GRFXPHQWVVR¢\RXFDQIRFXVRQWKHLPSRUWDQWVWXIIBy Bruce Byfield

HOW TEMPLATES WORK Unlike Microsoft Word, LibreOffice does not display a default template anywhere in its menus. This omission eliminates the possibility of a document being corrupted by too much editing of the default template.

56

The only way that you can alter LibreOffice’s default formats without using templates is to change the font settings in Tools | Options | LibreOffice Writer | Basic Fonts (Western). Default formatting, such as page and list styles, cannot be edited globally, only individually. However, you can also design a template with far more formatting information as a default. Its settings will be used for every document when you select File | New, unless you specifically select another template. Note that there is a distinction in LibreOffice documentation between the default template (the one built into LibreOffice) and the Default template (the one you select to use for every document). The default can be the Default, but it still exists when another template becomes Default. If the Default is deleted, the built-in default is used instead.

PLANNING AND NAMING TEMPLATES Many resist using templates on the grounds that each of their documents is unique. However, this claim is more a failure of imagination than anything else. If nothing else, almost everyone has design preferences. For instance, it may be a favorite font or, perhaps, corporate colors. Put these preferences into your default template, and you can get to work at once without setting the format each time. Your default template can also be the basis of other documents. If you are unsure what other templates you might want to create, consider what sorts of documents you are constantly creating, whether they are memos, letters, or essays. To jog your memory, have a look in Files | Recent Documents. Check what files you attach to emails. If all else fails, make a note of the documents you produce over several weeks. The

LIBREOFFICE SPECIAL – 2020 EDITION

Lead Image © dvarg, 123rf.com

F

ormatting documents is time-consuming. Even if you use styles, formatting can still take a lot of effort – effort that can be better spent developing content. In addition, if more than one person is working on a series of documents, you do not want everyone to do their own formatting with inevitably inconsistent results. The solution to both these problems is templates – special files for storing both structure and content for easy reuse. Used with styles, a well-designed template can save time and remain useful for years. LibreOffice handles templates differently from other documents. To start with, you can tell a template from another LibreOffice file, because the second letter of its extension is always a t. For example, a Writer template has an .ott extension rather than the usual .odt, while one for Impress has an .otp extension instead of the usual .odp. More importantly, to work within LibreOffice, a template must be registered – that is, saved in such a way that it is recognized as a template. Templates also have their own menus and menu items that are separate from those used by other files. These unique tools are designed to prevent the file corruption that used to be common in Microsoft Word and, in the pursuit of stability, place limitations on how you can interact with templates that can only be circumvented with some difficulty.

GET PRODUCTIVE /LEUH2I´FH7HPSODWHV effort you make now will be useful for years, and save you countless hours. As you produce your template library, make the template names as descriptive as possible. A descriptive title will make your templates easier to find. A descriptive name also prevents naming conflicts when you transfer the template to another computer. Instead of labelling a template article.ott, call it something more specific, such as Linux-Pro-Magazine.ott. You will be glad that you took the time to plan intelligently.

WAYS TO GET TEMPLATES The easiest way to get templates is to download them. Several hundred LibreOffice templates are available online [1], and you are sure to find other download sites. The disadvantage of downloading, though, is that it takes time to sort through the available selections, and the differences between items are not always immediately apparent. Probably, too, you will want to modify the downloads to suit your own needs and preferences, so downloads may not be as convenient as you originally think. Microsoft Office templates, which exist in the thousands online, are another useful source. However, test how these templates display in LibreOffice before using them. You may also want to check the licensing for any downloaded templates. Technically, using templates available from Microsoft Office outside of Microsoft Office is illegal, which probably means that you want to avoid using them for professional purposes. A more convenient source is available via File | Wizards. Since their creation can be interactive, the wizards can teach you how to think as you design.

The disadvantage of this source is that the wizards offer only a limited selection of templates, and many are more elaborate than necessary, even if they are perfectly usable. Sooner or later, though, you will probably need to design one for yourself. Whether you are modifying a downloaded template or creating one from scratch, go about the task just as you would creating any document. Besides the formatting, you might also want to include some content. A brief note at the start of the template might explain how to use it. You might also want to include a boilerplate – content that doesn’t vary between documents, such as a biography or a corporate backgrounder. If you know the type of information needed in a certain place on the template, but not the specific details, you add a placeholder via Insert | Fields | More Fields… | Functions | Placeholder. Other fields, such as Document Information or the general user information stored in Tools | Options | LibreOffice | User Data can also be added to a template, just like any other document (Figure 1). Some of these fields, such as Date and Time, can be fixed, inserting the time when the field was inserted, or variable, displaying the time when the document was opened. The differences from a normal document only start to appear as you save your results.

REGISTERING TEMPLATES Once a regular file is saved, it is ready for use. By comparison, regardless of how a template was created, it must be registered with LibreOffice before being

used, just like a data source, such as an address book or a database. You can, of course, save a template from the ordinary file dialog. However, to make a template available on your system, you must save it for the first time using File | Templates | Save as Template (Figure 2). When the dialog opens, type a name and select a category to file the template under. These categories correspond to the display filters in the Template Manager (see below). You also have the option to set the template as the default, the one that is used automatically when you open a LibreOffice file unless overridden. If you choose not to assign a category, the template displays on the top level of the Template Manager. Registering must be done one template at a time from the editing window. If you have downloaded a large number of templates, you can register them by using a file manager to drop them in one of the directories listed in the Paths section of Tools | Options or by using the Import tool in the Template Manager.

WORKING WITH TEMPLATES To manage templates, or to start a new document based on a template, select File | New | Templates. You can also manage templates from File | Templates | Open Templates… or Manage Templates. In each case, the Template Manager window opens (Figure 3). The Template Manager presents a virtual view of all the templates in the template

Figure 1: Placeholders and fields are useful for storing structure in a template, even if

Figure 2: Templates must be saved in their own dialog before you can use

you lack detailed information.

them.

LIBREOFFICE SPECIAL – 2020 EDITION

57

GET PRODUCTIVE /LEUH2I´FH7HPSODWHV

Figure 3: Once a template is registered, the Template Manager is the place to open, edit, relocate, or delete it.

paths listed in Tools | Options | Paths. By default, that means the templates in your home directory, although the path might also include a template repository available to all users on the system. Across the top of the Template Manager are three ways of locating registered templates: a search field, a LibreOffice module filter, and a category filter. Across the bottom of the window are tools for managing the view of the editing window and for importing and exporting files. To work with a particular template, right-click on it. From the right-click menu, you can start a new document based on the selected template, set the selected template as the default for its LibreOffice Module, or open the template to edit. If you are editing, you can use the regular File | Save dialog, since the template is already registered. You cannot delete templates installed with LibreOffice through an extension or for the entire system, although you can delete the extension from Tools | Extension Manager. However, templates made from the editing window can be deleted – but be careful, because the Template Manager does not include confirmation dialogs. From within the Template Manager, select the template to delete, and then click the Delete button.

58

CIRCUMVENTING TEMPLATE LIMITATIONS For years, Microsoft Word was notorious for allowing more than one template to be applied to a document. Too often, the result was unrecoverable file corruption. When StarOffice, LibreOffice’s first ancestor, was written, mixing templates was made impossible to avoid such problems. The only trouble is, users still need a convenient way to alter templates and the files associated with them. The most convenient way to alter a template and the documents based on it is to edit the template by right-clicking on it in the Template Manager. After you have saved the revised template, the next time you open an associated file, you are given the opportunity to upgrade it (Figure 4). If you upgrade, the association between the template and the document continues, and further changes to the template will trigger the upgrade dialog. However, if you do not upgrade the document, its link with the template is severed – although, somewhat confusedly, the template

continues to be listed in File | Properties | General. You sometimes find an extension that is supposed to allow you to change templates, but, like all extensions, you use such tools at your own risk. Considering the problems that have existed in Microsoft Word for decades, you are probably safest avoiding such tools. One way to reattach a document to a template is to open a new document using the template and then copy and paste the unattached file into it. Be careful, though, to use Paste and not Paste Special. In some circumstances, a possible solution may be to design a new template, carefully using the same style names, and then overwrite the original template name. The new template will be treated as a revision of the original, so associated files can be updated when each one is opened. A temporary solution is to use a Master Document. In the past, Master Documents were used to divided long files into divisions small enough to work with limited memory. Today, they are still used to allow more than one person to simultaneously work on a document. However, what matters here is that a Master Document can use a different template than any of its component files – even if only one file is involved. To take advantage of this feature, start a new document using the revised template and then select File | Send | Master Document. Then open the Master Document. From the right-click menu, select Insert | File to add the document from the file manager, and select Update | All to apply the Master Document’s formatting to it. Close the Master Document without saving, and you will still be able to open the document in its original format. Should you decide to keep the Master Document’s format, select Edit from the right-click menu to open the document in an editing window, from which you can save it using the Master Document’s template.

Figure 4: After you edit a template, files based upon it must be updated.

LIBREOFFICE SPECIAL – 2020 EDITION

GET PRODUCTIVE /LEUH2I´FH7HPSODWHV The idea of trusting your files to a Master Document may sound alarming if you are familiar with past versions of Microsoft Word, whose Master Documents were widely said to be in one of two conditions: corrupted and about to be corrupted. But Writer Master Documents are more robust, and, while they sometimes crash, they should not destroy their component files. Still, just to be safe, make sure that you have a current backup. If you do not mind ignoring or losing the connection between a document and its template, you can partly reformat using Edit | Paste Special | Unformatted Text on a selection of text from another document. With this command, text in the original formatting is inserted using the formatting of the paragraph or character style in which it is

placed. However, objects like images or tables are dropped and will have to be copied and pasted individually using Edit | Paste. Similarly, you can import styles from another document using Styles and Formatting | Load Styles. This choice allows you to select both the files and the categories of styles to upload: Text (paragraph and characters), Numbering, Frame, and Pages. For fullest effect, use imported styles with the same names as those in the files and select the Overwrite box (Figure 5)

BEST PRACTICES Although you can circumvent the restrictions on templates if necessary, remember that the restrictions are designed to preserve your documents from harm. Generally, the following tac-

tics should help you to use templates efficiently and without any difficulties: Q Avoid detaching documents from their templates whenever possible. Try not to detach the document unless it is only going to be used once, and its maintenance is unimportant. Q Change the formatting only on the template. Q Make all formatting changes on the template. Then apply the revised template to the document. Q Apply changes to a document as soon as they are made in the template. That way, you will not have to remember what changed, or wonder if you made an accidental change the next time that you open the document. It can take several hours to design a template. Probably, you will want to make some tweaks after working with the template a time or two. However, once a template does what you want, it can save you hours and remain useful for years. Discipline yourself and work with the template system rather than opting for short-term convenience, and templates can be one of your most valuable tools in LibreOffice. Q Q Q

INFO

Figure 5: Loading styles from a template gives the effect of switching templates without actually doing so.

[1] LibreOffice templates and extensions for downloading: https://www.libreoffice.org/ discover/templates-andextensions/ QQQ

LIBREOFFICE SPECIAL – 2020 EDITION

59

GET PRODUCTIVE /LEUH2I´FH0DFURV

$XWRPDWLQJ/LEUH2I´FHZLWKPDFURV

Of´ce Automation LibreOffice packs a built-in Basic-like scripting language that can be used to automate repetitive tasks and extend the suite’s default functionality. By Dmitri Popov

I

n skilled hands, the LibreOffice Basic scripting language can do wonders, but you don’t have to be a programming expert to write simple, or even more advanced, macros that perform useful tasks. Whether you are a Linux home user or an IT specialist, you can use the built-in scripting powers of the LibreOffice suite to automate recurring tasks. This article provides some examples you can use as building blocks for your own LibreOffice coding projects.

ond parameter is how you want the program to be opened (e.g., full-screen; minimized, maximized, or hidden program window; with and without focus, etc.). For the record, xdg-open is the now most common way to call the user’s preferred application for a given file type or URL. For example, running xdg-open http://

LOOKING UP WORDS The LibreOffice Basic macro editor is reachable through Tools | Macros | Edit Macros (Figure 1). Traditionally, an introduction to a programming language starts with a simple example that displays the “Hello world!” message. Although it’s cute, it’s not particularly useful, so instead, I’ll start with something more practical: a simple macro to look up the currently selected word in Wikipedia. The key element of the macro is the built-in Shell function [1], which is used to call external programs. For example, you can use the following code to open the default browser on your machine: Sub Main Shell ("xdg-open", 1) End Sub

The Shell function requires the name of the program to run (you might need to add the path if the application is not in a location included in Bash’s $PATH environment variable). The sec-

60

Figure 1:7KH/LEUH2IILFHPDFURHGLWRU

LIBREOFFICE SPECIAL – 2020 EDITION

/HDG,PDJH‹,RDQQLV.RXQDGHDV)RWROLDFRP

opens http:// in the user’s preferred web browser.

GET PRODUCTIVE /LEUH2I´FH0DFURV Once you have the script on your machine, you can make it executable with chmod +x aws

before moving it to the /usr/bin directory. The next step is to create a new text file and enter your Access Key ID on the first line and the Secret Access Key on the second line. Now save the file as .awssecret in your home directory and use the aws mkdir command to create a new bucket for use with LibreOffice: aws mkdir lobackup

At this point, you can start working on the backup macro. The macro first obtains the currently active document and then checks to see whether it has already been saved. The latter is required to retrieve the path to the document: ThisDoc=ThisComponent

Figure 2:$VVLJQLQJPDFURVWRNH\ERDUGVKRUWFXWVOHWV\RXUXQWKHPZKHQHYHU\RXZDQW

If ThisDoc.hasLocation=False Then MsgBox (U

If you want the macro to open a certain URL in the default browser, you can feed the URL to the shell command in a third parameter: Sub Main Shell ("xdg-open", 1,

U

"http://en.wikipedia.org/")

Function pane and click the Modify button to assign it. In the example shown in Figure 2, I assigned Lookup to the Shift+F10 shortcut. Now, every time I press Shift+F10, I can look up the word under the cursor in the currently opened LibreOffice document.

"Attention!"U ) :End End If

Next, the macro saves all unsaved changes in the document: ThisDocURL=ThisDoc.getURL()

End Sub

BACK UP With a few simple tweaks, you can turn the code above into a lookup macro (Listing 1). First, you need to add code that obtains the currently selected word (lines 2-3) and then modify the Shell command so it points to Wikipedia’s query URL followed by the selected word (line 4). To assign a keyboard shortcut to the created macro, choose Tools | Macros | Organize Macros | LibreOffice Basic. In the dialog that opens, click the Assign button. A new Customize dialog will pop up (Figure 2). Click the Keyboard tab and choose a shortcut with an empty slot from the Shortcut Keys section. To find the Lookup function you just wrote, look under LibreOffice Macros in the Category pane at the bottom of the dialog, and then highlight the macro in the

"Save the document first!", 16,U

Amazon S3 [2] offers unlimited storage at unbeatable prices, so it’s a perfect service for off-site backup. With the use of a little bit of LibreOffice Basic magic and the aws Perl script, you can seamlessly back up the currently opened document to Amazon S3. Before you start, you must sign up for Amazon S3 and download the latest version of the aws script from the project’s GitHub repository [3].

If ThisDoc.isModified Then ThisDoc.storeAsURL(ThisDocURL, Args) End If

To construct a command that uploads the currently opened document, the macro needs to obtain two things: the document’s path and name: DocPath=U ConvertFromURL(ThisDoc.getURL()) FileName=Dir(ThisDoc.getURL, 0)

/LVWLQJ: :RUG/RRNXS0DFUR 01 Sub Lookup() 02 ThisDoc=ThisComponent 03 LookupWord=ThisDoc.CurrentController.getViewCursor 04 Shell ("xdg-open",1, "http://en.wikipedia.org/wiki/" & LookupWord.String) 05 End Sub

LIBREOFFICE SPECIAL – 2020 EDITION

61

GET PRODUCTIVE /LEUH2I´FH0DFURV LISTING 2: $PD]RQ6%DFNXS0DFUR 01 Sub AmazonS3Backup()

To upload a file to Amazon S3, you can use the aws put command, which has the format:

02 Dim Args(0) As New com.sun.star.beans.PropertyValue aws put BUCKET_NAME/foo.txt.bak

03 ThisDoc=ThisComponent 04 If ThisDoc.hasLocation=False Then 05

MsgBox ("You have to save to document first!", 16, "Attention!") :End

06 End If 07 ThisDocURL=ThisDoc.getURL() 08 If ThisDoc.isModified Then 09

ThisDoc.storeAsURL(ThisDocURL, Args)

10 End If

U

/path/to/foo.txt

To construct the command that uploads the current LibreOffice document, the macro simply inserts the obtained DocPath value in a string, which is then passed to the shell routine: PutCommand="lobackup/" & FileName &

11 DocPath=ConvertFromURL(ThisDoc.getURL()) 12 FileName=Dir(ThisDoc.getURL, 0)

U

" " & DocPath Shell("aws put", 1, PutCommand)

13 PutCommand="lobackup/" & FileName & " " & DocPath 14 Shell("aws put ", 1, PutCommand) 15 End Sub

LISTING 3: 7LPHVWDPSLQJD)LOH1DPH 01 Timestamp=Format(Year(Now), "0000") &_ 02 Format(Month(Now), "00") &_ 03 Format(Day(Now), "00") & "-" &_ 04 Format(Hour(Time), "00") &_ 05 Format(Minute(Time), "00") &_ 06 Format(Second(Time), "00")

That’s all there is to it. You can see the entire macro in all its beauty in Listing 2. Although the backup macro does the job, a few features can still be improved. For example, the name of the bucket is specified directly in the macro, which makes it less flexible. If you plan to use different buckets for different types of LibreOffice documents, you might want to tweak the macro so it uses the InputBox() routine to display an input box where you enter the name of the target bucket:

07 BucketName=InputBox("Enter bucket name", "Bucket name") 08 PutCommand=BucketName & "/" & Timestamp & "-" & FileName & " " & DocPath

LISTING 4: 6KRUWHQLQJD85/ 01 Sub ShortenSelectedURL() 02 ThisDoc=ThisComponent 03 ThisText=ThisDoc.Text 04 SelectedURL=ThisDoc.CurrentController.getViewCursor 05 LongURL = SelectedURL.String 06 If LongURL="" Then 07

MsgBox("Select URL first.", 16, "Error!"):End

"Enter bucket name", "Bucket name") PutCommand=BucketName & "/" &

U

FileName & " " & DocPath

If you want to keep multiple backup copies of the current document, you can modify the macro so it attaches a timestamp to the file name (Listing 3). The code generates a timestamp in the yyymmdd-hhmmss format and prefixes it to the file name.

08 End If

SHORTENING URLS

09 FileNum=FreeFile

Working with long URLs in Writer documents can be a real nuisance. One way to fix this problem is to use shortened URLs. However, instead of manually converting long URLs with their short equivalents, you can write a macro that does this donkey job for you (Listing 4). To perform the URL-shortening operation, the macro relies on the is.gd service, which offers a simple HTTP-based API for converting links. The macro first grabs the currently selected text fragment containing a long URL and turns it into a string. A simple conditional statement

10 Open "http://is.gd/api.php?longurl=" & LongURL for Input As #FileNum 11 While not EOF(FileNum) 12

Line Input #FileNum, SingleLine

13

If SingleLine "" Then

14

StringBuffer=SingleLine

15

End If

16 Wend 17 Close FileNum 18 ShortURL=StringBuffer 19 ThisText.insertString(SelectedURL, ShortURL, True) 20 End Sub

62

BucketName=InputBox(U

LIBREOFFICE SPECIAL – 2020 EDITION

GET PRODUCTIVE /LEUH2I´FH0DFURV then checks whether a selection has been made, and it displays an error message and aborts if the selection is empty. To obtain the shortened URL returned by the is.gd API call, the macro uses a simple trick: It opens a file for input and feeds the obtained result into it. The macro then reads the first line in the file and assigns its value to the StringBuffer variable, which is then assigned to the ShortURL variable (lines 9-18). Finally, the macro replaces the selected long link with the shortened URL that it obtained.

0$5.'2:1)250$77,1* Markdown is a lightweight format popular with developers and users alike,

and it is supported by several Linux text editors. However, what if you use LibreOffice Writer as your preferred writing tool? Although the document processor doesn’t support the Markdown format, you can easily create a LibreOffice Basic macro that converts Writer documents to Markdown-formatted text files. The macro in Listing 5 can handle headings, bold, italics, and URLs. To perform the formatting operation, the macro relies on three functions: The MarkupHeadingsFunc function processes headings in the currently opened document, MarkupTextFunc searches by text attributes (i.e., bold and italics) and performs replacements, and MarkupURLFunc finds and formats hyperlinks in the document.

The macro itself can be roughly divided into two parts. The first part processes the text body of the document and applies Markdown tags to headings, formatted text, and URLs. The second part obtains the file name and path of the currently processed document and saves it as plain text with the .md file extension. Thanks to its modular structure, you can easily adapt the macro for use with other markup formats: All you have to do is replace the start and end tags in the main part of the macro and adjust the MarkupURLFunc function (lines 5367). For example, if you want the macro to apply HTML formatting, the relevant parts (lines 4-8, 63) of the macro and the function should look like the code in Listing 6.

LISTING 5: 0DUNGRZQ)RUPDWWLQJ0DFUR 01 Sub Markdown()

33

02 Dim Args(0) As New com.sun.star.beans.PropertyValue

34

03 ThisDoc=ThisComponent

35 Wend

04 MarkupHeadingsFunc("Heading 1", "#", "")

36 End Function

05 MarkupHeadingsFunc("Heading 2", "##", "")

37

06 MarkupHeadingsFunc("Heading 3", "###", "")

38 Function MarkupTextFunc 39 Dim SearchAttributes(0) As New com.sun.star.beans.PropertyValue

08 MarkupTextFunc("CharPosture", com.sun.star.awt. FontSlant.ITALIC, "*&*")

Wend

(SearchAttrName, SearchAttrValue, ReplaceStr)

07 MarkupTextFunc("CharWeight", com.sun.star.awt. FontWeight.BOLD, "**&**")

End if

40 ThisDoc=ThisComponent

09 MarkupURLFunc

41 SearchAttributes(0).Name=SearchAttrName

10 If (Not GlobalScope.BasicLibraries.

42 SearchAttributes(0).Value=SearchAttrValue

isLibraryLoaded("Tools")) Then 11

43 ReplaceObj=ThisDoc.createReplaceDescriptor

GlobalScope.BasicLibraries.LoadLibrary("Tools")

44 ReplaceObj.SearchRegularExpression=true

12 End If

45 ReplaceObj.searchStyles=false

13 DocURL=ThisDoc.getURL()

46 ReplaceObj.searchAll=true

14 DocDir=DirectoryNameoutofPath(DocURL, "/")

47 ReplaceObj.SetSearchAttributes(SearchAttributes)

15 FileName=Left(Dir(DocURL, 0), Len(Dir(DocURL, 0))-4)

48 ReplaceObj.SearchString=".*"

16 Args(0).Name="FilterName"

49 ReplaceObj.ReplaceString=ReplaceStr

17 Args(0).Value="Text"

50 ThisDoc.replaceAll(ReplaceObj)

18 TextFilePath=ConvertToURL(DocDir & "/" & FileName &

51 End Function

".md")

52

19 ThisDoc.StoreToURL(TextFilePath, Args())

53 Sub MarkupURLFunc

20 End Sub

54 ThisDoc=ThisComponent

21

55 ThisText=ThisDoc.Text

22 Function MarkupHeadingsFunc (StyleName, StartTag, EndTag)

56 ParaEnum=ThisText.createEnumeration 57 While ParaEnum.hasmoreElements

23 ThisDoc=ThisComponent

58

24 ThisText=ThisDoc.Text

59

PortionEnum=Para.createEnumeration

25 ParaEnum=ThisText.createEnumeration

60

While PortionEnum.hasMoreElements

26 While ParaEnum.hasmoreElements

61

Portion=PortionEnum.nextElement

27

62

Para=ParaEnum.nextElement

28

PortionEnum=Para.createEnumeration

29

While PortionEnum.hasMoreElements

30

Portion=PortionEnum.nextElement

31 32

Para=ParaEnum.nextElement

If Portion.HyperlinkURL "" then

63

Portion.String = "[" + Portion.String +"] (" + Portion.HyperlinkURL + ")"

64

If Portion.paraStyleName = StyleName then

65

End if Wend

66 Wend

Portion.String = StartTag + Portion.String + EndTag

67 End Sub

LIBREOFFICE SPECIAL – 2020 EDITION

63

GET PRODUCTIVE /LEUH2I´FH0DFURV BASE DATABASES The Base application lets you build rather advanced databases for storing all kinds of data, and LibreOffice Basic macros can help you integrate databases with other LibreOffice applications. To see how this works in practice, I’ll create a simple Base database for storing text

snippets and then create a macro that saves text selections from the current Writer document in the database. The first order of business is to create a Base database that has a single snippets table comprising two fields: id (an INTEGER field that acts as the primary key), and snippet (a VARCHAR

LISTING 6: +70/)RUPDWWLQJ ... 04 MarkupHeadingsFunc("Heading 1", "", "") 05 MarkupHeadingsFunc("Heading 2", "", "") 06 MarkupHeadingsFunc("Heading 3", "", "") 07 MarkupTextFunc("CharWeight", com.sun.star.awt.FontWeight.BOLD, "&") 08 MarkupTextFunc("CharPosture", com.sun.star.awt.FontSlant.ITALIC, "&") ... 63

Portion.String = "" + Portion.String + ""

...

LISTING 7: 'DWDEDVH7DEOH0DFUR 01 Sub InsertSnippet() 02 Dim Library As Object 03 ThisDoc=ThisComponent 04 TextSnippet=ThisDoc.getCurrentController().getSelection().getByIndex(0). getString() 05 Database=ConnectToDatabase("snippets") 06 TextSnippetSanitized = Join(Split(TextSnippet, "'"), "''")

text field for storing text snippets). When creating the database, tick the Yes, register the database for me checkbox to register the database as a data source in LibreOffice. Once the database is ready to go, you can start working on the macro (Listing 7). To establish a connection to the database, the macro uses the ConnectToDatabase function (line 5). This approach is more flexible because it allows you to establish a connection from any other macro when needed. The function (lines 16-30) includes a simple error-handling mechanism (line 19) that aborts the macro and displays an error message when the macro fails to establish a connection to the database (lines 28-29). The macro itself performs several actions. First, it initializes the current document and obtains the selection. It then establishes a connection to the database registered in LibreOffice under the snippets name. Next, the macro uses the Join() and Split() routines to sanitize the text selection by properly escaping the single quote (') characters, which is necessary to produce valid SQL queries. The macro then constructs an SQL query that inserts the text snippet into the snippets table.

07 SQLQuery="INSERT INTO ""snippets"" " + "(""snippet"") VALUES "_

FINAL WORD

08 + "('" + TextSnippetSanitized + "')" 09 SQLStatement=Database.createStatement 10 Result=SQLStatement.executeQuery (SQLQuery) 11 Database.close 12 Database.dispose() 13 MsgBox ("Text snippet has been saved.", 64, "Result") 14 End Sub 15 16 Function ConnectToDatabase(DBName As String) As Object 17 Dim DatabaseOpt(0) as new com.sun.star.beans.PropertyValue 18 DBContext=createUnoService("com.sun.star.sdb.DatabaseContext") 19 On Error GoTo ErrHndl 20 DataSource=DBContext.getByName(DBName)

These examples are just a few of the things you can do using LibreOffice Basic. Even these relatively simple macros have several building blocks you can easily reuse in your own scripts. Of course, the coding fun doesn’t have to stop here. Although LibreOffice Basic is not as flexible and powerful as many other popular programming languages, it can handle practically any LibreOfficerelated task you throw at it. So once you’ve mastered its basics, you can unleash the full potential of the LibreOffice productivity suite. QQQ

21 ConnectToDatabase=DataSource.GetConnection ("","")

INFO

22 DatabaseFile = DataSource.DatabaseDocument 23 DatabasePath = DatabaseFile.URL 24 DatabaseOpt(0).Name = "Hidden" 25 DatabaseOpt(0).Value = True 26 DatabaseFile = StarDesktop.loadComponentFromURL(DatabasePath, "_blank", 0, DatabaseOpt()) 27 Exit Function

[2] Amazon S3: https://aws.amazon.com/s3/

28

ErrHndl:

29

MsgBox("Failed to establish a database connection.", 16, "Error"):End

30 End Function

64

[1] /LEUH2IILFH6KHOOIXQFWLRQ https://help.libreoffice.org/ 7.0/en-US/text/sbasic/ shared/03130500.html

LIBREOFFICE SPECIAL – 2020 EDITION

[3] $:63HUOVFULSWRQ*LW+XE https://github.com/timkay/aws

GET PRODUCTIVE /LEUH2I´FH7\SRJUDSK\

6HWWLQJW\SHLQ/LEUH2I´FH:ULWHU

Typecast

LibreOffice Writer is a serviceable desktop publisher with more typography features than most users imagine. By Bruce Byfield

66

on, you can simply select Same content left/right and Same content on first page, and your header is set up. If you want more control, you can give the header separate margins from the mfain text (Left margin and Right margin); adjust the space between the bottom of the heading and the main text, making it fixed (Spacing) or variable (Use dynamic spacing); or make the height of the header

Figure 1:$OPRVWHYHU\DVSHFWRIKHDGHUVLQ:ULWHUFDQEH FXVWRPL]HG

LIBREOFFICE SPECIAL – 2020 EDITION

/HDG,PDJH‹3D]0DGULGPRUJXHILOHFRP

Y

ears ago, Elizabeth Mathias, an employee of Sun Microsystems, told me a story about StarOffice, the proprietary program that became OpenOffice.org, and later LibreOffice and Apache OpenOffice. According to Mathias, when the Writer module was first developed several decades ago, its programmers were told they would have to use it to document their work. As a result, they made sure that Writer was not simply a word processor, but a layout program as well – to the benefit of free software users everywhere. In fact, although not complete, Writer’s features are advanced enough that it should hardly be considered a word processor at all. Admittedly, the features of Writer often go unnoticed. If you format manually, you might be completely unaware of them. Even if you use styles, you might not have noticed them fully. For most purposes, the average user hardly cares about the length of the line that separates the main body of text and a footnote or the spacing between a bullet and a list item. Most of the time, you can trust the code to have a default that is, if not perfect, at least good enough for your purposes. However, if you want to enhance your document, the tools are waiting. Take, for example, the tools for setting up a header in a page style (Figure 1). Once a header is turned

GET PRODUCTIVE /LEUH2I´FH7\SRJUDSK\ fixed (Height) or variable (Autofit height) as well. What’s more, that is just the first tab. Click the More button, and you can surround the header with a border or separate it from the main text with a signal line, while setting the style, thickness, and color, as well as the distance between the border or box and the header’s contents. You can even customize a shadow to add a 3D effect, although I wouldn’t recommend that feature unless you want a retro 1990s look (Figure 2). And so it goes for every feature available in Writer. Page margins, tables, text wraps, tables of contents, and superscript and subscript letters – almost every aspect has as much degree of choice as you can imagine. At times, you might need some ingenuity to get the exact layout you want, but the actual limitations are few. You cannot, for example, create a list style that counts down from 10, but adding one manually is a rare and minor inconvenience at best.

Figure 2:+HDGHUVDUHVRFXVWRPL]DEOHWKDWWKH\UHTXLUHWZRSDQHVWROLVWDOOWKH SRVVLELOLWLHV

/,1(63$&,1*.(51,1* $1'+@,IWKLVKDSSHQVWR \RXRQD0DFXVHWKHFRP PDQGOLQHWRGHFRPSUHVV$O WHUQDWLYHO\LQVWDOODGLIIHUHQW DUFKLYHSURJUDP6WXII,W([ SDQGHU>@LVVWLOODYDLODEOH ■)RU/LQX[WKLQJVGHSHQGRQ \RXUFKRLFHVIRUGHVNWRSHQYL URQPHQWDQGILOHPDQDJHU$V DQH[DPSOH.'(­V'ROSKLQRI IHUVYDULRXVRSWLRQVIRUWUHDWLQJ ]LSILOHV/HIWFOLFNLQJWKHILOH ZLOOGLVSOD\LWVFRQWHQWVLQWKH $UNSURJUDPZKLOHDULJKWFOLFN RSHQVWKHFRQWH[WPHQXZKHUH Extract | Extract archive here, autodetect subfolder is the EHVWFKRLFH )LJXUH  'HSHQGLQJRQ\RXUXQ]LSWRRO­V GHIDXOWVHWWLQJVWKHXQSDFNHG ILOHVPLJKWDSSHDULQWKHVDPH IROGHUWKDWFRQWDLQVWKH]LSILOHEH FDXVH/LEUH2IILFH]LSILOHVVWRUH WKRVHILOHVLQWKHWRSOHYHOGLUHF WRU\,QPRVWFDVHVWKDWLVQRW ZKDW\RXZDQW,I\RXUXQ]LSSUR gram provides an unpack to subdirectoryRSWLRQ OLNHWKHRQHPHQ WLRQHGIRUWKH'ROSKLQFRQWH[W PHQXRQ/LQX[.'( XVHWKDW

LIBREOFFICE SPECIAL – 2020 EDITION

75

GET PRODUCTIVE ODF XML element content (such as the headline), and the corresponding closing tag (). Thus, Hello will match, but Nope will not because h1 and h2 are not the same.

),1',1*678))

)LJXUH2Q/LQX[\RXFDQHLWKHUGLVSOD\WKH]LSILOHFRQWHQWVLQDQDUFKLYHPDQDJHU RUPDNHWKHILOHPDQDJHUH[WUDFWWKHFRQWHQWVWRVRPHORFDWLRQ

)LJXUH:KHQ\RXLQVSHFWWKHcontent.xmlILOH\RXFDQILQGWKHWH[W\RXHQWHUHG

Q meta.xml contains metadata like title, author, generator (name and version of the word processor), and file creation and modification timestamps. Q styles.xml describes the text and paragraph styles used by the document. Q settings.xml stores some document properties. Since I am only interested in text contents, I’ll focus on content.xml. In Figure 4, you can see how the “Hello World” text occurs in the XML file: It is enclosed in opening and closing tags. For quickly finding text inside such tags you could search for the ” symbol. The streaming editor sed can do that: $ sed -e $'s/>/>\\\n/g'

U

content.xml | egrep "\n").split("\n")

18

for line in lines:

16

popd > /dev/null

17

rm -r "${newtmp}"

18 done

19 20

if search("",line): if pattern in line:

excellent support for all modern operhighlight() by 21 line = highlight(line,pattern) ating systems. Read the “Get Python putting a comment 22 print("%s: %s" % (lodoc,line)) for Windows” box for installation insign (#) before the structions. Again, Linux and macOS second-last line. users find Python preinstalled on their The main code is in lines 12-22. The Lines 14-16 use the ZipFile function systems. script expects the pattern to search for to open the current LibreOffice file and What’s the Python code in Listing 2 as first argument (argv[1], argument extract the contents of /content.xml doing? Line 1 makes the program find vector, entry 1). All further arguments from the archive’s root directory. the right Python interpreter on Unix-like can be accessed as argv[2], argv[3], Line 17 mimics the behavior of the systems, and in lines 3-5 the script imshell version of this program: The reetc., and the for command in line 13 ports some default modules, which are starts a loop over all those file names. place method adds a newline after each part of every Python installation. The For each of the names, all of the follow“>” character, and the split method modules provide functions for opening ing steps will be executed. turns the string into an array of strings: zip files, evaluating command-line arguments, and matching regular expressions against strings. Lines 7-10 implement a highlight() function, which adds escape sequences to parts of a string so that this part of the string is shown in a different color. Note that highlighting works only on Linux and macOS (and when run from Bash on Windows). If you start the script from cmd.exe, you should )LJXUH,QDVHOHFWLRQRI*HUPDQFRXUVHVOLGHVRQRSHUDWLQJV\VWHPVWKH%DVKDQG3\WKRQYHUVLRQVRI remove the call to logrepILQGDQGKLJKOLJKWWKHVHDUFKWHUPª%HWULHEV«

LIBREOFFICE SPECIAL – 2020 EDITION

77

GET PRODUCTIVE ODF XML Now every opening or closing tag sits in its private array entry. Lines 18-22 perform a loop over all the short lines that were generated in the previous step. If a line matches the pattern, and if, furthermore, the search term occurs in that line, it gets run through the highlighter() and then displayed in the filename: line format.

7851$+$&.,172 62)7:$5( Everything so far must be called a hack. There is nothing wrong with quickly hacking together a Shell or Python script that “does the job,” but attacking XML data structures with simple regular expressions does ask for trouble. For example, imagine what might happen if a search term was identical with an XML element name: Searching and replacing that with some random word would introduce syntax errors to the file.

Is there a better way to process XML files? Python developers can use the xml. etree.ElementTree module [6] and have an XML document properly parsed. It works like this: 1. Use the fromstring function to convert a string into an XML tree structure. The function call returns the root of that tree. 2. Use the findall method to search the tree (starting at the root) for interesting elements, such as and . 3. For each match, access the contents via its text property. Then you could print it, modify it, collect statistical data, etc. Thus, a basic code block for achieving the goal mentioned in the introduction (replacing the word “Linux” with “Windows”) would be this: from xml.etree

U

import ElementTree as et # ...content is a string w/ XML inside root = et.fromstring(content)

*(73