Attribute VB_Name = "Convert2Wiki"
'''#!/usr/bin/python
'''
'''from BeautifulSoup import BeautifulSoup
'''import io
'''import os
'''import re
'''import sys
'''import urllib2
'''
'''
'''# def download_inline_images(text):
'''#     m = re.findall()
'''#     for inline in m:
'''#         print('Downloading ' + inline)
'''#         image = urllib2.urlopen('https://guardianproject.info/wiki/File:' + inline)
'''#         with open(inline, 'w') as f:
'''#             f.write(image.read())
'''
'''def convert_and_save(Title, Text):
'''    contents = 'h1. ' + re.sub('_', ' ', title) + '\n\n'
'''    contents += text
'''
'''    # headers
'''    contents = re.sub('===== (.+?) =====', 'h5. \\1\n', contents)
'''    contents = re.sub('==== (.+?) ====', 'h4. \\1\n', contents)
'''    contents = re.sub('=== (.+?) ===', 'h3. \\1\n', contents)
'''    contents = re.sub('== (.+?) ==', 'h2. \\1\n', contents)
'''    contents = re.sub('= (.+?) =', 'h1. \\1\n', contents)
'''
'''    # fix bullet lists
'''    contents = re.sub('\n\*\*([^ ])', '\n** \\1', contents)
'''    contents = re.sub('\n\*([^ \*])', '\n* \\1', contents)
'''
'''    # bold - needs to be after 'fix bullet lists'
'''    contents = re.sub("'''(.+?)'''", '*\\1*', contents)
'''
'''    # italic
'''    contents = re.sub("''(.+?)''", '_\\1_', contents)
'''
'''    # external links with mistaken double brackets
'''    contents = re.sub('\[\[(http.+?) (.+?)\]\]', '"\\2":\\1', contents)
'''
'''    # external links
'''    contents = re.sub('\[(http.+?) (.+?)\]', '"\\2":\\1', contents)
'''
'''    # inline image links
'''    contents = re.sub('\[\[File:([^|\]]+).*?\]\]', '!\\1!', contents)
'''
'''    # make sure there's a trailing newline
'''    contents += '\n'
'''
'''    filename = re.sub('/', '_', title) + '.redmine'
'''    with io.open(filename, 'w', encoding='utf8') as f:
'''        f.write (contents)
'''
'''
'''def crawl_url(URL):
'''    Page = urllib2.urlopen(URL)
'''    soup = BeautifulSoup(Page)
'''    find = soup.find('textarea')
'''    if not find or len(find) == 0:
'''        Return
'''    textarea = find.contents[0]
'''
'''    m = re.match('.*title=([^&]+)', url)
'''    Title = m.Group(1)
'''    convert_and_save(title, textarea)
'''
'''    m = re.findall('\[\[([^|\]]+)', textarea)
'''    for page in m:
'''        Print 'Trying: ' + page
'''        if not os.path.exists(page + '.redmine') \
'''                and not page.startswith('File:') \
'''                and not page.startswith('http'):
'''            Print 'MATCH: ' + page
'''            crawl_url('https://guardianproject.info/wiki/index.php?title=' + re.sub(' ', '_', page) + '&action=edit')
'''
'''def main(argv):
'''    if len(argv) == 0:
'''        Print "Usage: " + sys.argv; [0] + " [URL]"
'''        Return
'''    if len(argv) == 1:
'''        crawl_url(argv[0])
'''
'''
'''if __name__ == "__main__":
'''    main(sys.argv[1:])


Option Explicit

Sub Word2Wiki()
    
    ClearSonMario
    
    Application.ScreenUpdating = False

    
    'Heading 1 to Heading 5
    ConvertParagraphStyle wdStyleHeading1, vbCr + "h1. ", vbCr, True, True
    ConvertParagraphStyle wdStyleHeading2, vbCr + "h2. ", vbCr, False, False
    ConvertParagraphStyle wdStyleHeading3, vbCr + "h3. ", vbCr, False, False
    ConvertParagraphStyle wdStyleHeading4, vbCr + "h4. ", vbCr, False, False
    ConvertParagraphStyle wdStyleHeading5, vbCr + "h5. ", vbCr, False, False
    
    ConvertItalic
    ConvertBold
    ConvertUnderline
    
    ConvertLists
    ConvertTables
    
    
    WriteInlineShapesToFile
    
    'Aggiungo righe finali
    Selection.EndKey Unit:=wdStory
    
    Selection.InsertAfter vbCr + vbLf
    Selection.InsertAfter "_File:""" + ActiveDocument.Name + """ imported  " + Str(Now) + "_"
    Selection.InsertAfter vbCr + vbLf
    Selection.InsertAfter vbCr + vbLf
    Selection.InsertAfter "{{toc}} "
    Selection.InsertAfter vbCr + vbLf
    Selection.InsertAfter " "
    Selection.InsertAfter vbCr + vbLf
    Selection.InsertAfter "p=. This document contains Information of reserved property for the use of the MEI technical service people only and contain information that is privileged, confidential or exempt from other disclosure under applicable law. All rights reserved. So You must use these information only for the best Use on MEI machine. If you are not the intended recipient, you are notified that any disclosure, printing, copying, distribution or use of the contents is prohibited. If you have received this in error, please notify the sender immediately by telephone or by returning it by reply email and then permanently deleting the communication from your system. Thank you to play correctly."
    Selection.InsertAfter vbCr + vbLf
    Selection.InsertAfter " "
    Selection.InsertAfter vbCr + vbLf
    Selection.InsertAfter "p=. MEI S.r.l.  Via Ing. G. Caproni, 50 - 24036 Ponte San Pietro (BG) Italy - Tel. +39 035 339112 - Fax. +39 035 4378007 - www.meisystem.com - info@meisystem.com - P.IVA 02053210163 - REA BG n. 258933 - Registro Imprese di BG 02053210163 - Cap. Soc. Euro 1.000.000,00 (i.v)"
    Selection.InsertAfter vbCr + vbLf
    Selection.InsertAfter vbCr + vbLf
    Selection.InsertAfter " "
    Selection.InsertAfter vbCr + vbLf

    
    ' Copy to clipboard
    ActiveDocument.Content.Copy
    
    ActiveDocument.SaveAs2 ("c:\Lavori\Redmine\Convert\wiki.txt"), wdFormatDOSText
    Application.ScreenUpdating = True
End Sub
 
 
Private Sub ClearSonMario()
    On Error Resume Next
    ActiveDocument.TablesOfContents(1).Range.Select
    Selection.Delete
    Selection.InsertAfter "{{toc}}"
End Sub
 
 
 
 
Private Sub ConvertParagraphStyle(styleToReplace As WdBuiltinStyle, _
                                    preText As String, _
                                    postText As String, addNum As Boolean, toc As Boolean)
    Dim normalStyle As Style
    Set normalStyle = ActiveDocument.Styles(wdStyleNormal)
    Dim ind As Integer
    
    ActiveDocument.Select
    ind = -1
    With Selection.Find
    
        .ClearFormatting
        .Style = ActiveDocument.Styles(styleToReplace)
        .Text = ""
        
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        
        .Forward = True
        .Wrap = wdFindContinue
        
        Do While .Execute
            With Selection
                If InStr(1, .Text, vbCr) Then
                    ' Just process the chunk before any newline characters
                    ' We'll pick-up the rest with the next search
                    .Collapse
                    .MoveEndUntil vbCr
                End If
                                       
                ' Don't bother to markup newline characters (prevents a loop, as well)
                If Not .Text = vbCr Then
                    ind = ind + 1

                    .InsertBefore preText + IIf(addNum And ind > 0, " " + Str(ind) + " ", "")
                    .InsertAfter postText
                    
                    If (toc And ind <= 0) Then
                        '.InsertAfter vbCr
                        '.InsertAfter "{{toc}} "
                        '.InsertAfter vbCr
                    End If
                End If
                
                .Style = normalStyle
            End With
        Loop
    End With
End Sub

Private Sub ConvertBold()
    ActiveDocument.Select
    
    With Selection.Find
    
        .ClearFormatting
        .Font.Bold = True
        .Text = ""
        
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        
        .Forward = True
        .Wrap = wdFindContinue
        
        Do While .Execute
            With Selection
                If InStr(1, .Text, vbCr) Then
                    ' Just process the chunk before any newline characters
                    ' We'll pick-up the rest with the next search
              .Font.Bold = False
                    .Collapse
                    .MoveEndUntil vbCr
                End If
                                       
                ' Don't bother to markup newline characters (prevents a loop, as well)
                If Not .Text = vbCr Then
                    .InsertBefore "*"
                    .InsertAfter "*"
                End If
                
                .Font.Bold = False
            End With
        Loop
    End With
End Sub
 
Private Sub ConvertItalic()
    ActiveDocument.Select
    
    With Selection.Find
    
        .ClearFormatting
        .Font.Italic = True
        .Text = ""
        
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        
        .Forward = True
        .Wrap = wdFindContinue
        
        Do While .Execute
            With Selection
                If InStr(1, .Text, vbCr) Then
                    ' Just process the chunk before any newline characters
                    ' We'll pick-up the rest with the next search
                    .Font.Italic = False
                    .Collapse
                    .MoveEndUntil vbCr
                End If
                                       
                ' Don't bother to markup newline characters (prevents a loop, as well)
                If Not .Text = vbCr Then
                    .InsertBefore "_"
                    .InsertAfter "_"
                End If
                
                .Font.Italic = False
            End With
        Loop
    End With
End Sub
 
Private Sub ConvertUnderline()
    ActiveDocument.Select
    
    With Selection.Find
    
        .ClearFormatting
        .Font.Underline = True
        .Text = ""
        
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        
        .Forward = True
        .Wrap = wdFindContinue
        
        Do While .Execute
            With Selection
                If InStr(1, .Text, vbCr) Then
                    ' Just process the chunk before any newline characters
                    ' We'll pick-up the rest with the next search
                    .Font.Underline = False
                    .Collapse
                    .MoveEndUntil vbCr
                End If
                                       
                ' Don't bother to markup newline characters (prevents a loop, as well)
                If Not .Text = vbCr Then
                    .InsertBefore "+"
                    .InsertAfter "+"
                End If
                
                .Font.Underline = False
            End With
        Loop
    End With
End Sub
 
Private Sub ConvertLists()


   Exit Sub 'non converto gli elenchi puntati in quanto non viene effettuato correttamente
    
   Dim para As Paragraph
   Dim i As Long
    For Each para In ActiveDocument.ListParagraphs
        With para.Range
            .InsertBefore " "
            For i = 1 To .ListFormat.ListLevelNumber
                If .ListFormat.ListType = wdListBullet Then
                    .InsertBefore "*"
                Else
                    .InsertBefore "#"
                End If
            Next i
            .ListFormat.RemoveNumbers
        End With
    Next para
End Sub
 
Private Sub ConvertTables()

    Dim myRange As Word.Range
    Dim tTable  As Word.Table
    Dim tRow    As Word.Row
    Dim tCell   As Word.Cell
    Dim strText As String
    
    Dim i   As Long
    Dim j   As Long
    Dim k   As Long
    Dim l   As Long
    
    For Each tTable In ActiveDocument.Tables
            
            'Memorize table text
            ReDim x(1 To tTable.Rows.Count, 1 To tTable.Columns.Count)
            i = 0
            For Each tRow In tTable.Rows
                i = i + 1
                j = 0
                For Each tCell In tRow.Cells
                    j = j + 1
                    strText = tCell.Range.Text
                    x(i, j) = Left(strText, Len(strText) - 2)
                Next tCell
            Next tRow
            
            'Delete table and position after table
            Set myRange = tTable.Range
            myRange.Collapse Direction:=wdCollapseEnd
            tTable.Delete
            
            'Rewrite table with memorized text
            myRange.InsertBefore vbCr
            For k = 1 To i
                For l = 1 To j
                    myRange.InsertAfter " | " + x(k, l)
                Next l
                myRange.InsertAfter " | " + vbCr
            Next k
             myRange.InsertAfter vbCr
            
    Next tTable

End Sub


Private Sub WriteInlineShapesToFile()
    Dim docCurrent As Document
    Dim shapeCurrent As InlineShape
    Dim RC As Integer
    Dim vData() As Byte
    Dim i As Long
    Dim lWritePos As Long
    Dim strOutFileName As String
    Dim jpgOutFileName As String
    Dim myRange As Word.Range

    Set docCurrent = ActiveDocument

    i = 0

    For Each shapeCurrent In docCurrent.InlineShapes
        i = i + 1
        Dim strFile As String
        strFile = "image" & CStr(i) & ".bmp"
        
        'Salvo immagini su files
        jpgOutFileName = "c:\Lavori\Redmine\Convert\" & strFile
        shapeCurrent.Range.CopyAsPicture
        'shapeCurrent.Range.CopyAsPicture
        'shapeCurrent.Range.Copy
        SavePicture ClipUtils.PastePicture, jpgOutFileName

'        strOutFileName = "c:\Lavori\Redmine\Convert\datafile" & CStr(i) & ".emf"
'        Open strOutFileName For Binary Access Write As #1
'
'        vData = shapeCurrent.Range.EnhMetaFileBits
'        lWritePos = 1
'        Put #1, lWritePos, vData
'        Close #1
        
        'Inserisco collegamento al file
        Set myRange = shapeCurrent.Range
        myRange.InsertAfter vbCr
        myRange.InsertAfter "!" & strFile & "!"
        myRange.InsertAfter vbCr
    Next shapeCurrent

End Sub


Private Sub WriteHtml()
Attribute WriteHtml.VB_ProcData.VB_Invoke_Func = "Normal.NewMacros.Macro1"
ActiveDocument.SaveAs FileName:="c:\Lavori\Redmine\Convert\Sample.htm", FileFormat:=wdFormatHTML, _
LockComments:=False, Password:="", AddToRecentFiles:=True, WritePassword _
:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _
False
End Sub
