[Writer] Work-around for a Two lines heading

Shared Libraries
Forum rules
For sharing working examples of macros / scripts. These can be in any script language supported by OpenOffice.org [Basic, Python, Netbean] or as source code files in Java or C# even - but requires the actual source code listing. This section is not for asking questions about writing your own macros.
Post Reply
User avatar
foxcole
Volunteer
Posts: 1507
Joined: Mon Oct 08, 2007 1:31 am
Location: Minneapolis, Minnesota

[Writer] Work-around for a Two lines heading

Post by foxcole »

 Edit: Hagar: discussion continuing that one: [Tutorial] Work-around for a Two lines heading
Nice work! Thank you, RGB.

Just one minor note... the text in the document sounds as though the TwoLinesHeading toolbar is automatically open and floating over the document. These settings appear to be user-specific, however, not settings that travel with the file. I needed to go into View> Toolbars and enable the TwoLineHeading entry, after which the toolbar appeared next to the Standard toolbar. I like tools such as this one to float, because it seems a shorter distance to the tool, so I simply undocked it by grabbing the dotted left end of the toolbar and dragging it out to the document area.

On an editorial note, if I were you I'd not use the words "trick" and "tricky" so much in the intro. These are negative words that make the method sound as though it's very difficult to use, creating a prejudice in the user's mind before they even get started. You want to "sell" the fruits of your labor and help people use it, not encourage them to avoid it! ;)

It is quite easy to use, in fact, so I'd like to add my vote for and endorsement of this macro. Very nice!
Cheers!
---Fox

OOo 3.2.0 Portable, Windows 7 Home Premium 64-bit
User avatar
RGB
Posts: 1456
Joined: Mon Oct 08, 2007 1:34 am

Re: [Tutorial] Work-around for a Two lines heading

Post by RGB »

I must post a "bug report" related to (but not caused by) my own work-around.
Sometimes, on a completely random way, when I run the macro to insert the double-line heading the second line "inherits" the font of the following paragraph. For example, suppose that headings use DejaVu Sans font, and main text Linux Libertine; if between two existing "main text" paragraphs I insert a new line and then run the macro, sometimes the second line of the heading (the real heading) turns to Linux Libertine. I can quickly fix it by selecting the paragraph and pressing Ctrl+Shift+Space (delete format), which shows that this character change is a sort of "direct formatting". On my understanding, this is a Writer misbehaviour, but I cannot "catch" the sequence that triggers it, so I don't know how to report the problem.
This random error seem to happen on both, versions 2.3 (64 bits from Fedora 8) and 2.4 (official 32 bits build)
Any idea?
There are two types of people: those who believe that there are two types of people and those who do not.

openSUSE Leap with KDE Plasma / LibreOffice
User avatar
Hagar Delest
Moderator
Posts: 32627
Joined: Sun Oct 07, 2007 9:07 pm
Location: France

Re: [Tutorial] Work-around for a Two lines heading

Post by Hagar Delest »

I've tried with your document and can't reproduce that. Can you upload a file where it did it for you?
LibreOffice 7.6.2.1 on Xubuntu 23.10 and 7.6.4.1 portable on Windows 10
User avatar
RGB
Posts: 1456
Joined: Mon Oct 08, 2007 1:34 am

Re: [Tutorial] Work-around for a Two lines heading

Post by RGB »

Here it is:
EncabezadoDosLineas.odt
The guilty
(18.72 KiB) Downloaded 665 times
Steps to reproduce the problem:
1. Go to the end of chapter 1 (Capítulo 1) and press enter
2. Press the EncabezadoDeDosLineas button
3. Type something.
Result: The Heading 1 paragraph shows a Liberation Serif font instead the Liberation Sans. Selecting the paragraph and pressing Ctrl+Shift+Space delete the unwanted "direct formatting"
Now, undo everything (or close the document without saving)
1. Go to the end of chapter 1 (Capítulo 1) and press enter
2. Press Ctrl+Shift+Space on the empty paragraph
3. Press the EncabezadoDeDosLineas button
4. Type something.
Result: Font in the Heading 1 paragraph is Liberation Sans, as it should be.
:?:

BTW: This sample is the Spanish version of the original document
There are two types of people: those who believe that there are two types of people and those who do not.

openSUSE Leap with KDE Plasma / LibreOffice
User avatar
Hagar Delest
Moderator
Posts: 32627
Joined: Sun Oct 07, 2007 9:07 pm
Location: France

