Source

texmaths / src / TexMathsEquations.bas

Full commit
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007

'
'    TexMathsEquations
'
'	 Copyright (C) 2012-2014 Roland Baudin (roland65@free.fr)
'    Based on the work of Geoffroy Piroux (gpiroux@gmail.com)
'
'    This program is free software; you can redistribute it and/or modify
'    it under the terms of the GNU General Public License as published by
'    the Free Software Foundation; either version 2 of the License, or
'    (at your option) any later version.
'
'    This program is distributed in the hope that it will be useful,
'    but WITHOUT ANY WARRANTY; without even the implied warranty of
'    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'    GNU General Public License for more details.
'
'    You should have received a copy of the GNU General Public License
'    along with this program; if not, write to the Free Software
'    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
'

' 	 Macros used to create the LaTeX equation

' Force variable declaration
Option Explicit


' Global constants
Global Const DLG_MIN_HEIGHT = 250
Global Const DLG_MIN_WIDTH = 200
Global Const DLG_STEP_SIZE = 5
Global Const ANCHOR_TO_PARA = 0
Global Const ANCHOR_TO_CHAR = 1
Global Const ANCHOR_TO_PAGE = 2
Global Const ANCHOR_AT_CHAR = 4


' Global preferences variables
Global glb_sUserPath as String, glb_sTmpPath as String, glb_sPkgPath as String
Global glb_sPreamble as String, glb_sFormat as String
Global glb_bIgnorePreamble as Boolean
Global glb_sWriterSize as String, glb_sWriterEqType as String
Global glb_sImpressSize as String, glb_sImpressEqType as String
Global glb_sDrawSize as String, glb_sDrawEqType as String
Global glb_sGraphicDPI as String, glb_sTransparency as String
Global glb_sStatus as String
Global glb_WordVertAlign as Boolean

' Global translation variables
Global glb_PoFileRead as Integer
Global glb_MsgId(0) as Variant
Global glb_MsgStr(0) as Variant

' Variables related to the edit equation mode
Public oShapePosition as Variant
Public EditEquation as Boolean, Dialog as Boolean



