<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
<script:module xmlns:script="http://openoffice.org/2000/script" script:name="TexMathsEquations" script:language="StarBasic">&apos;
&apos;    TexMathsEquations
&apos;
&apos;	 Copyright (C) 2012-2026 Roland Baudin (roland65@free.fr)
&apos;    Based on the work of Geoffroy Piroux (gpiroux@gmail.com)
&apos;
&apos;    This program is free software; you can redistribute it and/or modify
&apos;    it under the terms of the GNU General Public License as published by
&apos;    the Free Software Foundation; either version 2 of the License, or
&apos;    (at your option) any later version.
&apos;
&apos;    This program is distributed in the hope that it will be useful,
&apos;    but WITHOUT ANY WARRANTY; without even the implied warranty of
&apos;    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
&apos;    GNU General Public License for more details.
&apos;
&apos;    You should have received a copy of the GNU General Public License
&apos;    along with this program; if not, write to the Free Software
&apos;    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
&apos;

&apos; 	 Macros used to create the LaTeX equation

&apos; Force variable declaration
Option Explicit


&apos; Global constants

Global Const DLG_MIN_WIDTH  = 402  &apos; In map Appfonts units
Global Const DLG_MIN_HEIGHT = 332  &apos; In map Appfonts units

&apos; Shrinking factor when symbols are not shown
Global Const SHRINK_DLG_WIDTH = 0.85
Global Const SHRINK_DLG_HEIGHT = 0.78

Global Const ANCHOR_TO_PARA = 0
Global Const ANCHOR_TO_CHAR = 1
Global Const ANCHOR_TO_PAGE = 2
Global Const ANCHOR_AT_CHAR = 4

&apos; Must be even
Global Const HISTORY_MAX_SIZE = 2000

&apos; Global preferences variables
Global glb_UserPath as String, glb_TmpPath as String, glb_PkgPath as String, glb_SymbolColor as String
Global glb_Preamble as String, glb_Format as String
Global glb_IgnorePreamble as Boolean
Global glb_WriterSize as String, glb_WriterEquationType as String
Global glb_ImpressSize as String, glb_ImpressEquationType as String
Global glb_DrawSize as String, glb_DrawEquationType as String
Global glb_GraphicDPI as String
Global glb_WriterTransparency as String
Global glb_ImpressTransparency as String
Global glb_DrawTransparency as String
Global glb_Status as String
Global glb_ShowSymbols as Boolean
Global glb_ShowAppTooOld as Boolean
Global glb_WordVertAlign as Boolean
Global glb_EditorFontName as String
Global glb_EditorFontSize as String
Global glb_Compiler as String

&apos; Global translation variables
Global glb_PoFileRead as Integer
Global glb_MsgId(0) as String
Global glb_MsgStr(0) as String

&apos; Variables related to the edit equation mode
Public oShapePosition as Variant
Public editEquation as Boolean

&apos; History
Global glb_History(0) as String
Global glb_nHistory as Integer


