User:TJFrazier/WikiBasic

From Apache OpenOffice Wiki
Jump to: navigation, search

OOo Documentation Wiki Cleanup Extension

Thanks to the kindness and hard work of Andrew Douglas Pitonyak, the code described here is available as an extension on the Documentation website. Look in this folder for the latest version, and click on it to download. Pending a new upload to the new site, email me and I'll send you a copy of the .oxt file directly.

Use the OOo Extension Manager to install it as usual. <toggledisplay showtext="show Extension Manager instructions"> Click on the latest .oxt file to open it.
Depending on your download software and browser, you may have the choice of downloading and saving the file, or opening it directly with OOo Writer. Either will work.

  • With Writer, you will be asked if you want to install this extension. Select OK.
  • Download and save:
  1. After downloading the extension, open OOo and select Tools > Extension Manager.
  2. Select the Add button.
  3. Browse to the file, select it, and select Open.

In either case, remember that the new extension will only show up in a new Writer window. For instance, close and reopen your document. </toggledisplay> You can then run the main macro from the menu chain Tools > Add-Ons > OOoDocWikiCleanup > Tip/Note/Caution.

The remaining macros are available for wiki-markup editing, but access through the menu is not convenient. A toolbar will be available starting with Version 0.0.3 (implemented but not released as of 2010-08-10) released 2010-08-11.

What it does

Before this code is useful, you must:

  1. Download and open a chapter of a Guide from OOAuthors;
  2. Export the chapter with the Sun Wiki Publisher extension, to an ASCII text file;
  3. Load this text file into Writer.

At this point, you are working with a text file in wiki markup, and a substantial amount of cleanup is required.

The tips, notes, and cautions used in OOAuthors Guides are built as tables within Writer. The export process converts these tables to wiki tables. While this is technically correct, what you want is the wiki template form instead. The Cleanup macro converts these specific wiki tables into template calls.

You should run the macro as a first step in the file cleanup, because it reduces the amount of trash you have to deal with. You only need to run it once per file, but it is harmless if you run it again; it will find no tables to convert, and do nothing (as its statistics at the end will show).

The remaining macros may be useful in editing with wiki markup. Most wiki markup consists of brackets, with some text inside. Example: '''Bold''', surrounded by bracketing triple apostrophes, produces Bold. The <nowiki> and <tt> tags are frequently required. The editing macros produce the desired brackets, either around the selected text (if you select some), or with empty spaces in between the brackets, ready to be typed into. This is similar to the way the buttons work in wiki editors.

The Tip, Note, and Caution macros let you create new ones of those, supplying the proper template names and brackets.

Template:Documentation/Note User suggestions for additions or improvements are welcome, on the Talk page.

Code to post-process the output of MediaWiki Export Filter from Sun Wiki Publisher

Version information is embedded in the code, a little way down. If you need an earlier version, use the history tab to find it.

REM  *****  Wiki-related macros  *****
 
Option Explicit
 
Sub TipNoteCautionCleanup
' Cleans up Tips, Notes, and Cautions after "Export to MediaWiki (.txt)" filter
'   from Sun Wiki Publisher extension.
'   Converts wiki tables to wiki template calls.
 
Dim sV as String		'release version
'Dim vLang as Variant	'array of Locale structs
 
