AppleScript filename: AppleScriptPublisher.scpt
[Description:] This is a sample description.
--
--        • English translation of original Japanese version (see below) •
--
--        Purpose:
--                Creates an HTML page that displays (pretty-prints) a "target" script,
--                with a link at the bottom that opens the script in the system’s default
--                AppleScript editor.
--
--        Usage:
--                First, save this script as an application, e.g. named "AppleScriptPublisher".
--                To create the HTML code for a target script, use Script Editor to open the script.
--                Then run "AppleScriptPublisher", and it’ll take the frontmost window’s script and write a
--                .html file next to the place where the target script is stored.
--
--                Note: If you simply run this Publisher script, it’s see itself as the front window
--                and thus will create an html page of itself.
--
--                Another trick is to open this script and your target script, and leave the Publisher
--                script in the background, and then click its Run button with the cmd key held
--                down - that will keep the Publisher script in the background so that your
--                target script will be used to generate the HTML file.
--
--        Name: AppleScriptPublisher
--        Version: v19 (EN)
--
--        Created by: Takaaki Naganoya
--        Created on: 2014/11/09
--        Last modified on: 2021/11/07
--
--        Original version in Japanese: http://piyocast.com/as/archives/13805
--        Minor changes for translation into English language
--        by Edward Mendelson and Thomas Tempelmann (TT) 2022/11/13
--        See also: https://forum.latenightsw.com/t//4021/8
--
--        Copyright © 2006-2021 Piyomaru Software, All Rights Reserved
--
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property quotChar : string id 34

-- default colors - see changeColor() below where they get changed based on the script’s type (JS or AS)
property headerCol : "0000CC" --"0000CC" -- Header (dark)
property bodyBackCol : "EEFFFF" --"EEFFFF" -- Script body base (light color)
property footerCol : "66FFFF" --"66FFFF" -- Script Link Part

on run
        set pName to "com.apple.ScriptEditor2" -- Apple’s Script Editor
        
--set pName to "com.latenightsw.ScriptDebugger7" -- Script Debugger 7 (gives an error when run)
        
--set pName to "com.latenightsw.ScriptDebugger8" -- Script Debugger 8 (not tested)
        
        
using terms from application "Script Editor"
                tell application id pName
                        if (count every document) = 0 then
                                display dialog "Run this “AppleScriptPublisher” script with the target script open and frontmost in Script Editor." buttons {"OK"} default button 1 with icon 1
                                
return
                        end if
                        
                        
set aP to path of front document
                        
if aP = "" then
                                display dialog "Save the target script first, so that AppleScriptPublisher knows where to place the html file next to it." buttons {"OK"} default button 1 with icon 1
                                
return
                        end if
                        
                        
tell front document
                                set aInfo to properties
                                
set curLang to name of language of aInfo -- Get the name of the current OSA language
                        end tell
                        
                        
-- Change the color set based on the OSA Language name
                        
changeColor(curLang) of me
                        
                        
set c to name of front document
                        
                        
set aF to retMacOSpathList(aP) of me
                        
set htmlFilePath to retHTMLpath(aF) of me
                        
                        
set contText to contents of front document
                        
set encText to makeEncodedScript(contText) of me
                        
                        
set newLinkText to "applescript://com.apple.scripteditor?action=new&script=" & encText
                        
--set insLinkText to "applescript://com.apple.scripteditor?action=insert&script=" & encText
                        
--set apndLinkText to "applescript://com.apple.scripteditor?action=append&script=" & encText
                        
                        
set comText to description of front document
                        
                        
set textList to every attribute run of front document
                        
set textList_ref to a reference to textList
                        
                        
set colorList to color of every attribute run of front document
                        
set colorList_ref to a reference to colorList
                        
                        
set aTest to contents of item 2 of textList
                        
set asciiTest to id of aTest
                end tell
        end using terms from
        
        
set tabChar to string id 9
        
        
set indentString to "    "
        
        
set TIDsList to {{"\\", ""}, {"’", "’"}, {"&", "&amp;"}, {">", "&gt;"}, {"<", "&lt;"}, {"        ", indentString & indentString}, {string id 13, string id 10}, {string id 13, "<br>"}, {string id 10, "<br>"}, {"\"", "&quot;"}}
        