&apos; Main subroutine
Sub Main
  
	&apos; The Writer component is required
	If ComponentInstalled( &quot;Writer&quot; ) = FALSE Then

  		MsgBox( _(&quot;Please install the Writer component to run TexMaths Equations...&quot;), 0, &quot;TexMaths&quot;)
  		Exit Sub

	End If	 

	&apos; The Draw component is required
	If ComponentInstalled( &quot;Draw&quot; ) = FALSE Then

  		MsgBox( _(&quot;Please install the Draw component to run TexMaths Equations...&quot;), 0, &quot;TexMaths&quot; )
  		Exit Sub

	End If	 
 	
	&apos; Set TexMaths configuration
	SetConfig()
	
	&apos; Check program paths
	CheckProgramPaths()
	
	&apos; Exit if configuration was not saved
	Dim oSystemInfo as Variant
	oSystemInfo = GetConfigAccess(&quot;/ooo.ext.texmaths.Registry/SystemInfo&quot;, TRUE)
	If oSystemInfo.ConfigSaved = &quot;&quot; Then Exit Sub
	
	&apos; Get compiler
	glb_Compiler = oSystemInfo.Compiler
	
	&apos; Get Word vertical alignment compatibility option
	If oSystemInfo.WordVertAlign = &quot;TRUE&quot; Then	glb_WordVertAlign = TRUE Else glb_WordVertAlign = FALSE

	&apos; Get editor font name
	glb_EditorFontName = oSystemInfo.EditorFontName

	&apos; Get editor font size
	glb_EditorFontSize = oSystemInfo.EditorFontSize

	&apos; Get show symbols option
	If oSystemInfo.ShowSymbols = &quot;TRUE&quot; Then glb_ShowSymbols = TRUE Else glb_ShowSymbols = FALSE

	&apos; Get show app too old option
	If oSystemInfo.ShowAppTooOld = &quot;TRUE&quot; Then glb_ShowAppTooOld = TRUE Else glb_ShowAppTooOld = FALSE

	&apos; Get the current document and controller
 	Dim oDoc as Variant, oDocCtrl as Variant
 	oDoc = ThisComponent
	oDocCtrl = oDoc.getCurrentController()

	&apos; Test if we are in Writer, Impress or Draw and set the default user preferences
	Dim equationSize as String, equationType as String, equationCode as String, equationFormat as String
	Dim equationDPI as String, equationTransp as String, equationName as String

	&apos; Default image format, graphic DPI and transparency
	equationFormat = glb_Format
	equationDPI = glb_GraphicDPI

	If GetDocumentType(oDoc) = &quot;swriter&quot; Then

		&apos; Get equation transparency
		equationTransp = glb_WriterTransparency

		&apos; If we are in Writer preview mode, just silently exit
		If oDoc.getCurrentController.getFrame.LayoutManager.isElementVisible ( &quot;private:resource/toolbar/previewobjectbar&quot; ) Then Exit Sub

		&apos; We are in a Writer doc, set default preferences
		equationSize = glb_WriterSize
		equationType = glb_WriterEquationType
		equationCode = &quot;&quot;

	ElseIf GetDocumentType(oDoc) = &quot;simpress&quot; Then

		&apos; Get equation transparency
		equationTransp = glb_ImpressTransparency

		&apos; We are in an Impress doc, set default preferences
		equationSize = glb_ImpressSize
		equationType = glb_ImpressEquationType
		equationCode = &quot;&quot;

	ElseIf GetDocumentType(oDoc) = &quot;sdraw&quot; Then

		&apos; Get equation transparency
		equationTransp = glb_DrawTransparency

		&apos; We are in an Draw doc, set default preferences
		equationSize = glb_DrawSize
		equationType = glb_DrawEquationType
		equationCode = &quot;&quot;

	Else

		MsgBox( GetDocumentType(oDoc) &amp; _(&quot;: document type not supported by TexMaths&quot;), 0, &quot;TexMaths&quot; )
		Exit Sub

	End If

	&apos; If there is something selected, then we are in the edit equation mode
	&apos; and we have to get the equation attributes (font size, equation type, LaTeX code)
	&apos; NB in Writer, if no text is selected oDocCtrl.selection() is not empty but the selected text is &quot;&quot;
	
	editEquation = FALSE

	If Not isEmpty(oDocCtrl.getSelection()) Then

		Dim dlgArg as String
		Dim StrArray() as String
		Dim oSelection as Variant, oShape as Variant
		oSelection = oDocCtrl.getSelection()
		
		If isNull(oSelection) Then 

			TexMaths.TexMathsText.main()
			
			Exit Sub
		
		End If
		
		&apos; We are in a Writer document
		If GetDocumentType(oDoc) = &quot;swriter&quot; Then

			&apos; For Writer, check if the selected objet is a SwXTextGraphicObject
	    	If oSelection.getImplementationName() = &quot;SwXTextGraphicObject&quot; Then
		
				oShape = oSelection
				dlgArg = ReadAttributes(oShape)
				
				If dlgArg = &quot;&quot; Then

					&apos; Try TexMaths Text
					TexMaths.TexMathsText.main()
					Exit Sub

	    		End If
	       		editEquation = TRUE

				StrArray() = Split(dlgArg,&quot;§&quot;)

				&apos; Pre v0.39 equation
				If Ubound(StrArray) = 2 Then
				
		    		equationSize = StrArray(0)
		    		equationType = StrArray(1)
		    		equationCode = StrArray(2)
				
				ElseIf Ubound(StrArray) = 5 Then

		    		equationSize = StrArray(0)
		    		equationType = StrArray(1)
		    		equationCode = StrArray(2)
		    		equationFormat = StrArray(3)
		    		equationDPI = StrArray(4)
		    		equationTransp = StrArray(5)
		    		equationName = &quot;&quot;

				ElseIf Ubound(StrArray) = 6 Then

		    		equationSize = StrArray(0)
		    		equationType = StrArray(1)
		    		equationCode = StrArray(2)
		    		equationFormat = StrArray(3)
		    		equationDPI = StrArray(4)
		    		equationTransp = StrArray(5)
		    		equationName = StrArray(6)
				
				Else
				
					&apos; Try TexMaths Text
					TexMaths.TexMathsText.main()
					Exit Sub
				
				End If
	    		
	   			glb_Status = _(&quot;Edit equation...&quot;)	    		
	    		TexMathsDialog(equationSize, equationType, equationCode, equationFormat, equationDPI, equationTransp, equationName, TRUE)
	    		Exit Sub
	    		
			&apos; Selected objet is a SvxShapeCollection
	    	ElseIf oSelection.getImplementationName() = &quot;com.sun.star.drawing.SvxShapeCollection&quot; Then
		
				oShape = oSelection.getByIndex(0)
				dlgArg = ReadAttributes(oShape)
			
				If dlgArg = &quot;&quot; Then
						
					&apos; Try TexMaths Text
					TexMaths.TexMathsText.main()
					Exit Sub
	
	    		End If
	       		editEquation = TRUE

				StrArray() = Split(dlgArg, &quot;§&quot;)

				&apos; Pre v0.39 equation
				If Ubound(StrArray) = 2 Then
				
		    		equationSize = StrArray(0)
		    		equationType = StrArray(1)
		    		equationCode = StrArray(2)
				
				ElseIf Ubound(StrArray) = 5 Then

		    		equationSize = StrArray(0)
		    		equationType = StrArray(1)
		    		equationCode = StrArray(2)
		    		equationFormat = StrArray(3)
		    		equationDPI = StrArray(4)
		    		equationTransp = StrArray(5)
		    		equationName = &quot;&quot;
				
				ElseIf Ubound(StrArray) = 6 Then

		    		equationSize = StrArray(0)
		    		equationType = StrArray(1)
		    		equationCode = StrArray(2)
		    		equationFormat = StrArray(3)
		    		equationDPI = StrArray(4)
		    		equationTransp = StrArray(5)
		    		equationName = StrArray(6)

				Else
				
					&apos; Try TexMaths Text
					TexMaths.TexMathsText.main()
					Exit Sub

				End If
				    		
	   			glb_Status = _(&quot;Edit equation...&quot;)	    		
	    		TexMathsDialog(equationSize, equationType, equationCode, equationFormat, equationDPI, equationTransp, equationName, TRUE)
	    		Exit Sub


			&apos; Selected object is Text
			ElseIf oSelection.supportsService(&quot;com.sun.star.text.TextRanges&quot;) Then

				&apos; Call MakeLatexEquation without dialog box
				Dim oSel as Variant		
      			oSel = oSelection.getByIndex(0)
      			If oSel.supportsService(&quot;com.sun.star.text.TextRange&quot;) And oSel.String &lt;&gt; &quot;&quot; Then
     					
		 			&apos; Get selected text
		 			Dim oViewCursor as Variant
		 			Dim oCursor as Variant
		 			
		 			oViewCursor = oDocCtrl.ViewCursor
		 			
		 			oCursor = GetLeftMostCursor(oSel)
					oViewCursor.gotoRange(oCursor, FALSE)
	 	 			
	 				oCursor = GetRightMostCursor(oSel)
					oViewCursor.gotoRange(oCursor, TRUE)
	
	 				&apos; Generate LaTeX equation
	 				MakeLatexEquation(CInt(equationSize), equationType, oSel.String, equationFormat, equationDPI, equationTransp, &quot;&quot;, null, TRUE)	      					
	 				Exit Sub
      				
      			End If
      				
	    	&apos; Other object
	    	Else
	    	
				&apos; Try TexMaths Text
				TexMaths.TexMathsText.main()
				Exit Sub
	    	
	    	End If
	
		&apos; We are in an Impress or Draw document
		ElseIf GetDocumentType(oDoc) = &quot;simpress&quot; Or  GetDocumentType(oDoc) = &quot;sdraw&quot; Then
		
			&apos; For Impress or Draw, check if the selected object is in a SvxShapeCollection
			If oSelection.getImplementationName() = &quot;com.sun.star.drawing.SvxShapeCollection&quot; Then
			
				oShape = oSelection.getByIndex(0)
				dlgArg = ReadAttributes(oShape)
				If dlgArg = &quot;&quot; Then
				
					&apos; Try TexMaths Text
					TexMaths.TexMathsText.main()
					Exit Sub

	    		End If
				oShapePosition = oShape.position()
	       		editEquation = TRUE
	    		
				StrArray() = Split(dlgArg, &quot;§&quot;)

				&apos; Pre v0.39 equation
				If Ubound(StrArray) = 2 Then
				
		    		equationSize = StrArray(0)
		    		equationType = StrArray(1)
		    		equationCode = StrArray(2)
				
				ElseIf Ubound(StrArray) = 5 Then

		    		equationSize = StrArray(0)
		    		equationType = StrArray(1)
		    		equationCode = StrArray(2)
		    		equationFormat = StrArray(3)
		    		equationDPI = StrArray(4)
		    		equationTransp = StrArray(5)
		    		equationName = &quot;&quot;

				ElseIf Ubound(StrArray) = 6 Then

		    		equationSize = StrArray(0)
		    		equationType = StrArray(1)
		    		equationCode = StrArray(2)
		    		equationFormat = StrArray(3)
		    		equationDPI = StrArray(4)
		    		equationTransp = StrArray(5)
		    		equationName = StrArray(6)
				
				Else
				
					&apos; Try TexMaths Text
					TexMaths.TexMathsText.main()
					Exit Sub
				
				End If
   		
	   			glb_Status = _(&quot;Edit equation...&quot;)
	    		TexMathsDialog(equationSize, equationType, equationCode, equationFormat, equationDPI, equationTransp, equationName, TRUE)
	    		Exit Sub
	
	    	&apos; Other object
	    	Else
	    	
				&apos; Try TexMaths Text
				TexMaths.TexMathsText.main()
				Exit Sub
	    	
	    	End If

		End If

	End If

	&apos; Open the dialog box with the default options, for LaTeX equations
	TexMathsDialog(equationSize, equationType, equationCode, equationFormat, equationDPI, equationTransp, equationName, TRUE)