Re: [Tutorial] Work-around for a Two lines heading

Post by Hagar Delest »

I've looked at the content.xml file and it seems that your text has got some direct formatting in few places. So in fact, it's not a random behavior. It's just that some paragraphs have been directly formatted by accident and the setting sticks to the new paragraphs created hitting Enter when in those paragraphs. So the newly created headings inherits the direct formatting from the previous paragraph, not the following one. Here are some extracts.

The introduction is fine for first paragraph (try the macro, it works fine):

Code: Select all

- <text:h text:style-name="Heading_20_1" text:outline-level="1">
   <text:tab /> 
   Introducción 
  </text:h>
  <text:p text:style-name="Text_20_body">No existe un modo sencillo de tener un encabezado de dos lineas en Writer como el "simulado" en este documento: si se inserta un quiebre de linea (Ctrl+Enter) en un párrafo de encabezado, este quiebre de línea se verá también en el índice de contenidos (IDC desde ahora), haciéndolo poco apetecible. Si se usa una combinación de dos estilo, uno numerado y el otro no, habrá problemas con las referencias cruzadas a los capítulos...</text:p>
But last paragraph of the intro has got a non existing string formatted with T4 text style sticking to the whole paragraph:

Code: Select all

- <text:p text:style-name="Text_20_body">
   <text:span text:style-name="T4" /> 
  </text:p>
- <text:p text:style-name="Text_20_body">
   <text:span text:style-name="T4">Los estilos están organizados de modo tal que Encabezado 1 sigue automáticamente a FalsoCap. Para realizar una referencia cruzada a otro capítulo, se debe seleccionar el "verdadero capítulo", como se muestra en el capítulo</text:span>
T4 being defined at beginning:

Code: Select all

- <style:style style:name="T4" style:family="text">
   <style:text-properties style:font-name="Liberation Serif" style:font-name-asian="DejaVu LGC Sans" style:font-name-complex="DejaVu LGC Sans" /> 
  </style:style>
So why the direct formatting in some places? That's the question. But your macro is fine.
LibreOffice 7.6.2.1 on Xubuntu 23.10 and 7.6.4.1 portable on Windows 10
User avatar
RGB
Posts: 1456
Joined: Mon Oct 08, 2007 1:34 am

Re: [Tutorial] Work-around for a Two lines heading

Post by RGB »

Thanks! I'll go with some Ctrl+Shift+Space here and there to fix the whole document.
The document was created from scratch and no direct formatting was ever applied. The origin of the T4 style is a complete mystery for me...
Oh well, I'll survive.
Thanks again!
There are two types of people: those who believe that there are two types of people and those who do not.

openSUSE Leap with KDE Plasma / LibreOffice
User avatar
Hagar Delest
Moderator
Posts: 32627
Joined: Sun Oct 07, 2007 9:07 pm
Location: France

Re: [Tutorial] Work-around for a Two lines heading

Post by Hagar Delest »

I was playing around your code and here is a proposal. It's not finished yet but I now face the difficult (for me) task to define the numbering styles and I've not yet found out how to do that. Seems to be related to arrays for the settings.

