-->

Why does TextEdit open html files as locked?

2019-09-07 19:41发布

问题:

I have an applescript that creates html files and uses textedit to open them:

try
    tell application "Finder" to set save_folder to (target of window 1) as alias
on error
    set save_folder to path to desktop
end try

set textFile to (choose file name with prompt "Enter file name:" default location save_folder default name "Comment.html") as text
if textFile does not end with ".html" then set textFile to textFile & ".html"
do shell script "touch " & quoted form of POSIX path of textFile
tell application "Finder"
    set file type of (textFile as alias) to "html"
    set creator type of (textFile as alias) to "sfri"
end tell
tell application "TextEdit"
    open file textFile
    activate
end tell

The file opens as locked which is a pain. But if i set the filetype and creator to TEXT and ttxt (identifiers for TextEdit) then all is well. I hate to have to give root access to textedit just to edit html files but i guess that's what is needed? I could switch to another text editor I suppose but I am left with the question as to why TextEdit is acting this way with html files?

回答1:

To open empty HTML file without lock:

First solution: check the "Display HTML files as HTML code instead of formatted text" button in TextEdit preferences. But you must write HTML code in the document

--

Second solution: write a valid HTML code for an empty HTML file, like this:

set base to "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"><html><head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><meta http-equiv=\"Content-Style-Type\" content=\"text/css\">
<title></title><meta name=\"Generator\" content=\"Cocoa HTML Writer\"><meta name=\"CocoaVersion\" content=\"1265.21\">
<style type=\"text/css\"></style></head><body></body></HTML>"

try
    tell application "Finder" to set save_folder to (target of window 1) as alias
on error
    set save_folder to path to desktop
end try
set textFile to (choose file name with prompt "Enter file name:" default location save_folder default name "Comment.html") as text
if textFile does not end with ".html" then set textFile to textFile & ".html"
do shell script "printf  " & (quoted form of base) & " > " & quoted form of POSIX path of textFile
tell application "TextEdit"
    open file textFile
    activate
end tell