End Sub


&apos; Set configuration
Sub SetConfig

	&apos; Initialize state String
	glb_Status = &quot;&quot;
	
	&apos; Set default system configuration (pkg, user and tmp paths)
	DefaultSysConfig()

	&apos; Set default equation preferences (image format, equation type, font size)
	DefaultPrefs()

	&apos; Apply saved config if it exists
	If FileExists(glb_UserPath &amp; &quot;TexMaths.cfg&quot; ) Then ReadPrefFileName()
	
	&apos; Try to read a local stored LaTeX preamble
	If ReadLocalPreamble() = 0 Then
	
		&apos; Try to read a global preamble
		If ReadGlobalPreamble() = 0 Then
			
			&apos; Fallback to the default preamble
			SetDefaultPreamble()
			
		End If
	
	End If
	
End Sub


&apos; This is the core macro for LaTeX equations, it is called by the dialog box
&apos; with the equationCode, equationType, equationSize, equationFormat, equationDPI and equationTransp variables
&apos; It makes the image and inserts it in the document as a graphic image
&apos; Save and restore the clipboard if variable clipboard is set to TRUE
&apos; Return -1 if an error has occurred, else return 0
Function MakeLatexEquation(equationSize as Integer, equationType as String, equationCode as String, _
                           equationFormat as String, equationDPI as String, equationTransp as String, _
                           equationName as String, oShape as Variant, clipboard as Boolean) as Integer

	Dim iNumber as Integer
	Dim URL as String, shellArg as String, msg as String, latexCode as String, shellCommand as String
	Dim version as String

	&apos; Create the controller and dispatcher for the current document
	Dim oDoc as Variant, oDocCtrl as Variant, oDispatcher as Variant
	oDoc = ThisComponent
	oDocCtrl = oDoc.getCurrentController()
	oDispatcher = createUnoService(&quot;com.sun.star.frame.DispatchHelper&quot;)

	&apos; Create an empty hidden Writer temporary document to save the clipboard content
	If clipboard = TRUE Then

		Dim oClipDoc as Variant
		oclipDoc = StarDesktop.loadComponentFromURL( &quot;private:factory/swriter&quot;, &quot;_blank&quot;, 0, Array( MakePropertyValue( &quot;Hidden&quot;, TRUE ) ) )
		SaveClipboard(oClipDoc)
		
	End If

	&apos; Put current document to front
	&apos;Dim oWindow as Variant
	&apos;oWindow = oDocCtrl.Frame.ContainerWindow
	&apos;oWindow.ToFront()

	&apos; We first test if there is LateX code
	If equationCode = &quot;&quot; Then 

		MsgBox( _(&quot;Please enter an equation...&quot;), 0, &quot;TexMaths&quot; )
		MakeLatexEquation = -1
		Exit Function

	End If

	&apos; Force LaTeX mode when equation code contains certain environments
	&apos; because they don&apos;t work in Display or Inline mode
	If InStr(equationCode, &quot;\begin{align&quot;) &lt;&gt; 0 _
		Or InStr(equationCode, &quot;\begin{eqnarray&quot;) &lt;&gt; 0 _
	   	Or InStr(equationCode, &quot;\begin{gather&quot;) &lt;&gt; 0 _
	   	Or InStr(equationCode, &quot;\begin{flalign&quot;) &lt;&gt; 0 _
	   	Or InStr(equationCode, &quot;\begin{multline&quot;) &lt;&gt; 0 _
	   	Or InStr(equationCode, &quot;\begin{minted&quot;) &lt;&gt; 0 Then
	   
	   equationType = &quot;latex&quot;
	
	End If

	&apos; Check if the LaTeX code has any dependencies that can be fulfilled easily by copying files from source dir to tmp dir
	&apos; We check for include and input (with .tex files) and usepackage (with .sty files)
	&apos; Note that we search in the preamble and in the LaTeX code (we concatenate the two)
	&apos; Patch by Daniel Fett

	&apos; Document URL
	URL = ThisComponent.getURL()
	
	&apos; Open service file and an output stream
	Dim oFileAccess as Variant, oTextStream as Variant
	oFileAccess = createUnoService(&quot;com.sun.star.ucb.SimpleFileAccess&quot;)
	oTextStream  = createUnoService(&quot;com.sun.star.io.TextOutputStream&quot;)

	Dim potentialFile as String
	Dim filePath as String 
	Dim tmpPath as String
	
	Dim SplittedURL() as String
	Dim currentDir as String
	
	SplittedURL = split(URL, &quot;/&quot;)

	For Each potentialFile in FindInLatexCommand(glb_Preamble &amp; equationCode, &quot;include&quot;)

		&apos; Document not saved
		If (URL = &quot;&quot;) Then	

			MsgBox( _(&quot;Please save the document before using an include command...&quot;), 0, &quot;TexMaths&quot; )
			MakeLatexEquation = -1
			Exit Function

		End If
		
		&apos; Copy tex file to the tmp directory
		currentDir = Left(URL, Len(URL) - Len(SplittedURL(UBound(SplittedURL))))
		
		If Right(potentialFile, 4) = &quot;.tex&quot; Then
		
			filePath = currentDir &amp; &quot;/&quot; &amp; potentialFile
			tmpPath = ConvertToURL( glb_TmpPath &amp; potentialFile )
			
		Else		
		
			filePath = currentDir &amp; &quot;/&quot; &amp; potentialFile &amp; &quot;.tex&quot;
			tmpPath = ConvertToURL( glb_TmpPath &amp; potentialFile &amp; &quot;.tex&quot; )
			
		End If

		If oFileAccess.exists(filePath) Then oFileAccess.copy(filePath, tmpPath)

	Next
	
	For Each potentialFile in FindInLatexCommand(glb_Preamble &amp; equationCode, &quot;input&quot;)

		&apos; Document not saved
		If (URL = &quot;&quot;) Then

			MsgBox( _(&quot;Please save the document before using an input command...&quot;), 0, &quot;TexMaths&quot; )
			MakeLatexEquation = -1
			Exit Function

		End If

		&apos; Copy tex file to the tmp directory
		currentDir = Left(URL, Len(URL) - Len(SplittedURL(UBound(SplittedURL))))

		If Right(potentialFile, 4) = &quot;.tex&quot; Then
		
			filePath = currentDir &amp; &quot;/&quot; &amp; potentialFile
			tmpPath = ConvertToURL( glb_TmpPath &amp; potentialFile )
			
		Else		
		
			filePath = currentDir &amp; &quot;/&quot; &amp; potentialFile &amp; &quot;.tex&quot;
			tmpPath = ConvertToURL( glb_TmpPath &amp; potentialFile &amp; &quot;.tex&quot; )
			
		End If

		If oFileAccess.exists(filePath) Then oFileAccess.copy(filePath, tmpPath)

	Next
	
	For Each potentialFile in FindInLatexCommand(glb_Preamble &amp; equationCode, &quot;usepackage&quot;)
	
		&apos; Document not saved
		If (URL = &quot;&quot;) Then
	
            &apos; Path of sty file in tmp dir
			If Right(potentialFile, 4) = &quot;.sty&quot; Then
			
                tmpPath = ConvertToURL( glb_TmpPath &amp; potentialFile )
				
			Else		
			
				tmpPath = ConvertToURL( glb_TmpPath &amp; potentialFile &amp; &quot;.sty&quot; )
				
			End If

			If oFileAccess.exists(tmpPath) Then oFileAccess.kill(tmpPath)
		
		Else

			&apos; Copy sty file to the tmp directory
			currentDir = Left(URL, Len(URL) - Len(SplittedURL(UBound(SplittedURL))))
	
			If Right(potentialFile, 4) = &quot;.sty&quot; Then
			
				filePath = currentDir &amp; &quot;/&quot; &amp; potentialFile
				tmpPath = ConvertToURL( glb_TmpPath &amp; potentialFile )
				
			Else		
			
				filePath = currentDir &amp; &quot;/&quot; &amp; potentialFile &amp; &quot;.sty&quot;
				tmpPath = ConvertToURL( glb_TmpPath &amp; potentialFile &amp; &quot;.sty&quot; )
				
			End If
	
			If oFileAccess.exists(filePath) Then oFileAccess.copy(filePath, tmpPath)
			
		End If
	
	Next

	&apos; For Inline or Display equations, separate \include and \input commands from normal code
	&apos; to insert them at different places in the tex file
	If equationType = &quot;inline&quot;  Or  equationType = &quot;display&quot; Then

		Dim inCode as String, eqCode as String
		
		&apos; Initialize
		inCode = &quot;&quot;
		eqCode = &quot;&quot;

		&apos; Some \include or \input commands in equation code, then separate
		If InStr(equationCode, &quot;\include&quot;) &lt;&gt; 0 Or InStr(equationCode, &quot;\input&quot;) Then
		
			Dim SplittedLine() as String, i as Integer
			
			SplittedLine() = Split(equationCode, chr(10))	
		
			For i = 0 to UBound(SplittedLine)
			
				If InStr(SplittedLine(i), &quot;\include&quot;) &lt;&gt; 0 Or InStr(SplittedLine(i), &quot;\input&quot;) &lt;&gt; 0 Then
						
					inCode = inCode &amp; SplittedLine(i) &amp; chr(10)
					
				Else
					
					If SplittedLine(i) &lt;&gt; &quot;&quot; Then eqCode = eqCode &amp; SplittedLine(i) &amp; chr(10)
					
				End If
				
			Next
		
		&apos; No \include or \input commands in equation code
		Else
		
			eqCode = equationCode
		
		End If

		&apos; Build the LaTeX code, depending on the selected type
		If equationType = &quot;inline&quot;  Then
			
			latexCode = &quot;\begin{document}&quot; &amp; chr(10) &amp;_
			inCode &amp; chr(10) &amp;_
			&quot;\newsavebox{\eqbox}&quot; &amp; chr(10) &amp;_
			&quot;\newlength{\width}&quot; &amp; chr(10) &amp;_
			&quot;\newlength{\height}&quot; &amp; chr(10) &amp;_
			&quot;\newlength{\depth}&quot; &amp; chr(10) &amp; chr(10) &amp;_
			&quot;\begin{lrbox}{\eqbox}&quot; &amp; chr(10) &amp;_
			&quot;\begin{math}&quot; &amp; chr(10) &amp;_
			eqCode &amp; chr(10) &amp;_
			&quot;\end{math}&quot; &amp; chr(10) &amp;_		
			&quot;\end{lrbox}&quot; &amp; chr(10) &amp; chr(10) &amp;_
			&quot;\settowidth {\width}  {\usebox{\eqbox}}&quot; &amp; chr(10) &amp;_
			&quot;\settoheight{\height} {\usebox{\eqbox}}&quot; &amp; chr(10) &amp;_
			&quot;\settodepth {\depth}  {\usebox{\eqbox}}&quot; &amp; chr(10) &amp;_
			&quot;\newwrite\file&quot; &amp; chr(10) &amp;_
			&quot;\immediate\openout\file=\jobname.bsl&quot; &amp; chr(10) &amp;_
			&quot;\immediate\write\file{Depth = \the\depth}&quot; &amp; chr(10) &amp;_
			&quot;\immediate\write\file{Height = \the\height}&quot; &amp; chr(10) &amp;_
			&quot;\addtolength{\height} {\depth}&quot; &amp; chr(10) &amp;_
			&quot;\immediate\write\file{TotalHeight = \the\height}&quot; &amp; chr(10) &amp;_
			&quot;\immediate\write\file{Width = \the\width}&quot; &amp; chr(10) &amp;_
			&quot;\closeout\file&quot; &amp; chr(10) &amp;_
			&quot;\usebox{\eqbox}&quot; &amp; chr(10) &amp;_
			&quot;\end{document}&quot; &amp; chr(10)
			
		ElseIf equationType = &quot;display&quot;  Then
			
			latexCode = &quot;\begin{document}&quot; &amp; chr(10) &amp;_
			inCode &amp; chr(10) &amp;_
			&quot;\newsavebox{\eqbox}&quot; &amp; chr(10) &amp;_
			&quot;\newlength{\width}&quot; &amp; chr(10) &amp;_
			&quot;\newlength{\height}&quot; &amp; chr(10) &amp;_
			&quot;\newlength{\depth}&quot; &amp; chr(10) &amp; chr(10) &amp;_
			&quot;\begin{lrbox}{\eqbox}&quot; &amp; chr(10) &amp;_
			&quot;\begin{math}&quot; &amp; chr(10) &amp;_
			&quot;\displaystyle &quot; &amp; eqCode &amp; chr(10) &amp;_
			&quot;\end{math}&quot; &amp; chr(10) &amp;_		
			&quot;\end{lrbox}&quot; &amp; chr(10) &amp; chr(10) &amp;_
			&quot;\settowidth {\width}  {\usebox{\eqbox}}&quot; &amp; chr(10) &amp;_
			&quot;\settoheight{\height} {\usebox{\eqbox}}&quot; &amp; chr(10) &amp;_
			&quot;\settodepth {\depth}  {\usebox{\eqbox}}&quot; &amp; chr(10) &amp;_
			&quot;\newwrite\file&quot; &amp; chr(10) &amp;_
			&quot;\immediate\openout\file=\jobname.bsl&quot; &amp; chr(10) &amp;_
			&quot;\immediate\write\file{Depth = \the\depth}&quot; &amp; chr(10) &amp;_
			&quot;\immediate\write\file{Height = \the\height}&quot; &amp; chr(10) &amp;_
			&quot;\addtolength{\height} {\depth}&quot; &amp; chr(10) &amp;_
			&quot;\immediate\write\file{TotalHeight = \the\height}&quot; &amp; chr(10) &amp;_
			&quot;\immediate\write\file{Width = \the\width}&quot; &amp; chr(10) &amp;_
			&quot;\closeout\file&quot; &amp; chr(10) &amp;_
			&quot;\usebox{\eqbox}&quot; &amp; chr(10) &amp;_
			&quot;\end{document}&quot; &amp; chr(10)
	
		Else &apos; Should not happen
		
			latexCode = equationCode
			
		End If
	
	&apos; equationType = &quot;latex&quot;
	Else 
	
		latexCode = equationCode
		
	End If

	&apos; Create the LaTeX file with the LaTeX code
	URL = ConvertToURL( glb_TmpPath &amp; &quot;tmpfile.tex&quot; )
	If oFileAccess.exists( URL ) Then oFileAccess.kill( URL )
    oTextStream.setOutputStream(oFileAccess.openFileWrite(URL))
       
    &apos; LuaLaTeX compiler is incompatible with dvips
    Dim head as String
    If glb_Compiler = &quot;lualatex&quot; Then
    	head = &quot;\documentclass[10pt]{article}&quot;
    Else
    	head = &quot;\documentclass[10pt,dvips]{article}&quot;
    End If
	
	If equationType = &quot;latex&quot; Then
	
		If glb_IgnorePreamble = TRUE Then
	
			oTextStream.writeString(latexCode)
	
		Else
	
			oTextStream.writeString( _
			    	head &amp; chr(10) &amp;_
		    		glb_Preamble &amp; chr(10) &amp; chr(10) &amp;_
			    	&quot;\pagestyle{empty}&quot; &amp; chr(10) &amp;_
			    	&quot;\begin{document}&quot; &amp; chr(10) &amp;_
			    	latexCode &amp; chr(10) &amp;_
			    	&quot;\end{document}&quot; )
	
		End If

	Else
	
		oTextStream.writeString( _
		    	head &amp; chr(10) &amp;_
		    	glb_Preamble &amp; chr(10) &amp; chr(10) &amp;_
		    	&quot;\pagestyle{empty}&quot; &amp; chr(10) &amp;_
		    	latexCode )
	
	End If

	&apos; Close the file
    oTextStream.closeOutput()
    
    &apos; Test the existence of the LaTeX file...
    If CheckFile( glb_TmpPath &amp; &quot;tmpfile.tex&quot; , _
    		_(&quot;The file &quot;) &amp; ConvertFromURL(glb_TmpPath) &amp; _(&quot;tmpfile.tex can&apos;t be created&quot;) &amp; chr(10) &amp; _
			_(&quot;Please check your installation...&quot;) ) Then 

		ConfigDialog()
		MakeLatexEquation = -1
		Exit Function

	End If
	
	&apos; Windows
	If getGUIType() = 1 Then

		shellCommand = ConvertToURL( GetScriptPath() )
		shellArg = equationFormat &amp; &quot; &quot;  &amp; equationDPI &amp; &quot; &quot;  &amp; equationTransp &amp; &quot; &quot; &amp; glb_TmpPath &amp; &quot; &quot; &amp; glb_Compiler

	&apos; Linux or Mac OS X
	Else 					
		
		shellCommand = &quot;/bin/sh&quot;
		shellArg = &quot;&apos;&quot; &amp; ConvertFromURL(GetScriptPath()) &amp; &quot;&apos; &quot; &amp; equationFormat &amp;_
				    &quot; &quot; &amp; equationDPI &amp; &quot; &quot; &amp; equationTransp &amp; &quot; &apos;&quot;  &amp; ConvertFromURL(glb_TmpPath) &amp; &quot;&apos; &quot; &amp; glb_Compiler
	End If

    &apos; Remove LaTeX output file
	URL = ConvertToURL( glb_TmpPath &amp; &quot;tmpfile.out&quot; )
	If oFileAccess.exists( URL ) Then oFileAccess.kill( URL )

	&apos; Call the script
	Shell(shellCommand, 2, shellArg, TRUE)

	&apos; Check the result
	Dim dviFile as String
	If glb_Compiler = &quot;latex&quot; Or glb_Compiler = &quot;lualatex&quot; Then dviFile = &quot;tmpfile.dvi&quot; Else dviFile = &quot;tmpfile.xdv&quot;
	 
 	If Not FileExists(glb_TmpPath &amp; dviFile) and Not FileExists(glb_TmpPath &amp; &quot;tmpfile.out&quot;)  Then
		MsgBox( _(&quot;No file created in the directory:&quot;) &amp; _
  		       chr(10) &amp; ConvertFromURL(glb_TmpPath), 0, &quot;TexMaths&quot; )
  		MakeLatexEquation = -1
  		Exit Function

 	ElseIf Not FileExists(glb_TmpPath &amp; dviFile) and FileExists(glb_TmpPath &amp; &quot;tmpfile.out&quot;)  Then &apos; LaTeX error

  		PrintError(&quot;tmpfile.out&quot;)
  		MakeLatexEquation = -1
  		Exit Function

 	ElseIf CheckFile(glb_TmpPath &amp; &quot;tmpfile.&quot; &amp; equationFormat,_
   		_(&quot;Script error: the dvi file was not converted to &quot;) &amp; equationFormat &amp; &quot;! &quot; &amp; chr(10) &amp; chr(10) &amp;_
   		_(&quot;Please check your system configuration...&quot;) ) Then
   		
	  		MakeLatexEquation = -1
	  		Exit Function

 	End If

	Dim ret as Boolean, oGraphic as Variant, oShapeSize as Variant

	&apos; ================== Current document is a Writer document ==================
	If GetDocumentType(oDoc) = &quot;swriter&quot; Then

		Dim oViewCursor as Variant, oCursor as Variant
		Dim anchorType as Integer

		&apos; If there is already an equation image, remove it
		If editEquation Then

			&apos; Select image (ensuring compatibility with pre v0.39 TexMaths versions)
			Dim oSelection as Variant
			On Error Goto SelectionError
			oSelection = oDocCtrl.getSelection().GetByIndex(0)
			On Error GoTo 0
			
			&apos; Get selected image anchor
			Dim oAnchor as Variant
			oAnchor = oSelection.getAnchor()
			anchorType = oSelection.anchorType

			&apos; Unselect image
		 	oDispatcher.executeDispatch( oDocCtrl.Frame, &quot;.uno:Escape&quot;, &quot;&quot;, 0, Array())
		 	
		 	&apos; Workaround for an issue with gtk3 backend
		 	If isNull(oShape) Then oDoc.drawPage.remove(oSelection) Else oDoc.drawPage.remove(oShape)
		 
		 End If
		 				
		&apos; Set text cursor position to the view cursor position
		oViewCursor = oDocCtrl.ViewCursor
		oCursor = oViewCursor.Text.createTextCursorByRange(oViewCursor)
		oCursor.gotoRange(oViewCursor,FALSE)
								
		&apos; Import the new image into the clipboard
   		ret = ImportGraphicIntoClipboard(ConvertToURL( glb_TmpPath &amp; &quot;tmpfile.&quot;&amp; equationFormat), equationFormat, equationDPI, equationTransp, equationCode)
   		If ret = FALSE Then
   		
	  		MakeLatexEquation = -1
	  		Exit Function
   		
   		 End If
	
		&apos; Save actual value of the expert setting SelectPastedAnchoredObject
		&apos; and set the value to true for TexMaths (for LibreOffice 26.2+)
		Dim settingVal as Boolean
		settingVal = GetSelPastedSetting()
		SetSelPastedSetting(true)

		&apos; Paste image to the current document
		oDispatcher.executeDispatch(oDocCtrl.Frame, &quot;.uno:Paste&quot;, &quot;&quot;, 0, Array())
	
		&apos; Restore setting value (for LibreOffice 26.2+)
		SetSelPastedSetting(settingVal)

	  	&apos; Select image
	   	oGraphic = oDocCtrl.getSelection().GetByIndex(0)

		&apos; Set the graphic object name
		oGraphic.Name = equationName

		&apos; Scale image
		oShapeSize = oGraphic.Size
		oShapeSize.Width = oShapeSize.Width * (equationSize / 10)
		oShapeSize.Height = oShapeSize.Height * (equationSize / 10)
		oGraphic.Size = oShapeSize	

		&apos; In edit mode, anchor the image as it was
		If editEquation Then
		
			Select Case anchorType

				Case ANCHOR_TO_PARA
					oDispatcher.executeDispatch(oDocCtrl.Frame, &quot;.uno:SetAnchorToPara&quot;, &quot;&quot;, 0, Array())
				
				Case ANCHOR_TO_CHAR
					oDispatcher.executeDispatch(oDocCtrl.Frame, &quot;.uno:SetAnchorToChar&quot;, &quot;&quot;, 0, Array())
				
				Case ANCHOR_TO_PAGE
					oDispatcher.executeDispatch(oDocCtrl.Frame, &quot;.uno:SetAnchorToPage&quot;, &quot;&quot;, 0, Array())
				
				Case ANCHOR_AT_CHAR
					oDispatcher.executeDispatch(oDocCtrl.Frame, &quot;.uno:SetAnchorAtChar&quot;, &quot;&quot;, 0, Array())
			
			End Select
		
		&apos; New equations are anchored to char
		Else
		
			anchorType = ANCHOR_TO_CHAR
			oDispatcher.executeDispatch(oDocCtrl.Frame, &quot;.uno:SetAnchorToChar&quot;, &quot;&quot;, 0, Array())
			
		End If
	
		 &apos; Set some image properties
		oGraphic.TopMargin = 0
		oGraphic.BottomMargin = 0
		oGraphic.VertOrient = 0

		&apos; Adjust vertical position for Inline or Display equations when image is anchored to char
		If anchorType = ANCHOR_TO_CHAR and ( equationType = &quot;inline&quot; or equationType = &quot;display&quot; ) Then
					
			&apos; Get vertical shift coefficient
			Dim coef as Double
			coef = getVertShift()
			
			&apos; Adjust the vertical position to the baseline
			oGraphic.VertOrientPosition = -coef * oShapeSize.Height

		End If

		&apos; Set image attributes (size, type LaTeX code) for further editing
		SetAttributes( oGraphic, equationSize, equationType, equationCode, equationFormat, equationDPI, equationTransp, equationName )

		&apos; Save the paragraph style
		Dim paraStyleName as String, paraAdjust as Integer
		paraStyleName = oViewCursor.paraStyleName
		paraAdjust = oViewCursor.paraAdjust

		&apos; Trick to ensure the image is located at the cursor position
		&apos; =&gt; cut image, position cursor, then paste
		&apos; =&gt; otherwise, the image can be anywhere within the paragraph 
		oDispatcher.executeDispatch(oDocCtrl.Frame, &quot;.uno:Cut&quot;, &quot;&quot;, 0, Array())		
		oViewCursor.gotoRange(oCursor, FALSE)
		oDispatcher.executeDispatch(oDocCtrl.Frame, &quot;.uno:Paste&quot;, &quot;&quot;, 0, Array())

		&apos; Adjust vertical alignement for Word
		If glb_WordVertAlign = TRUE and anchorType = ANCHOR_TO_CHAR and ( equationType = &quot;inline&quot; or equationType = &quot;display&quot; ) Then

			&apos; Paragraph must be aligned vertically to baseline
			&apos; otherwise vertical alignment will be erratic in Word
			oViewCursor.ParaVertAlignment = 1

			&apos; Select graphic image and adjust its character vertical position
			oViewCursor.goLeft(1, FALSE)
			oViewCursor.goRight(1, TRUE)
			oViewCursor.CharEscapement = 100 * (coef - 1)
			oViewCursor.CharEscapementHeight = 100
				
		&apos; Necessary for Recompile All macro
		Else
		
			&apos; Reset character vertical position
			oViewCursor.goLeft(1, FALSE)
			oViewCursor.goRight(1, TRUE)
			oViewCursor.CharEscapement = 0
			oViewCursor.CharEscapementHeight = 100
		
		
		End If

		&apos; Restore paragraph style if it changed
		If paraStyleName &lt;&gt; oViewCursor.paraStyleName Then
					
			oViewCursor.paraStyleName = paraStyleName
			oViewCursor.paraAdjust = paraAdjust
			
		End If

		&apos; Deselect image (no more necessary for LibreOffice 7.2 and later?)
		oDispatcher.executeDispatch(oDocCtrl.Frame, &quot;.uno:Escape&quot;, &quot;&quot;, 0, Array())

		&apos; Reset character vertical alignement
		If glb_WordVertAlign = TRUE and anchorType = ANCHOR_TO_CHAR and ( equationType = &quot;inline&quot; or equationType = &quot;display&quot; ) Then

			oViewCursor.CharEscapement = 0
			oViewCursor.CharEscapementHeight = 100
		
		End If


	&apos; ================== Current document is an Impress or Draw document ==================
	ElseIf GetDocumentType(oDoc) = &quot;simpress&quot; or GetDocumentType(oDoc) = &quot;sdraw&quot; Then
		
 		&apos; Edit equation: remove old image
 		If editEquation Then 
 			
 			&apos; Fill in reference to original shape (used to keep animations and Z index)
			Dim oOriginalShape as Variant
			Dim oOriginalShapeZOrder as Long
			oOriginalShape = oDocCtrl.getSelection().getByIndex(0)
			oOriginalShapeZOrder = oOriginalShape.ZOrder
 			oDispatcher.executeDispatch(oDocCtrl.Frame,&quot;.uno:Cut&quot;, &quot;&quot;, 0, Array() )
 		
 		End If
		
		&apos; Import the new image to the clipboard
   		ret = ImportGraphicIntoClipboard(ConvertToURL( glb_TmpPath &amp; &quot;tmpfile.&quot; &amp; equationFormat), equationFormat, equationDPI, equationTransp, equationCode)
   		If ret = FALSE Then

	  		MakeLatexEquation = -1
  			Exit Function

   		End If

		&apos; Paste image to the current document
		oDispatcher.executeDispatch( oDocCtrl.Frame, &quot;.uno:Paste&quot;, &quot;&quot;, 0, Array())

		&apos; Select image
		oGraphic = oDocCtrl.getSelection().getByIndex(0)

		&apos; Set the graphic object name
		oGraphic.Name = equationName

		&apos; Edit equation: set its position equal to the previous one
		If editEquation Then

			oGraphic.setPosition(oShapePosition)
		
		&apos; New equation: Position the image at the center of the visible area
		Else
		
			Dim oPosition as Variant
			oPosition = createUnoStruct( &quot;com.sun.star.awt.Point&quot; ) 
			oPosition.X = oDocCtrl.VisibleArea.X + oDocCtrl.VisibleArea.Width / 2 - (oGraphic.Size.Width*equationSize/10) / 2
			oPosition.Y = oDocCtrl.VisibleArea.Y + oDocCtrl.VisibleArea.Height / 2	- (oGraphic.Size.Height* equationSize/10) / 2
			oGraphic.setPosition(oPosition)

		End If

		&apos; Scale the image
		oShapeSize = oGraphic.Size
		oShapeSize.Width = oShapeSize.Width * equationSize / 10
		oShapeSize.Height = oShapeSize.Height * equationSize / 10
		oGraphic.Size = oShapeSize
		
		&apos; Set image attributes (size, type LaTeX code) for further editing
		SetAttributes( oGraphic, equationSize, equationType, equationCode, equationFormat, equationDPI, equationTransp, equationName)

		&apos; Trick to allow undoing the equation insertion
		oDispatcher.executeDispatch( oDocCtrl.Frame, &quot;.uno:Cut&quot;, &quot;&quot;, 0, Array())
		oDispatcher.executeDispatch( oDocCtrl.Frame, &quot;.uno:Paste&quot;, &quot;&quot;, 0, Array())

		&apos; Select image (this unexpectedly fails in rare cases) 
		On Error GoTo Error1
		oGraphic = oDocCtrl.getSelection().getByIndex(0)
		On Error GoTo 0

		&apos; Edit equation: if in Normal view mode, transfer animations from old shape to new shape
 		If editEquation and GetDocumentType(oDoc) = &quot;simpress&quot; and oDocCtrl.DrawViewMode = 0 Then
			TransferAnimations(oDocCtrl.getCurrentPage(), oOriginalShape, oGraphic) 			
			TransferAnimations(oDocCtrl.getCurrentPage(), oOriginalShape, oGraphic) 
		End If

		&apos; Preserve Z index of equation
		If editEquation Then oGraphic.ZOrder = oOriginalShapeZOrder

	End If
	
	&apos; Restore clipboard content
	If clipboard = TRUE Then
	
		RestoreClipboard(oClipDoc)
	
		&apos; Close temporary clipboard document (fails sometimes)
		On Error GoTo Error2
		oClipDoc.close( TRUE )
		On Error GoTo 0 &apos; Restore error handler
		
	End If

	&apos; Push LaTeX code to history
	PushToHistory(equationCode, glb_History, glb_nHistory)
	
	&apos; Return
	MakeLatexEquation = 0
	Exit Function

	&apos; To ensure compatibility with previous TexMaths versions
	SelectionError:
		oSelection = oDocCtrl.getSelection
		Resume Next
		
	Error1:
		MsgBox( _(&quot;Unexpected error (error code #1), please try again...&quot;), 48, &quot;TexMaths&quot; )
		MakeLatexEquation = 0
		Exit Function

	Error2:
		MsgBox( _(&quot;Unexpected error (error code #2), please try again...&quot;), 48, &quot;TexMaths&quot; )
		MakeLatexEquation = 0

End Function

</script:module>