What it does for the moment:
- Create both the WhiteChar and FakeChapter styles (if they don't exist yet)
- Insert the FakeChapter paragraph with Numbering 1 style
- Insert (automatically) the new paragraph with Heading 1, with its indent and [standard] tabulation
- Apply the WhiteChar style and the outline numbering to Heading 1

Todo:
- Apply the WhiteChar style and the outline numbering to Heading 1
- Perhaps set the first tabstop to 1.5 cm (equal to negative indent)
- Set the "Chapter " prefix for Numbering 1
 Edit: Removed the code, now deprecated, see new code in that post below 
Of course, the Chapter string has still to be added manually to the TOC structure line, except if it's put as prefix in the Outline numbering (but perhaps the indent needs to be modified then).

Note that in your macro, the lines to put the non breaking spaces have been deactivated (with the 'REM' string at their beginning). But you don't really need them since the Heading 1 is not empty (has a tabulation). And a 'numbered list ' paragraph can be empty, the only thing is that you can't hit Enter to create the next numbered paragraph. That's why it works fine even without the non breaking spaces.
LibreOffice 7.6.2.1 on Xubuntu 23.10 and 7.6.4.1 portable on Windows 10
User avatar
foxcole
Volunteer
Posts: 1507
Joined: Mon Oct 08, 2007 1:31 am
Location: Minneapolis, Minnesota

Re: [Tutorial] Work-around for a Two lines heading

Post by foxcole »

Because this is a tutorial, could this problem please be split into a new thread in the Writer forum? That includes my prior post, which I might have made before I realized it should not be done in the thread (or perhaps before the thread was moved from the Writer forum to Tutorials; I've no idea, but regardless, I don't think my comment belongs here.)
Cheers!
---Fox

OOo 3.2.0 Portable, Windows 7 Home Premium 64-bit
User avatar
Hagar Delest
Moderator
Posts: 32627
Joined: Sun Oct 07, 2007 9:07 pm
Location: France

Re: [Writer] Work-around for a Two lines heading

Post by Hagar Delest »

OK, done.

BTW, I've modified the code, the only remaining point is to set the configuration for the Numbering 1 style.
LibreOffice 7.6.2.1 on Xubuntu 23.10 and 7.6.4.1 portable on Windows 10
User avatar
Hagar Delest
Moderator
Posts: 32627
Joined: Sun Oct 07, 2007 9:07 pm
Location: France

Re: [Writer] Work-around for a Two lines heading

Post by Hagar Delest »

I've improved the code and written the macro in Basic language to make it more clear and to allow customization.
Added features:
  • Creation of a custom ChapterNumber numbering style to avoid troubles if Numbering 1 is already used in the document
  • You can specify the Heading level to be faked (drawback: you don't have the parent numbering and you've to restart the numbering ChapterNumber at each chapter)
  • You have to define Prefix and Suffix in the macro
  • The Prefix and Suffix can be put automatically in the TOC (can be deactivated)
Enjoy!

NB: with OOo 3, because of a new feature, allowing a tab stop after the heading number (configuration by default), the code below had to be changed. Therefore it is now adapted for the 3.0. To make it work with 2.#, uncomment the line tagged 'OOo 2 compatibility'.
 Edit: New code in that post
For the installation: [Tutorial] How to install a code snippet.
LibreOffice 7.6.2.1 on Xubuntu 23.10 and 7.6.4.1 portable on Windows 10
User avatar
Hagar Delest
Moderator
Posts: 32627
Joined: Sun Oct 07, 2007 9:07 pm
Location: France

Re: [Writer] Work-around for a Two lines heading

Post by Hagar Delest »

Another code is available here if you want to insert line breaks in the heading: Ignoring line breaks in headings for the index?
LibreOffice 7.6.2.1 on Xubuntu 23.10 and 7.6.4.1 portable on Windows 10
User avatar
Hagar Delest
Moderator
Posts: 32627
Joined: Sun Oct 07, 2007 9:07 pm
Location: France

Re: [Writer] Work-around for a Two lines heading

Post by Hagar Delest »

New version that allows a document to have several heading levels with different prefixes and suffixes.

Code: Select all

Option Explicit         ' http://user.services.openoffice.org/en/forum
Sub TwoLinesHeadings    ' Hagar Delest from the concept by RGB
Dim oDoc as Object      ' v1.2 - Mar. 23 2009
Dim oCharStyles as Object, oCharStyle as Object
Dim oNumStyles as Object, oNumStyle as Object
Dim oParaStyles as Object, oParaStyle as Object
Dim oViewCursor as Object
Dim oCurText as Object
Dim oCursor as Object
Dim iLevel%   ' Faked heading level
Dim sPrefix as String   ' Customize your prefix
Dim sSuffix as String   ' Customize your suffix

'----------------------  User customization  ----------------------
' To get something like:
'    Chapter #:
'    My chapter
sPrefix = "Chapter"
sSuffix = ": "
iLevel = 1   ' Set to 2 if you want to fake Heading 2
' But you won't get the parent numbering
'------------------------------------------------------------------

oDoc = stardesktop.currentComponent

' Create the styles if they don't exist
oCharStyles = oDoc.styleFamilies.getByName("CharacterStyles")
If not oCharStyles.hasByName("WhiteChar") then
	oCharStyle = oDoc.createInstance("com.sun.star.style.CharacterStyle")
    oCharStyles.insertByName("WhiteChar", oCharStyle)
    oCharStyle.CharColor = RGB(255,255,255)
End If
       
oNumStyles = oDoc.styleFamilies.getByName("NumberingStyles")
If not oNumStyles.hasByName("ChapterNumber " & iLevel) then
    oNumStyle = oDoc.createInstance("com.sun.star.style.NumberingStyle")
    oNumStyles.insertByName("ChapterNumber " & iLevel, oNumStyle)
End If

oParaStyles = oDoc.styleFamilies.getByName("ParagraphStyles")
If not oParaStyles.hasByName("FakeChapter " & iLevel) then
    oParaStyle = oDoc.createInstance("com.sun.star.style.ParagraphStyle")
    oParaStyles.insertByName("FakeChapter " & iLevel, oParaStyle)
    oParaStyle.NumberingStyleName = "ChapterNumber " & iLevel
    oParaStyle.ParentStyle = "Heading " & iLevel
    oParaStyle.ParaFirstLineIndent = 0
    oParaStyle.FollowStyle = "Heading " & iLevel
End If

' Define the numbering styles and change Heading indent
SetHeadingNumbering("Heading " & iLevel, iLevel, sPrefix, sSuffix)
SetNumbering("ChapterNumber " & iLevel, sPrefix, sSuffix)
oParaStyle = oParaStyles.getByName("Heading " & iLevel)
oParaStyle.ParaFirstLineIndent = -4000
           
' Apply the FakeChapter paragraph style and a new paragraph
oViewCursor =  oDoc.CurrentController.ViewCursor
oCurText = oViewCursor.Text
oCursor = oCurText.createTextCursorByRange(oViewCursor)
oViewCursor.ParaStyleName = "FakeChapter " & iLevel
oCurText.insertString(oCursor,chr$(13), false)
'oCurText.insertString(oCursor,chr$(9), false)  ' OOo 2 compatibility
End Sub

' Update the outline Numbering configuration
Sub SetHeadingNumbering(sStyleName,iHeadLevel,sHeadPrefix, sHeadSuffix)
Dim i%, j%
Dim oRules as Object
Dim oRule as Object
Dim oProp as Object

oRules = ThisComponent.getChapterNumberingRules
i = iHeadLevel - 1
oRule = oRules.getByIndex(i)
For j = LBound(oRule) To Ubound(oRule)
    oProp = oRule(j)
    Select Case oProp.Name
       	Case "HeadingStyleName"
        	oProp.Value = sStyleName
		Case "NumberingType"
            oProp.Value = com.sun.star.style.NumberingType.ARABIC
        Case "CharStyleName"
            oProp.Value = "WhiteChar"
        Case "Prefix"
            oProp.Value = sHeadPrefix   ' Replace by "" if you don't
        Case "Suffix"
            oProp.Value = sHeadSuffix   ' want the TOC to display Pre/Suffix
    End Select
    oRule(j) = oProp
Next
oRules.replaceByIndex(i, oRule)
End Sub

' Set the numbering for FakeChapter style
Sub SetNumbering(sStyleName as string, sHeadPrefix, sHeadSuffix)
Dim oFamilies as Object
Dim oStyle as Object
Dim oParaStyles as Object
Dim oNumStyles as Object
Dim oRules as Object
Dim i%, j%
Dim oRule as Object
Dim oProp as Object

'Get all Styles then Numbering styles
oFamilies = ThisComponent.StyleFamilies
oNumStyles = oFamilies.getByName("NumberingStyles")
oStyle = oNumStyles.getByName(sStyleName)
oRules = oStyle.NumberingRules
For i = 0 to oRules.GetCount() - 1
	oRule = oRules.getByIndex(i)
	For j = LBound(oRule) To UBound(oRule)
		oProp = oRule(j)
		Select Case oProp.Name
			Case "NumberingType"
				oProp.Value = com.sun.star.style.NumberingType.ARABIC
            Case "Prefix"
                oProp.Value = sHeadPrefix
            Case "Suffix"
                oProp.Value = sHeadSuffix
            Case "LeftMargin"
			oProp.Value = 640
		End Select
        oRule(j) = oProp
	Next
    'overwrite the old Property-Value
    oRules.replaceByIndex(i, oRule)
Next
'overwrite the old NumberingRules with the new ones
oStyle.NumberingRules = oRules
End Sub
For the installation: [Tutorial] How to install a code snippet.
LibreOffice 7.6.2.1 on Xubuntu 23.10 and 7.6.4.1 portable on Windows 10
Post Reply