--set TIDsList to {{"&", "&amp;"}, {">", "&gt;"}, {"<", "&lt;"}, {"¥"", "&quot;"}}
        
        
set TIDsList_ref to a reference to TIDsList
        
        
set dataOut to {}
        
set dataOut_ref to a reference to dataOut
        
        
set iCounter to 1
        
repeat with i in textList_ref
                set j to contents of i
                
                
set curDelim to AppleScript’s text item delimiters
                
repeat with eachItem in TIDsList_ref
                        set AppleScript’s text item delimiters to contents of item 1 of eachItem
                        
set j to every text item of j
                        
set AppleScript’s text item delimiters to contents of item 2 of eachItem
                        
set j to j as string
                end repeat
                
set AppleScript’s text item delimiters to curDelim
                
                
set cText to RBG2HTML(item iCounter of colorList_ref) of me
                
                
set the end of dataOut_ref to "<font color=" & cText & ">" & j & "</font>"
                
set iCounter to iCounter + 1
        end repeat
        
        
set headString to "<head>" & return & "<meta charset=" & quotChar & "utf-8" & quotChar & ">" & return & "<style> body { font-family: " & quotChar & "Arial" & quotChar & ", sans-serif; } </style>" & return & "</head>" & return
        
        
set htmlHeader to headString & "<table width=" & quotChar & "100%" & quotChar & " border=" & quotChar & "0" & quotChar & "cellspacing=" & quotChar & "2" & quotChar & " cellpadding=" & quotChar & "2" & quotChar & ">
<tr>
<td bgcolor=\"#" & headerCol & "\"><font color=" & quotChar & "#FFFFFF" & quotChar & ">" & curLang & " filename: " & c
        
        
if comText is not equal to "" then
                set comText to "<br><font size=" & quotChar & "2" & quotChar & "> [Description:] " & comText & "</font><br>"
        end if
        
        
set htmlHeader2 to "</font></td>
</tr>
<tr>
<td bgcolor=\"#" & bodyBackCol & "\"><font size=\"3\">"
        
        
set htmlFooter1 to "</font></td>
</tr>
<tr>
<td bgcolor=\"#" & footerCol & "\"><p><font size=\"2\"><a href=\"" & newLinkText & "\">•• Click here to open this Script on your Mac ••</a> </font></p>
</td>
</tr>
</table>
"

        
        
set dataText to htmlHeader & comText & htmlHeader2 & (dataOut as text) & htmlFooter1
        
set dataText to dataText as Unicode text
        
        
--set dDir to (path to desktop as text) & "index.html"
        
--write_to_file(dataText, htmlFilePath, false) of me
        
--saveInEncoding(dataText, htmlFilePath, "UTF8") of me --UTF8
        
my write_to_file_Safely(dataText, htmlFilePath)
        
        
set htmlPosixPath to POSIX path of htmlFilePath
        
set button to display dialog "A HTML file has been created in the same folder as the script file:" & return & return & htmlPosixPath buttons {"Cancel", "Reveal", "Open"} default button 3 with icon 1
        
if button returned of button is "Reveal" then
                tell application "Finder"
                        select htmlFilePath as alias
                        
activate
                end tell
        else if button returned of button is "Open" then
                open location "file:///" & htmlPosixPath
                
return
        end if
        
end run -- script is finished

on retHTMLpath(aF)
        tell application "Finder"
                --set aF to retMacOSpathList(aP) of me
                
set afA to aF as alias
                
set aInfo to info for afA
                
set aExt to name extension of afA
                
                
set aFileName to name of afA
                
set aFileName to aFileName as text
                
set aFileName to aFileName as Unicode text
                
                
set aFileName_rev to reverse of (every character of aFileName) as text
                
set parentF to ((parent of afA) as alias) as text
                
set htmlFileName to name of afA
                
set htmlFileName to htmlFileName as text
                
set htmlFileName to htmlFileName as Unicode text
                
                
if aExt is not equal to "" then
                        set htmlFileNameText to ((reverse of (items ((length of aExt) + 2) thru -1 of aFileName_rev)) as text) & ".html"
                else
                        set htmlFileNameText to (aFileName as text) & ".html"
                end if
                
set htmlFileNameFullPath to parentF & htmlFileNameText
        end tell
        
return htmlFileNameFullPath
end retHTMLpath

on makeEncodedScript(contText)
        (*

        set aList to every paragraph of contText
        set aClass to class of aList
        if aClass = list then
                set aLen to length of aList
        else
                set aLen to 1
        end if
        
        set aaList to {}
        
        set delim to AppleScript’s text item delimiters
        set AppleScript’s text item delimiters to "//piyomaru_replacement_temp//"
        set bList to aList as text
        set AppleScript’s text item delimiters to delim
        
        set aaList to (encodeURL(bList) of me) as Unicode text
        
        set search_string to "//piyomaru_replacement_temp//" as Unicode text
        set replacement_string to "%0A" as Unicode text
set bList to replace_chars(aaList, search_string, replacement_string) of me
*)

        
        
set aaList to (encodeURL(contText) of me) as Unicode text
        
        
return aaList
end makeEncodedScript

-- Convert RGB values to HTML color specifications
on RBG2HTML(RGB_values)
        -- NOTE: this sub-routine expects the RBG values to be from 0 to 65536
        
set the hex_list to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}
        
set the the hex_value to ""
        
repeat with i from 1 to the count of the RGB_values
                set this_value to (item i of the RGB_values) div 256
                
if this_value is 256 then set this_value to 255
                
set x to item ((this_value div 16) + 1) of the hex_list
                
set y to item (((this_value / 16 mod 1) * 16) + 1) of the hex_list
                
set the hex_value to (the hex_value & x & y) as string
        end repeat
        
return ("#" & the hex_value) as string
end RBG2HTML

-- Write file safely, using a tmp path
on write_to_file_Safely(this_data, target_file)
        global pName
        
tell application id pName
                set finalPath to target_file
                
                
-- Export once to a temporary folder and navigate to the target path        
                
set tmpFol to path to temporary items from system domain
                
set tmpName to do shell script "date +%Y%m%d%H%M%S"
                
set tmpPath to (tmpFol as string) & tmpName
                
                
-- Export file to temporary path
                
try
                        set the target_file to the tmpPath as text
                        
set this_data to this_data as Unicode text
                        
                        
set the open_target_file to open for access file target_file with write permission
                        
set eof of the open_target_file to 0 --always overwrite modenot append
                        
write this_data to the open_target_file starting at eof as «class utf8»
                        
close access the open_target_file
                        
                on error error_message
                        try
                                close access file target_file
                        end try
                        
return error_message
                end try
                
                
-- Move files
                
set tFilePOSIX to quoted form of POSIX path of target_file
                
set fPathPOSIX to quoted form of POSIX path of finalPath
                
set sText to "mv " & tFilePOSIX & " " & fPathPOSIX
                
try
                        do shell script sText
                on error error_message
                        return error_message
                end try
                
                
return true
        end tell
end write_to_file_Safely

(* -- emendelson - not used
on replace_chars(this_text, search_string, replacement_string)
        set AppleScript’s text item delimiters to the search_string
        set the item_list to every text item of this_text
        set AppleScript’s text item delimiters to the replacement_string
        set this_text to the item_list as string
        set AppleScript’s text item delimiters to ""
        return this_text
end replace_chars
*)


on encodeURL(origStr as string)
        set aStr to current application’s NSString’s stringWithString:origStr
        
set encodedStr to aStr’s stringByAddingPercentEncodingWithAllowedCharacters:(current application’s NSCharacterSet’s alphanumericCharacterSet())
        
return encodedStr as string
end encodeURL

on retMacOSpathList(aFile)
        set aPath to POSIX file aFile
        
set aPath to aPath as alias
        
set aPath to aPath as string
        
set aPath to aPath as Unicode text
        
set aliasFileList to aPath
        
return aliasFileList
end retMacOSpathList

(* TT - not used
-- Append file routine "write_to_file"
-- Append data, file to be appended, boolean (appended with true)
on write_to_file(this_data, target_file, append_data)
        global pName
        tell application id pName
                try
                        set the target_file to the target_file as text
                        set the open_target_file to open for access file target_file with write permission
                        if append_data is false then set eof of the open_target_file to 0
                        write this_data to the open_target_file starting at eof
                        close access the open_target_file
                        return true
                on error error_message
                        try
                                close access file target_file
                        end try
                        return error_message
                end try
        end tell
end write_to_file
*)


on changeColor(aLang)
        if aLang = "AppleScript" then
                set headerCol to "0000CC" --"0000CC" -- Header (dark)
                
set bodyBackCol to "EEFFFF" --"EEFFFF" -- Script body base (light color)
                
set footerCol to "66FFFF" --"66FFFF" -- Script Link Part
                
        else if aLang = "JavaScript" then
                set headerCol to "804000" --"0000CC" -- Header (dark)
                
set bodyBackCol to "E2D3D3" --"EEFFFF" -- Script body base (light color)
                
set footerCol to "E7AC53" --"66FFFF" -- Script Link Part
        end if
end changeColor

•• Click here to open this Script on your Mac ••