View Safari page source in an external editor

Jan 19, '11 07:30:00AM

Contributed by: ra5ul

To complement robg's recent hint, here's an AppleScript to view Safari's page source in Emacs.app.

It adds the <base> tag to the <head> and ensures .php files will display as HTML in case you wish to preview the (edited) source.

Here is the AppleScript:

try
 -- external editor
 set editor to "Emacs"
 -- temporary directory (cleaned on reboot)
 set myDir to POSIX path of (path to temporary items from user domain)
 
 -- get name and source
 tell application "Safari"
 tell document 1
  set basehref to do JavaScript "location.href.match(/.+\\//).toString()"
  set myFile to do JavaScript "location.href.match(/[^\\/]+$/) ? location.href.match(/[^\\/]+$/).toString().match(/[^?&]+/).toString() : 'index.html'"
  --bottleneck
  set mySource to source as string
 end tell
 end tell
 
 -- local php file problem
 if myFile ends with ".php" then
 set myFile to myFile & ".html"
 end if
 
 -- unique filename
 set myFile to myDir & "safarisource-" & (do shell script "date +%s") & "-" & myFile
 
 -- insert base href after head; save file
 do shell script "echo " & quoted form of mySource & "| perl -pe 's^^\\n^i' > " & quoted form of myFile
 
 -- open in external editor
 do shell script "open -a " & editor & " " & quoted form of myFile
 
on error errText number errNum
 display dialog errText
end try
It's easy enough to bind the script to a keystroke using a third-party utility. It's equally easy to open the source back up in Safari with the same keystroke. This is what I use in Emacs:
; open in provided app, or Safari, or finally Firefox
(defun open-current-buffer (&optional app)
 "Open current buffer in some APP."
 (interactive)
 (cond (app
 (shell-command (concat "open -a " app " " buffer-file-name)))
 ((string-match "\\/safarisource\\|\\.html$" buffer-file-name)
 (shell-command (concat "open -a safari " buffer-file-name)))
 (t (shell-command (concat "open -a firefox " buffer-file-name)))))

; bind it to cmd-u
(global-set-key [?\s-u] 'open-current-buffer)
Obviously you can substitute your preferred text editor for Emacs. TextEdit users will need to select 'Ignore rich text commands in HTML files' in the Preferences. Other users should be aware that the source lines end in Unix-style newlines, so a conversion may be needed for proper display.

[crarko adds: I haven't tested this one.]

Comments (1)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20110115204624912