' Main subroutine
Sub main
  
	' The Draw component is required
	If ComponentInstalled( "Draw" ) = FALSE Then

  		msgbox( _("Please install the Draw component to run TexMaths!") )
  		Exit Sub

	End If	 
 
	' Initialize object to null to allow testing if it was created
	oDlgMain = null
	
	' Set TexMaths configuration
	SetConfig()
	
	' Check program paths
	CheckProgramPaths()
	
	' Exit if configuration was not saved
	Dim oSystemInfo as Variant
	oSystemInfo = GetConfigAccess("/ooo.ext.texmaths.Registry/SystemInfo", TRUE)
	If oSystemInfo.ConfigSaved = "" Then Exit Sub
	
	' Get Word vertical alignment compatibility option
	If oSystemInfo.WordVertAlign = "TRUE" Then	glb_WordVertAlign = TRUE Else glb_WordVertAlign = FALSE

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

	' Test if we are in Writer, Impress or Draw and set the default user preferences
	Dim sEqSize as String, sEqType as String, sEqLatexCode as String, sEqFormat as String, sEqDPI as String, sEqTransp as String, sEqName as String

	' Default image format, graphic DPI and transparency
	sEqFormat = glb_sFormat
	sEqDPI = glb_sGraphicDPI
	sEqTransp = glb_sTransparency

	If GetDocumentType(oDoc) = "swriter" Then

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

		' We are in a Writer doc, set default preferences
		sEqSize = glb_sWriterSize
		sEqType = glb_sWriterEqType
		sEqLatexCode = ""

	ElseIf GetDocumentType(oDoc) = "simpress" Then

		' We are in an Impress doc, set default preferences
		sEqSize = glb_sImpressSize
		sEqType = glb_sImpressEqType
		sEqLatexCode = ""

	ElseIf GetDocumentType(oDoc) = "sdraw" Then

		' We are in an Draw doc, set default preferences
		sEqSize = glb_sDrawSize
		sEqType = glb_sDrawEqType
		sEqLatexCode = ""

	Else

		Msgbox GetDocumentType(oDoc) & _(": document type not supported by TexMaths")
		Exit Sub

	End If

	' If there is something selected, then we are in the edit equation mode
	' and we have to get the equation attributes (font size, equation type, LaTeX code)
	EditEquation = FALSE
	Dialog = TRUE

	If Not isEmpty(oDocCtrl.selection()) Then

		Dim sDlgArg as String
		Dim sArray() as String
		Dim oSelection as Variant, oShape as Variant
		oSelection = oDocCtrl.getSelection()
		
		' We are in a Writer document
		If GetDocumentType(oDoc) = "swriter" Then

			' For Writer, check if the selected objet is a SwXTextGraphicObject
	    	If oSelection.getImplementationName() = "SwXTextGraphicObject" Then
		
				oShape = oSelection
				sDlgArg = ReadAttributes(oShape)
				
				If sDlgArg = "" Then
	
	    			Msgbox _("The selected object is not a TexMaths equation...") & chr(10) &_
	    				     	 _("Please unselect it and call the macro again...")
	    			Exit Sub  			

	    		End If
	       		EditEquation = TRUE

				sArray()=Split(sDlgArg,"§")

				' Pre v0.39 equation
				If Ubound(sArray) = 2 Then
				
		    		sEqSize=sArray(0)
		    		sEqType=sArray(1)
		    		sEqLatexCode=sArray(2)
				
				ElseIf Ubound(sArray) = 5 Then

		    		sEqSize=sArray(0)
		    		sEqType=sArray(1)
		    		sEqLatexCode=sArray(2)
		    		sEqFormat=sArray(3)
		    		sEqDPI=sArray(4)
		    		sEqTransp=sArray(5)
		    		sEqName=""

				ElseIf Ubound(sArray) = 6 Then

		    		sEqSize=sArray(0)
		    		sEqType=sArray(1)
		    		sEqLatexCode=sArray(2)
		    		sEqFormat=sArray(3)
		    		sEqDPI=sArray(4)
		    		sEqTransp=sArray(5)
		    		sEqName=sArray(6)
				
				Else
				
	    			Msgbox _("The selected object is not a TexMaths equation...") & chr(10) &_
	    				     	 _("Please unselect it and call the macro again...")
	    			Exit Sub  			
				
				End If
	    		
	   			glb_sStatus = _("Edit equation...")	    		
	    		TexMathsDialog(sEqSize, sEqType, sEqLatexCode, sEqFormat, sEqDPI, sEqTransp, sEqName)
	    		Exit Sub
	    		
			' Selected objet is a SvxShapeCollection
	    	ElseIf oSelection.getImplementationName() = "com.sun.star.drawing.SvxShapeCollection" Then
		
				oShape = oSelection.getByIndex(0)
				sDlgArg = ReadAttributes(oShape)
				
				If sDlgArg = "" Then
	
	    			Msgbox _("The selected object is not a TexMaths equation...") & chr(10) &_
	    				     	 _("Please unselect it and call the macro again...")
	    			Exit Sub  			
	
	    		End If
	       		EditEquation = TRUE

				sArray()=Split(sDlgArg,"§")

				' Pre v0.39 equation
				If Ubound(sArray) = 2 Then
				
		    		sEqSize=sArray(0)
		    		sEqType=sArray(1)
		    		sEqLatexCode=sArray(2)
				
				ElseIf Ubound(sArray) = 5 Then

		    		sEqSize=sArray(0)
		    		sEqType=sArray(1)
		    		sEqLatexCode=sArray(2)
		    		sEqFormat=sArray(3)
		    		sEqDPI=sArray(4)
		    		sEqTransp=sArray(5)
		    		sEqName=""
				
				ElseIf Ubound(sArray) = 6 Then

		    		sEqSize=sArray(0)
		    		sEqType=sArray(1)
		    		sEqLatexCode=sArray(2)
		    		sEqFormat=sArray(3)
		    		sEqDPI=sArray(4)
		    		sEqTransp=sArray(5)
		    		sEqName=sArray(6)

				Else
				
	    			Msgbox _("The selected object is not a TexMaths equation...") & chr(10) &_
	    				     	 _("Please unselect it and call the macro again...")
	    			Exit Sub  			
				
				End If
				    		
	   			glb_sStatus = _("Edit equation...")	    		
	    		TexMathsDialog(sEqSize, sEqType, sEqLatexCode, sEqFormat, sEqDPI, sEqTransp, sEqName)
	    		Exit Sub


			' Selected object is Text
			ElseIf oSelection.supportsService("com.sun.star.text.TextRanges") Then

				' Call MakeEquation without dialog box
				Dim oSel as Variant		
      			oSel = oSelection.getByIndex(0)
      			If oSel.supportsService("com.sun.star.text.TextRange") And oSel.String <> "" Then
     					
   					Dialog = FALSE

		 			' Find if we allow an extra CR in MakeEquation
		 			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)
	
	 				' Generate LaTeX equation
	 				MakeEquation(CInt(sEqSize), sEqType, oSel.String, sEqFormat, sEqDPI, sEqTransp, "")	      					
	 				Exit Sub
      				
      			End If
      				
	    	End If
	
		' We are in an Impress or Draw document
		ElseIf GetDocumentType(oDoc) = "simpress" Or  GetDocumentType(oDoc) = "sdraw" Then
		
			' For Impress or Draw, check if the selected object is in a SvxShapeCollection
			If oSelection.getImplementationName() = "com.sun.star.drawing.SvxShapeCollection" Then
			
				oShape = oSelection.getByIndex(0)
				sDlgArg = ReadAttributes(oShape)
				If sDlgArg = "" Then
				
    				Msgbox _("The selected object is not a TexMaths equation...") & chr(10) &_
	    				     	 _("Please unselect it and call the macro again...")
	   				Exit Sub
	    					
	    		End If
				oShapePosition = oShape.position()
	       		EditEquation = TRUE
	    		
				sArray()=Split(sDlgArg,"§")

				' Pre v0.39 equation
				If Ubound(sArray) = 2 Then
				
		    		sEqSize=sArray(0)
		    		sEqType=sArray(1)
		    		sEqLatexCode=sArray(2)
				
				ElseIf Ubound(sArray) = 5 Then

		    		sEqSize=sArray(0)
		    		sEqType=sArray(1)
		    		sEqLatexCode=sArray(2)
		    		sEqFormat=sArray(3)
		    		sEqDPI=sArray(4)
		    		sEqTransp=sArray(5)
		    		sEqName=""

				ElseIf Ubound(sArray) = 6 Then

		    		sEqSize=sArray(0)
		    		sEqType=sArray(1)
		    		sEqLatexCode=sArray(2)
		    		sEqFormat=sArray(3)
		    		sEqDPI=sArray(4)
		    		sEqTransp=sArray(5)
		    		sEqName=sArray(6)
				
				Else
				
	    			Msgbox _("The selected object is not a TexMaths equation...") & chr(10) &_
	    				     	 _("Please unselect it and call the macro again...")
	    			Exit Sub  			
				
				End If
   		
	   			glb_sStatus = _("Edit equation...")
	    		TexMathsDialog(sEqSize, sEqType, sEqLatexCode, sEqFormat, sEqDPI, sEqTransp, sEqName)
	    		Exit Sub
	
	    	' Selected object is text within a frame
	    	ElseIf oSelection.getImplementationName() = "SvxUnoTextCursor" Then

    			Msgbox _("The selected object is not a TexMaths equation...") & chr(10) &_
	    				     	 _("Please unselect it and call the macro again...")
    			Exit Sub
    			
    		End If

		End If

	End If

	' Open the dialog box with the default options
	TexMathsDialog(sEqSize, sEqType, sEqLatexCode, sEqFormat, sEqDPI, sEqTransp, sEqName)