sV = "0.2.0"
REM Version notes:
'V 0.2.0: Older versions WILL NOT COMPILE, due to a change in the interface.
'   The 'Anchor' construct is no longer a part of 'Text'.
'   Updated for Sun Wiki Publisher output. Extra 'style=' trash removed.
'   Version notes relocated up top.
'   Language default "always US" set. This is easily user-customizable.
'V 0.1.2: Add file-type check for ".txt" input.
'   Remove all tabs, so wiki version aligns properly.
'	Localize tally message.
'	Make user constant localization easy.
'V 0.1.1: Localized for DE. Also necessary to allow for different
'	structure of Caution/Achtung table (no images in DE).
'V 0.1.0: Released 2009-09-04 to wiki page. All MsgBox constants removed.
'V 0.0.2: More code cleanup. MsgBox constants now for module.
'V 0.0.1: Remove useless error msg for other table. Code cleanup.
'	Tally "other tables", & display.
'	Display version in tally header.
'V 0.0.0 released 2009-01-22 to authors list & JHW.
 
 
Dim oCursor as Variant	'text cursor
Dim oDoc as Object
Dim enum1 as Variant	'paragraph enumeration
Dim enum2 as Variant	'portion enumeration
Dim thisPara as Variant
Dim thisPortion as Variant
Dim bBegin as Boolean	'True if looking for table start
' counters for items found.
Dim iCaution as Integer
Dim iNote as Integer
Dim iTip as Integer
Dim iPara as Integer
Dim iPor as Integer
Dim iTable as Integer	'non-T|N|C tables
Dim ix as Integer		'scratch
 
Dim aNames(2) as String	'names to search for
Const kNote = 0			'subscript enumeration list
Const kTip = 1
Const kCaution = 2
 
Dim sFind as String		'sentinel sought
Dim sISO as String		'language code
Dim sRep as String		'replacement
Dim sText as String		'scratch
 
oDoc = ThisComponent
'oDoc = StarDesktop.CurrentComponent		'Testing bad-file, gives IDE
If TNCBadFile(oDoc, ".txt") Then Exit Sub
'Localize searches
aNames(kNote) = "Note"
aNames(kTip) = "Tip"
aNames(kCaution) = "Caution"
 
'Language locales are not available in txt files ...
'vLang = oDoc.getDocumentLanguages(1, 2)
'sISO = vLang(0).Country
 
' USER LOCALIZE: only one of the following group of lines should be active (not commented out).
' Pick whichever you find convenient.
'sISO = InputBox( "Please input ISO language code", "T/N/C Cleanup ver " & sV, "US") 'ask language
sISO = "US" 	'always US
'sISO = "DE"	'always DE
' End group.
 
If sISO = "DE" then
  aNames(kNote) = "Anmerkung"
  aNames(kTip) = "TIPP"
  aNames(kCaution) = "Achtung"
End If 'DE
' Other languages can be added here, in similar fashion.
' Careful! Some code may be needed to parse differences in the tables.
' See other references to variable sISO.
 
enum1 = oDoc.Text.createEnumeration
bBegin = True
 
While enum1.hasMoreElements
  thisPara = enum1.nextElement
  iPara = iPara + 1
  enum2 = thisPara.createEnumeration
  While enum2.hasMoreElements
    thisPortion = enum2.nextElement
    iPor = iPor + 1
    sText = thisPortion.getString()
    sFind = IIf( bBegin, "{|", "|}" )	'start/end wiki table
    If Mid(sText, 1, len(sFind)) = sFind Then	'found a sentinel
      oCursor = thisPortion.Text.createTextCursorByRange(thisPortion.Start)
      oCursor.gotoEndOfParagraph( True )
      If bBegin Then	'looking for opening delimiter   
        bBegin = False	'next loop, look for closing delimiter
        ' expand selection to include next paragraph and its mark.
        oCursor.goRight( 1, True )	'-> next paragraph
        oCursor.gotoEndOfParagraph( True )
        oCursor.goRight( 1, True )	'include the para mark
        ' the selected string should hold one of the 3 target names.
        ' Set sRep to generate wiki-template names "{{Documentation/whatever"
        ' Code included for possible future localized templates.
        If InStr( oCursor.String, aNames(kNote) ) Then
'	      sRep = aNames(kNote)
	      sRep = "Note"
	      iNote = iNote + 1
        ElseIf InStr( oCursor.String, aNames(kTip) ) Then
'	      sRep = aNames(kTip)
	      sRep = "Tip"
	      iTip = iTip + 1
        ElseIf InStr( oCursor.String, aNames(kCaution) ) Then