End Sub


' Set configuration
Sub SetConfig

	' Initialise state string
	glb_sStatus = ""
	
	' Set default system configuration (pkg, user and tmp paths)
	DefaultSysConfig()

	' Set default equation preferences (image format, equation type, font size)
	DefaultPrefs()

	' Apply saved config if it exists
	If FileExists(glb_sUserPath & "TexMaths.cfg" ) Then ReadPrefsFile()
	
	' Set default preamble
	DefaultPreamble()

	' Try to read a stored LaTeX preamble
	ReadPreamble()
	
End Sub


' This is the core macro! It is called by the dialog box
' with the sEqCode, sEqType, iEqSize, sEqFormat, sEqDPI and sEqTransp variables
' It makes the image and inserts it in the document
Sub MakeEquation(iEqSize as Integer, sEqType as String, sEqCode as String, sEqFormat as String, sEqDPI as String, sEqTransp as String, sEqName as String)

	Dim iNumber as Integer
	Dim cURL as String, sShellArg as String, sMsg as String, sLatexCode as String, sShellCommand as String

	' Save initial clipboard content because it will be lost when pasting the image
	Dim sClipContent as String
	sClipContent = ClipboardToText()

	' We first test if there is LateX code
	If sEqCode = "" Then 

		Msgbox _("Please enter some LaTeX code...")
		Exit Sub

	End If

	' Some environments only work in LaTeX mode 
	If IsPrefixString("\begin{align",sEqCode) Or IsPrefixString("\begin{eqnarray",sEqCode) Or IsPrefixString("\begin{gather",sEqCode) _
	Or isPrefixString("\begin{flalign",sEqCode) Or IsPrefixString("\begin{multline",sEqCode) Or IsPrefixString("\begin{minted",sEqCode) Then
		sEqType = "latex" 
		
		' Don't do this if the object is not defined 	
		If Not isNull(oDlgMain) Then
			oDlgMain.getControl("TypeLatex").setState(1)
		End If

	End If

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

	' Document URL
	Dim sUrl as String
	sUrl = ThisComponent.getURL()
	
	' Open service file and an output stream
	Dim oFileAccess as Variant, oTextStream as Variant
	oFileAccess = createUnoService("com.sun.star.ucb.SimpleFileAccess")
	oTextStream  = createUnoService("com.sun.star.io.TextOutputStream")

	Dim sPotentialFile as String
	Dim sFilePath as String 
	
	Dim aSplittedURL() as String
	Dim sCurrentDir as String
	
	aSplittedURL = split(sUrl, "/")

	For Each sPotentialFile in FindInLatexCommand(glb_sPreamble & sEqCode, "include")

		' Document not saved
		If (sUrl = "") Then	
			msgbox _("Please save the document before using an \include command...")
			Exit Sub
		End If
		
		' When using an \include command, the equation type must be set to "latex"
		sEqType = "latex" 	
		If Not isNull(oDlgMain) Then ' Don't do this if the object is not defined
			oDlgMain.getControl("TypeLatex").setState(1)
		End If

		' Copy tex file to the tmp directory
		sCurrentDir = Left(sUrl, Len(sUrl) - Len(aSplittedUrl(UBound(aSplittedUrl))))
		sFilePath = sCurrentDir & "/" & sPotentialFile & ".tex"				
		If oFileAccess.exists(sFilePath) Then
			oFileAccess.copy(sFilePath, ConvertToURL( glb_sTmpPath & sPotentialFile & ".tex"))
		End If

	Next
	
	For Each sPotentialFile in FindInLatexCommand(glb_sPreamble & sEqCode, "input")

		' Document not saved
		If (sUrl = "") Then
			msgbox _("Please save the document before using an \input command...")
			Exit Sub
		End If

		' Copy tex file to the tmp directory
		sCurrentDir = Left(sUrl, Len(sUrl) - Len(aSplittedUrl(UBound(aSplittedUrl))))
		sFilePath = sCurrentDir & "/" & sPotentialFile & ".tex"
		If oFileAccess.exists(sFilePath) Then
			oFileAccess.copy(sFilePath, ConvertToURL( glb_sTmpPath & sPotentialFile & ".tex"))
		End If
	Next
	
	For Each sPotentialFile in FindInLatexCommand(glb_sPreamble & sEqCode, "usepackage")
	
		' Document not saved
		If (sUrl = "") Then
	
			sFilePath = ConvertToURL( glb_sTmpPath & sPotentialFile & ".sty") ' Path of sty file in tmp dir
			If oFileAccess.exists(sFilePath) Then
				oFileAccess.kill(sFilePath)
			End If
		
		Else

			sCurrentDir = Left(sUrl, Len(sUrl) - Len(aSplittedUrl(UBound(aSplittedUrl))))
			sFilePath = sCurrentDir & "/" & sPotentialFile & ".sty"
			If oFileAccess.exists(sFilePath) Then
				oFileAccess.copy(sFilePath, ConvertToURL( glb_sTmpPath & sPotentialFile & ".sty"))
			End If
		
		End If

	Next


	' Build the LaTeX code, depending on the selected mode
	If sEqType = "inline"  Then
		
		sLatexCode = "\newsavebox{\eqbox}" & chr(10) &_
		"\newlength{\width}" & chr(10) &_
		"\newlength{\height}" & chr(10) &_
		"\newlength{\depth}" & chr(10) & chr(10) &_
		"\begin{lrbox}{\eqbox}" & chr(10) &_
		"{$ " & sEqCode & " $}" & chr(10) &_
		"\end{lrbox}" & chr(10) & chr(10) &_
		"\settowidth {\width}  {\usebox{\eqbox}}" & chr(10) &_
		"\settoheight{\height} {\usebox{\eqbox}}" & chr(10) &_
		"\settodepth {\depth}  {\usebox{\eqbox}}" & chr(10) &_
		"\newwrite\file" & chr(10) &_
		"\immediate\openout\file=\jobname.bsl" & chr(10) &_
		"\immediate\write\file{Depth = \the\depth}" & chr(10) &_
		"\immediate\write\file{Height = \the\height}" & chr(10) &_
		"\addtolength{\height} {\depth}" & chr(10) &_
		"\immediate\write\file{TotalHeight = \the\height}" & chr(10) &_
		"\immediate\write\file{Width = \the\width}" & chr(10) &_
		"\closeout\file" & chr(10) &_
		"\begin{document}" & chr(10) &_
		"\usebox{\eqbox}" & chr(10) &_
		"\end{document}" & chr(10)
		
	ElseIf sEqType = "display"  Then
		
		sLatexCode = "\newsavebox{\eqbox}" & chr(10) &_
		"\newlength{\width}" & chr(10) &_
		"\newlength{\height}" & chr(10) &_
		"\newlength{\depth}" & chr(10) & chr(10) &_
		"\begin{lrbox}{\eqbox}" & chr(10) &_
		"{$\displaystyle " & sEqCode & " $}" & chr(10) &_
		"\end{lrbox}" & chr(10) & chr(10) &_
		"\settowidth {\width}  {\usebox{\eqbox}}" & chr(10) &_
		"\settoheight{\height} {\usebox{\eqbox}}" & chr(10) &_
		"\settodepth {\depth}  {\usebox{\eqbox}}" & chr(10) &_
		"\newwrite\file" & chr(10) &_
		"\immediate\openout\file=\jobname.bsl" & chr(10) &_
		"\immediate\write\file{Depth = \the\depth}" & chr(10) &_
		"\immediate\write\file{Height = \the\height}" & chr(10) &_
		"\addtolength{\height} {\depth}" & chr(10) &_
		"\immediate\write\file{TotalHeight = \the\height}" & chr(10) &_
		"\immediate\write\file{Width = \the\width}" & chr(10) &_
		"\closeout\file" & chr(10) &_
		"\begin{document}" & chr(10) &_
		"\usebox{\eqbox}" & chr(10) &_
		"\end{document}" & chr(10)

	ElseIf sEqType = "latex" Then
	
		sLatexCode = sEqCode
		
	End If


	' Create the LaTeX file with the LatexCode
	cURL = ConvertToURL( glb_sTmpPath & "tmpfile.tex" )
	If oFileAccess.exists( cURL ) Then oFileAccess.kill( cURL )
    oTextStream.setOutputStream(oFileAccess.openFileWrite(cURL))
	
	If sEqType = "latex" Then
	
		If glb_bIgnorePreamble Then
	
			oTextStream.writeString(sLatexCode)
	
		Else
	
			oTextStream.writeString( _
			    	"\documentclass[10pt]{article}" & chr(10) &_
		    		glb_sPreamble & chr(10) & chr(10) &_
			    	"\pagestyle{empty}" & chr(10) &_
			    	"\begin{document}" & chr(10) &_
			    	sLatexCode & chr(10) &_
			    	"\end{document}" )
	
		End If

	Else
	
		oTextStream.writeString( _
		    	"\documentclass[10pt]{article}" & chr(10) &_
		    	glb_sPreamble & chr(10) & chr(10) &_
		    	"\pagestyle{empty}" & chr(10) &_
		    	sLatexCode
	
	End If

	' Close the file
    oTextStream.closeOutput()
    
    ' Test the existence of the LaTeX file...
    If CheckFile( glb_sTmpPath & "tmpfile.tex" , _
    		_("The file ") & ConvertFromURL(glb_sTmpPath) & _("tmpfile.tex cannot be created") & chr(10) & _
			_("Please check your installation...") ) Then 

		ConfigDialog()
		Exit Sub

	End If
	
	' Windows
	If getGUIType() = 1 Then

		sShellCommand = GetScriptPath()	
		sShellArg = sEqFormat & " "  & sEqDPI & " "  & sEqTransp & " " & winPath(glb_sTmpPath)

	' Linux or Mac OS X
	Else 					
		
		sShellCommand = "/bin/bash"
		sShellArg = "'" & ConvertFromURL(GetScriptPath()) & "' " & sEqFormat &_
				    " " & sEqDPI & " " & sEqTransp & " '"  & ConvertFromURL(glb_sTmpPath) & "'"

	End If

    ' Remove Latex output file
	cURL = ConvertToURL( glb_sTmpPath & "tmpfile.out" )
	If oFileAccess.exists( cURL ) Then oFileAccess.kill( cURL )

	' Call the script
	Shell(sShellCommand, 2, sShellArg, TRUE)

	' Check the result
 	If Not FileExists(glb_sTmpPath & "tmpfile.dvi") _
 	   and Not FileExists(glb_sTmpPath & "tmpfile.out")  Then
		Msgbox ( _("No file created in the directory:") & _
  		       chr(10) & ConvertFromURL(glb_sTmpPath) )
  		Exit Sub

 	ElseIf Not FileExists(glb_sTmpPath & "tmpfile.dvi") _
 	       and FileExists(glb_sTmpPath & "tmpfile.out")  Then ' Latex error

  		PrintFile("tmpfile.out")
  		Exit Sub

 	ElseIf CheckFile(glb_sTmpPath & "tmpfile." & sEqFormat,_
   		_("Script error: the dvi file was not converted to ") & sEqFormat & "! " & chr(10) & chr(10) &_
   		_("Please check your system configuration...") ) Then Exit Sub
 	End If

	' Image size is 0
	If FileExists(glb_sTmpPath & "tmpfile.bsl") Then
		If GetVertShift() = 0 Then Exit Sub
	End If

	' If we arrive here, the compilation succeeded. We can close the dialog
	If Dialog Then
		oDlgMain.endExecute()
		SavePosSize()
	End If

	' Create the Controller and dispatcher for current document
	Dim oDoc as Variant, oDocCtrl as Variant, oDispatcher as Variant, oGraphic as Variant, oShapeSize as Variant
	oDoc = ThisComponent
	oDocCtrl = oDoc.getCurrentController()
	oDispatcher = createUnoService("com.sun.star.frame.DispatchHelper")


	' ================== Current document is a Writer document ==================
	If GetDocumentType(oDoc) = "swriter" Then

		Dim oViewCursor as Variant, oCursor as Variant
		Dim AnchorType as Integer

		' If there is already an equation image, remove it
		If EditEquation Then

			' Select image (ensuring compatibility with previous TexMaths versions)
			Dim oSelection as Variant
			On Error Goto SelectionError
			oSelection = oDocCtrl.getSelection().GetByIndex(0)		
			
			' Get selected image anchor
			Dim oAnchor as Variant
			oAnchor = oSelection.getAnchor()
			AnchorType = oSelection.AnchorType

			' Save image position for further use
			Dim oImgPosition as Variant
			oImgPosition = oSelection.getPosition()

			' Delete the selected image
		 	oDispatcher.executeDispatch( oDocCtrl.Frame, ".uno:Delete", "", 0, Array())

		 End If
		 
		' Set vertical alignement to middle when Word compatibility is requested
		If glb_WordVertAlign = TRUE Then
			
			dim args4(0) as new com.sun.star.beans.PropertyValue
			args4(0).Name = "VerticalParagraphAlignment"
			args4(0).Value = 3		
			oDispatcher.executeDispatch(oDocCtrl.Frame, ".uno:VerticalParagraphAlignment", "", 0, args4())
		
		End If
		
		' Set text cursor position to the view cursor position
		oViewCursor = oDocCtrl.ViewCursor
		oCursor = oViewCursor.Text.createTextCursorByRange(oViewCursor)
		oCursor.gotoRange(oViewCursor,FALSE)
								
		' Import the new image into the clipboard
   		ImportGraphicIntoClipboard(ConvertToURL( glb_sTmpPath & "tmpfile."& sEqFormat), sEqFormat, sEqDPI, sEqTransp)	
	
		' Paste image to the current document
		oDispatcher.executeDispatch( oDocCtrl.Frame, ".uno:Paste", "", 0, Array())
	
	  	' Select image
	   	oGraphic = oDocCtrl.getSelection().GetByIndex(0)

		' Set the graphic object name
		oGraphic.Name = sEqname

		' Scale image
		oShapeSize = oGraphic.Size
		oShapeSize.Width = oShapeSize.Width * (iEqSize / 10)
		oShapeSize.Height = oShapeSize.Height * (iEqSize / 10)
		oGraphic.Size = oShapeSize	

		' In edit mode, anchor the image as it was
		If EditEquation Then
		
			Select Case AnchorType

				Case ANCHOR_TO_PARA
					oDispatcher.executeDispatch( oDocCtrl.Frame, ".uno:SetAnchorToPara", "", 0, Array())
					oGraphic.setPosition(oImgPosition)
				
				Case ANCHOR_TO_CHAR
					oDispatcher.executeDispatch( oDocCtrl.Frame, ".uno:SetAnchorToChar", "", 0, Array())
					' Don't position image in this case
				
				Case ANCHOR_TO_PAGE
					oDispatcher.executeDispatch( oDocCtrl.Frame, ".uno:SetAnchorToPage", "", 0, Array())
					oGraphic.setPosition(oImgPosition)					
				
				Case ANCHOR_AT_CHAR
					oDispatcher.executeDispatch( oDocCtrl.Frame, ".uno:SetAnchorAtChar", "", 0, Array())
					oGraphic.setPosition(oImgPosition)
			
			End Select
		
		' New equations are anchored to char
		Else
		
			AnchorType = ANCHOR_TO_CHAR
			oDispatcher.executeDispatch( oDocCtrl.Frame, ".uno:SetAnchorToChar", "", 0, Array())
			
		End If
	
		 ' Set some image properties
		oGraphic.TopMargin = 0
		oGraphic.BottomMargin = 0
		oGraphic.VertOrient = 0

		' Adjust vertical position for Inline or Display equations when image is anchored to char
		If AnchorType = ANCHOR_TO_CHAR and ( sEqtype = "inline" or sEqType = "display" ) Then
			
			' Get vertical shift coefficient
			Dim coef as Double
			coef = getVertShift()
				
			' Adjust the vertical position to the baseline
			oGraphic.VertOrientPosition = - coef * oShapeSize.Height

		End If

		' Set image attributes (size, type LaTeX code) for further editing
		SetAttributes( oGraphic, iEqSize, sEqType, sEqCode, sEqFormat, sEqDPI, sEqTransp, sEqName )

		' Trick used to ensure the image is located at the cursor position 
		If AnchorType = ANCHOR_TO_CHAR Then

			oDispatcher.executeDispatch( oDocCtrl.Frame, ".uno:Cut", "", 0, Array())
			oViewCursor.gotoRange(oCursor, FALSE)
  			oDispatcher.executeDispatch( oDocCtrl.Frame, ".uno:Paste", "", 0, Array())

		Else

			' Deselect image
			oDispatcher.executeDispatch(oDocCtrl.Frame, ".uno:Escape", "", 0, Array())

		End If

		' Reposition the view cursor
		oViewCursor.gotoRange(oCursor, FALSE)



	' ================== Current document is an Impress or Draw document ==================
	ElseIf GetDocumentType(oDoc) = "simpress" or GetDocumentType(oDoc) = "sdraw" Then
		
 		' Edit equation: remove old image
 		If EditEquation Then 
 			
 			' Fill in reference to original shape (used to keep animations)
			Dim oOriginalShape as Variant
			oOriginalShape = oDocCtrl.getSelection().getByIndex(0)
 			oDispatcher.executeDispatch(oDocCtrl.Frame,".uno:Cut","", 0, Array() )
 		
 		End If
		
		' Import the new image to the clipboard
   		ImportGraphicIntoClipboard(ConvertToURL( glb_sTmpPath & "tmpfile." & sEqFormat), sEqFormat, sEqDPI, sEqTransp)

		' Paste image to the current document
		oDispatcher.executeDispatch( oDocCtrl.Frame, ".uno:Paste", "", 0, Array())

		' Select image
		oGraphic = oDocCtrl.getSelection().getByIndex(0)

		' Set the graphic object name
		oGraphic.Name = sEqname

		' Edit equation: set its position equal to the previous one
		If EditEquation Then
			oGraphic.setPosition(oShapePosition)
		
		' New equation: Position the image at the center of the visible area
		Else
		
			Dim oPosition as Variant
			oPosition = createUnoStruct( "com.sun.star.awt.Point" ) 
			oPosition.X = oDocCtrl.VisibleArea.X + oDocCtrl.VisibleArea.Width / 2 - (oGraphic.Size.Width*iEqSize/10) / 2
			oPosition.Y = oDocCtrl.VisibleArea.Y + oDocCtrl.VisibleArea.Height / 2	- (oGraphic.Size.Height* iEqSize/10) / 2
			oGraphic.setPosition(oPosition)

		End If

		' Scale the image
		oShapeSize = oGraphic.Size
		oShapeSize.Width = oShapeSize.Width * iEqSize / 10
		oShapeSize.Height = oShapeSize.Height * iEqSize / 10
		oGraphic.Size = oShapeSize

		' Edit equation: Transfer animations from old shape to new shape
 		If EditEquation and GetDocumentType(oDoc) = "simpress" Then
			TransferAnimations(oDocCtrl.getCurrentPage(), oOriginalShape, oGraphic) 			
 		End If
 		
		' Set image attributes (size, type LaTeX code) for further editing
		SetAttributes( oGraphic, iEqSize, sEqType, sEqCode, sEqFormat, sEqDPI, sEqTransp, sEqName)
		
		If not EditEquation Then
			' Trick to allow undoing the operation
			oDispatcher.executeDispatch( oDocCtrl.Frame, ".uno:Cut", "", 0, Array())
			oDispatcher.executeDispatch( oDocCtrl.Frame, ".uno:Paste", "", 0, Array())
		End If		
		

	End If
	
	' If Writer is installed, restore initial clipboard content
	If ComponentInstalled( "Writer" ) Then
		TextToClipboard(sClipContent)
	End If

	Exit Sub

	' To ensure compatibility with previous TexMaths versions
	SelectionError:
		oSelection = oDocCtrl.getSelection
		Resume Next

End Sub

' This macro recompiles every TexMath equation in Impress documents
Sub RecompileAllEquations
	' The Draw component is required
	If ComponentInstalled( "Draw" ) = FALSE Then

  		msgbox( _("Please install the Draw component to run TexMaths!") )
  		Exit Sub

	End If	 
	
	Dim iMsgResult as Variant
	iMsgResult = MsgBox(_("Do you want to recompile all equations? This may take a while."), 1)
	If iMsgResult <> 1 Then Exit Sub
 
	' Initialize object to null to allow testing if it was created
	oDlgMain = null
	
	' Set TexMaths configuration
	SetConfig()
	
	' Check program paths
	CheckProgramPaths()
	
	' Exit if configuration was not saved
	Dim oSystemInfo as Variant
	oSystemInfo = GetConfigAccess("/ooo.ext.texmaths.Registry/SystemInfo", TRUE)
	If oSystemInfo.ConfigSaved = "" Then Exit Sub
	
	' Get the current document and controller
 	Dim oDoc as Variant, oDocCtrl as Variant
 	oDoc = ThisComponent
	oDocCtrl = oDoc.getCurrentController()

	' Test if we are in Writer, Impress or Draw and set the default user preferences
	Dim sEqSize as String, sEqType as String, sEqLatexCode as String, sEqFormat as String, sEqDPI as String, sEqTransp as String, sEqName as String

	' Default image format, graphic DPI and transparency
	sEqFormat = glb_sFormat
	sEqDPI = glb_sGraphicDPI
	sEqTransp = glb_sTransparency

	If GetDocumentType(oDoc) = "simpress" Then

		' We are in an Impress doc, set default preferences
		sEqSize = glb_sImpressSize
		sEqType = glb_sImpressEqType
		sEqLatexCode = ""
	Else

		Msgbox GetDocumentType(oDoc) & _(": document type not supported by TexMathsCompileAll")
		Exit Sub

	End If

	If isEmpty(oDocCtrl.selection()) Then
		MsgBox _("Please select some drawing object.")
		Exit Sub
	End If

	Dialog = FALSE

	Dim numSlides, numForms, i, j as Integer    
	Dim oSlide, oShape as Object
	
	Dim sDlgArg as String
	Dim sArray() as String
	

    numSlides = oDoc.getDrawPages().getCount()
        
    ' go through pages
    For i = 0 to numSlides - 1
        oSlide = oDoc.drawPages(i)
        If oSlide.hasElements() Then
            For j = (oSlide.getCount() - 1) To 0 Step -1
                oShape = oSlide.getByIndex(j)
		
				' For Impress or Draw, check if the selected object is in a SvxShapeCollection
				If oShape.getImplementationName() <> "SvxShape" and oShape.getImplementationName() <> "SvxShapeText" Then
					MsgBox oShape.getImplementationName()
					goto NextShape
				End If 				
				sDlgArg = ReadAttributes(oShape)
				If sDlgArg = "" Then
					goto NextShape
	    		End If
	    		
	    		
				sArray()=Split(sDlgArg,"§")
	
				' Pre v0.39 equation
				If Ubound(sArray) = 2 Then
				
		    		sEqSize=sArray(0)
		    		sEqType=sArray(1)
		    		sEqLatexCode=sArray(2)
				
				ElseIf Ubound(sArray) = 5 Then
	
		    		sEqSize=sArray(0)
		    		sEqType=sArray(1)
		    		sEqLatexCode=sArray(2)
		    		sEqFormat=sArray(3)
		    		sEqDPI=sArray(4)
		    		sEqTransp=sArray(5)
		    		sEqName=""
	
				ElseIf Ubound(sArray) = 6 Then
	
		    		sEqSize=sArray(0)
		    		sEqType=sArray(1)
		    		sEqLatexCode=sArray(2)
		    		sEqFormat=sArray(3)
		    		sEqDPI=sArray(4)
		    		sEqTransp=sArray(5)
		    		sEqName=sArray(6)
				
				Else
					goto NextShape
				End If
	  		
	    		oDocCtrl.select(oShape)
	       		EditEquation = TRUE
				oShapePosition = oShape.position()
	    		MakeEquation(sEqSize, sEqType, sEqLatexCode, sEqFormat, sEqDPI, sEqTransp, sEqName)
NextShape:
	
            Next
        EndIf
	Next
	
End Sub