'	      sRep = aNames(kCaution)
          sRep = "Caution"
          iCaution = iCaution + 1
          If sISO = "DE" Then
            ' no special action required
          Else
            'kill generated image-related text
            oCursor.goRight( 2, True)				'empty para and into next
            oCursor.gotoEndOfParagraph( True )	'img: <center> para
            oCursor.goRight( 1, True )			'include the para mark
          End If 'Language
        Else	'different kind of wiki table
          sRep = ""
          iTable = iTable + 1
          bBegin = True	'keep looking for beginning, after other table
        EndIf 'NTC or other table found
        If sRep <> "" Then	'we found a Note, Tip, or Caution, so
          ' (1) replace table and trash with template call.
          thisPortion.Text.insertString( oCursor, "{{Documentation/" & sRep, True )
          ' (2) remove possible '| style="xxx"' trash.
          oCursor.collapseToEnd
          oCursor.gotoEndOfParagraph( True )
          If Left( oCursor.String, 9 ) = "| style=""" Then		'found trash
            ix = InStr( oCursor.String, """|" )
            oCursor.goLeft( len(oCursor.String) - ix, True )		'select | sty -> "
            thisPortion.Text.insertString( oCursor, "", True )	'delete trash
          End If 'found trash
        End If 'sRep not empty
      Else 'bBegin = False, found ending delimiter
        oCursor.collapseToEnd
        oCursor.goLeft( 4, True )	'include two para marks
        'replace table-end delimiter with template call delimiter
        thisPortion.Text.insertString( oCursor, "}}", True )
        bBegin = True
      EndIf 'bBegin
    End If 'hit
  Wend			'loop for all portions in this paragraph
Wend		'loop for all paragraphs in document
 
MsgBox "Language code " &sISO & " Processing Complete!" & chr(13) & chr(13) _
  & "Paragraphs - " & str(iPara) & chr(13) _
  & "Portions - " & str(iPor) & chr(13) _
  & aNames(kCaution) & " - " & str(iCaution) & chr(13) _
  & aNames(kNote) & " - " & str(iNote) & chr(13) _
  & aNames(kTip) & " - " & str(iTip) & chr(13) _
  & "Other tables - " & str(iTable) & chr(13) _
  ,, "T|N|C ver " & sV
 
End Sub 'TipNoteCautionCleanup
 
Function TNCBadFile(oDoc as Object, Optional sSuffix as String) as Boolean
Dim sName as String
Dim sURL as String
 
On local error GoTo BadFile
sName = oDoc.ImplementationName
sURL = oDoc.URL
If IsMissing(sSuffix) Then sSuffix = ""
If len(sSuffix) = 0 Then Exit Function
If Right(sUrl, len(sSuffix)) = sSuffix Then Exit Function
 
BadFile:
On error GoTo 0
Dim iAnswer as Integer
iAnswer = MsgBox( "Found this target file:" & chr(13) _
  & "Name: " & sName & chr(13) _
  & "URL: " & sURL & chr(13) _
  & "You probably want to bring the proper file to the foreground, and run the macro again." _
  & chr(13) & chr(13) & "Process this file anyway?" _
  ,MB_YESNO + MB_DEFBUTTON2 + MB_ICONEXCLAMATION, "WRONG FILE?" )
TNCBadFile = (iAnswer <> IDYES) 
End Function 'TNCBadFile
 
'The following code is not used by the TNC process.
 
' Code for pseudo-wiki editing within Writer.
' They work, but lack easy access (like a toolbar). Working on it.
REM V0.0.2 with V0.2.0 of TNC. Added Tip/Note/Caution generator entry points.
REM V0.0.1 with V0.1.2 of TNC. "Source" bracket split up for Syntax Highlighter.
REM V0.0.0 released with V0.0.1 of TNC. No toolbar or buttons yet.
'	Entry points for bold, italics, nowiki, source, and tt.
 
Sub wikiServSub( byVal sBegin as String, Optional byVal sEnd as String )
REM Service routine for entry points which define the brackets.
' If the end bracket is not given, it is the same as the begin.
 
Dim oDoc as Object
Dim oViewCursor as Object
Dim bEmpty as Boolean
Dim iLF as Integer
Dim sTarget as String
 
If IsMissing( sEnd ) Then sEnd = sBegin
 
oDoc = ThisComponent
' get the current cursor position in the GUI.
oViewCursor = oDoc.getCurrentController().getViewCursor()
sTarget = oViewCursor.getString()	'fetch user selection, if any
bEmpty = (sTarget = "")
If bEmpty Then sTarget = "   "
iLF = InStr( sTarget, chr(10) )	'Remove artifact line feeds
Do While iLF
  Mid( sTarget, iLF, 1, "" )
  iLF = InStr( sTarget, chr(10) )
Loop 'for all line feeds
oViewCursor.setString( sBegin & sTarget & sEnd )		'set result
' un-select the insertion.
If bEmpty Then	'select the spaces
  oViewCursor.collapseToStart
  oViewCursor.goRight( len(sBegin), False )
  oViewCursor.goRight( len(sTarget), True )
Else	'select nothing
  oViewCursor.collapseToEnd
End If 'user selection was empty
End Sub 'wikiServSub
 
Sub wikiServTNC( sName as String )
  call wikiServSub( "{{Documentation/" & sName & "|", "}}" )
End Sub 'wikiServTNC
 
'--------------------------------
' Entry points for wiki editing.
 
Sub WikiBold
  call wikiServSub( "'''" )
End Sub 'WikiBold
 
Sub WikiCaution
  call wikiServTNC( "Caution" )
End Sub 'WikiCaution
 
Sub WikiItalics
  call wikiServSub( "''" )
End Sub 'WikiItalics
 
Sub WikiNote
  call wikiServTNC( "Note" )
End Sub 'WikiNote
 
Sub WikiNowiki
  call wikiServSub( "<nowiki>", "</nowiki>" )
End Sub 'WikiNowiki
 
Sub WikiSource
' call wikiServSub( "\n<" & "source lang=oobas>\n", _
'   "\n<" & "/source>\n" )	'fails, "\n" ignored
  call wikiServSub( chr(13) & "<" & "source lang=""oobas"">" & chr(13), _
    chr(13) & "<" & "/source>" & chr(13) )
End Sub 'WikiSource
 
Sub WikiTip
  call wikiServTNC( "Tip" )
End Sub 'WikiTip
 
Sub WikiTT
  call wikiServSub( "<tt>", "</tt>" )
End Sub 'WikiTT

Usage Instructions

Here the basic instructions how to use the above code AFAIR (which are standard instructions on using external Macro code in OOo[1]):

Installing the macro

You must choose where to store the macros. If the macros are frequently used, perhaps they can be stored in the Standard Library. My recommendation, however, is that they be stored in a specific library. Perhaps I will name the library TJLib.
  1. Use Tools > Macros > Organize Macros > OpenOffice.org Basic to open the OOo Basic Macros dialog.
  2. Click the organizer button to open the macro organizer.
  3. Click on the Libraries tab.
  4. Make certain that the Location drop-down displays "My Macros & Dialogs".
  5. Click the New button. For the library name, use TJLib (or pick a more appropriate name).
  6. Click the Modules tab.
  7. Select TJLib and expand the entries. There should be a module shown as "Module1".
    In the unlikely event that it does not exist, Select TJLib and click on New and create Module1.
  8. Select Module1 in the TJLib and click Edit to open the Basic IDE.
  9. In the Basic IDE, copy all of TJ's code and replace what ever is already in the IDE.

Running the macro

There is more than one way to run the macro. Press F5 to run the macro. You can also click on the "Run Basic" button in the toolbar. A good idea is to assign a shortcut key to accelerate later performance.
When you then use WikiPublisher to obtain a .txt file with all the wiki markup, you have to open this file with OOo writer, just run the Macro by using the shortcut key, and save the file (as .txt) again or copy its contents and paste it into the wiki page editor.

References

  1. see Getting Started with Macros
Content on this page is licensed under the Public Documentation License (PDL).
Personal tools