Browse files

Rewrite from scratch

  • Loading branch information...
1 parent 33f71c5 commit cde020bdb4caf1c56171574281f791c3766133be Brian Carper committed Oct 22, 2009
Showing with 3,728 additions and 0 deletions.
  1. +29 −0 LICENSE
  2. +67 −0 README
  3. +91 −0 blog/admin.clj
  4. +18 −0 blog/config.clj
  5. +114 −0 blog/db.clj
  6. +86 −0 blog/layout.clj
  7. +33 −0 blog/markdown.clj
  8. +109 −0 blog/pages.clj
  9. +50 −0 blog/rss.clj
  10. +97 −0 blog/server.clj
  11. +24 −0 blog/test.clj
  12. +62 −0 blog/tokyocabinet.clj
  13. +7 −0 blog/user.clj
  14. +49 −0 blog/util.clj
  15. +1,313 −0 deps/showdown.js
  16. +117 −0 public/css/style.css
  17. +41 −0 public/js/editor.js
  18. +19 −0 public/js/jquery.js
  19. +1 −0 public/js/jquery.textarearesizer.compressed.js
  20. +1,313 −0 public/js/showdown.js
  21. +88 −0 public/js/typewatch.js
View
29 LICENSE
@@ -0,0 +1,29 @@
+Rhino
+
+Rhino is copyright Mozilla, released under the GPL 2.0. See http://www.mozilla.org/rhino/
+
+Javascript libraries
+
+See the files in /public/js for their respective creator and license information. All Javascript libraries are open source and re-distributed with permission.
+
+Everything else:
+
+Copyright (c) 2009 Brian Carper (http://briancarper.net)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
View
67 README
@@ -0,0 +1,67 @@
+# cow-blog
+by [Brian Carper](http://briancarper.net/)
+
+Now featuring thread safety!
+
+This is a complete rewrite of my blog engine written in Clojure using Compojure and Tokyo Cabinet. Previous versions of this code were terrible and you should not use them.
+
+## Purpose
+
+This is intended as a working proof-of-concept of a simple website using Compojure. This is a clean rewrite that's close (but not identical) to the code I have been using to run my blog for the past year.
+
+You should **NOT** expect to unpack this code and fire it up and have it work. This code is meant largely as a learning tool or HOWTO for writing a web app in Clojure. You should read the code carefully and understand it. It's only ~700 lines of code and it shouldn't be hard to read through.
+
+Some effort has been made to make this a bit secure but **not much**. Read and understand (and fix) this code before deploying it publicly. Use at your own risk.
+
+## Features
+
+* Post tags, categories, comments
+* Markdown
+* Gravatars
+* RSS
+* Add/edit posts via admin interface
+
+## Dependencies
+
+* [Clojure](http://clojure.org/), [clojure-contrib](http://code.google.com/p/clojure-contrib/), [Compojure](http://github.com/weavejester/compojure) (duh).
+
+* [Tokyo Cabinet](http://1978th.net/tokyocabinet/). You must install the C library (compile it yourself, it's straightforward), then install the Java bindings. Then you have to tell Java where to find everything via `$CLASSPATH` and possibly `LD_LIBRARY_PATH`. Follow the [directions](http://1978th.net/tokyocabinet/javadoc/) closely.
+
+* [Rhino javascript engine](http://www.mozilla.org/rhino/). Download and install it, all you need is `js.jar`.
+
+* JQuery and some JQuery plugins (included in `/public/js`).
+
+* [Showdown](http://attacklab.net/showdown/) JS Markdown library (included in `/deps`); I have slightly edited showdown to include a few extra features and integrate better with my blog. Vanilla Showdown will likely not work.
+
+## TODO
+
+These features are very simple to implement (like, one or two functions each) but I haven't bothered yet; they will show up in he next version.
+
+* Documentation!
+* Better stylesheet.
+* Editing comments, deleting posts/comments (you can do this from the REPL in the meantime)
+* Spam filtering
+* Archives
+* Tag cloud
+
+## Getting started
+
+Make sure Tokyo Cabinet, Showdown, Compojure, and all of the files in `/blog` are on your $CLASSPATH.
+
+Then edit `blog/config.clj`. Then run this in a REPL:
+
+ (.start blog.server/blog-server)
+
+Visit http://localhost:8080 in a browser.
+
+A file `posts.db` will be created to store your data. Start reading `server.clj` to see what's what.
+
+## Bugs
+
+Bugs are a certainty.
+
+For bug reports, feedback, or suggestions, please email me at brian@briancarper.net or open an issue on github.
+
+## LICENSE
+
+See the `LICENSE` file.
View
91 blog/admin.clj
@@ -0,0 +1,91 @@
+(ns blog.admin
+ (:use (compojure.html gen form-helpers)
+ (compojure.http session helpers)
+ (clojure.contrib str-utils)
+ (blog layout config db util)))
+
+(defn login-page []
+ {:title "Login"
+ :body [:div
+ [:h2 "Log in"]
+ (form-to [:post "/admin/login"]
+ [:div
+ (label "username" "Username:")
+ (text-field "username")]
+ [:div
+ (label "password" "Password:")
+ (password-field "password")]
+ [:div.submit
+ (submit-button "Log in")])]})
+
+(defn- generate-user [username password]
+ {:username username :password (sha-256 (str PASSWORD-SALT password))})
+
+(defn- validate-user [username password]
+ (= (generate-user username password) ADMIN-USER))
+
+(defn do-login [username password]
+ (if (validate-user username password)
+ [(flash-assoc :message "Logged in OK.")
+ (session-assoc :username username)
+ (redirect-to "/")]
+ [(flash-assoc :error "Login failed.")
+ (redirect-to "/admin/login")]))
+
+(defn do-logout []
+ [(session-dissoc :username)
+ (redirect-to "/")])
+
+(defn- post-form
+ ([target] (post-form target {}))
+ ([target post]
+ [:div.add-post.markdown
+ [:p "Leave nothing blank!"]
+ [:p "Tags should be comma-separated."]
+ (form-to [:post target]
+ (form-row text-field "title" "Title" (:title post))
+ (form-row text-field "id" "ID" (:id post))
+ (form-row text-field "category" "Category" (:title (:category post)))
+ (form-row text-field "tags" "Tags" (str-join #", " (map :title (:tags post))))
+ (form-row text-area "markdown" "Body" (:markdown post))
+ (submit-row "Submit"))
+ (preview-div)]))
+
+(defn add-post-page []
+ {:title "Add Post"
+ :body (post-form "/admin/do-add-post")})
+
+(defn- validate* [arg]
+ `(when (empty? ~arg)
+ (die "You left '" (str '~arg) "' blank. Try again.")))
+
+(defmacro validate [& args]
+ `(do ~@(map validate* args)))
+
+(defn- post-from-params [ip id title category tags markdown]
+ (validate ip id title category tags markdown)
+ {:id id
+ :title title
+ :markdown markdown
+ :ip ip
+ :category (make-category {:title category})
+ :tags (map #(make-tag {:title %})
+ (re-split #"\s*,\s*" tags))})
+
+(defn do-add-post [& args]
+ (add-post (apply post-from-params args))
+ [(flash-assoc :message "Post added.")
+ (redirect-to "/")])
+
+(defn edit-post-page [id]
+ (if-let [post (get-post id)]
+ {:title "Edit Post"
+ :body (post-form (str "/admin/do-edit-post/" id) post)}
+ [(flash-assoc :error "Post not found.")
+ (redirect-to "/")]))
+
+(defn do-edit-post [old-id & args]
+ (edit-post old-id (apply post-from-params args))
+ [(flash-assoc :message "Post edited.")
+ (redirect-to "/")])
+
View
18 blog/config.clj
@@ -0,0 +1,18 @@
+(ns blog.config)
+
+(def SITE-TITLE "A Clojure Blog (\u03bb)")
+(def SITE-URL "http://localhost:8080")
+(def SITE-DESCRIPTION "Some guy's blog about Clojure.")
+
+(def PUBLIC-DIR "public") ;;CS/JS/images live here. Relative path.
+
+;; For now, only a single admin user can exist, and this is where the login details live.
+;; use blog.admin/generate-user to generate a new user and then put it here.
+;; Below:
+;; username = foo
+;; password = bar
+(def ADMIN-USER {:username "foo"
+ :password "4bdec02a2dd5e6b6e28935bccf9bf4e7e5becce96b7845bee692768f4e4a810"})
+
+;; Change this.
+(def PASSWORD-SALT "K@#$J@$#(FJ@#!$M@#n1NELKDwdjf9wef123krJ@!FKnjef2i#JR@R")
View
114 blog/db.clj
@@ -0,0 +1,114 @@
+(ns blog.db
+ (:use (clojure.contrib def str-utils)
+ (blog util tokyocabinet markdown)))
+
+(defonce posts (make-dataref "posts.db"))
+
+(defn- uuid []
+ (str (java.util.UUID/randomUUID)))
+
+(defn title-to-id [s]
+ (when s
+ (->> s
+ (re-gsub #"\s" "-")
+ (re-gsub #"[^-A-Za-z0-9_]" "")
+ .toLowerCase)))
+
+(defn- with-type [type x]
+ (with-meta x {:type type}))
+
+(defn- valid-id? [id]
+ (re-matches #"^[-A-Za-z0-9_]+$" id))
+
+(defn make-post [post]
+ (if (and (valid-id? (post :id))
+ (not (empty? (post :markdown))))
+ (with-type :post
+ (assoc post
+ :date (or (post :date) (now))
+ :html (markdown-to-html (post :markdown) false)))
+ (die "Invalid post data. You left something blank: " post)))
+
+(defn make-comment [post c]
+ (with-type :comment
+ (assoc c
+ :id (uuid)
+ :post-id (post :id)
+ :date (or (c :date) (now))
+ :html (markdown-to-html (:markdown c) true))))
+
+(defn make-category [cat]
+ (when cat
+ (with-type :category
+ (assoc cat
+ :id (title-to-id (:title cat))))))
+
+(defn make-tag [tag]
+ (when tag
+ (with-type :tag
+ (assoc tag
+ :id (title-to-id (:title tag))))))
+
+(defn all-posts []
+ (reverse (sort-by :date (vals @posts))))
+
+(defn get-post [id]
+ (posts id))
+
+(defn- store-post [post]
+ (dosync (alter posts assoc (post :id) (make-post post))))
+
+(defn add-post [post]
+ (when (get-post (:id post))
+ (die "A post with that ID already exists."))
+ (store-post post))
+
+(defn remove-post [id]
+ (dosync (alter posts dissoc id)))
+
+(defn edit-post [old-id post]
+ (dosync
+ (when (not= old-id (:id post))
+ (remove-post old-id))
+ (store-post post)))
+
+(defn all-categories []
+ (sort-by :name
+ (set (filter identity
+ (map :category (all-posts))))))
+
+(defn get-category [cat]
+ (first (filter #(= (:id %) cat)
+ (all-categories))))
+
+(defn all-tags []
+ (sort-by :name
+ (set (filter identity
+ (mapcat :tags (all-posts))))))
+
+(defn get-tag [tag]
+ (first (filter #(= (:id %) tag)
+ (all-tags))))
+
+(defn all-posts-with-category [category]
+ (filter #(= (:category %) category)
+ (all-posts)))
+
+(defn all-posts-with-tag [tag]
+ (filter #(some #{tag} (:tags %))
+ (all-posts)))
+
+(defn get-comments [post]
+ (sort-by :date (post :comments)))
+
+(defn add-comment [post comment]
+ (dosync
+ (let [id (:id post)
+ post-in-ref (get-post id)]
+ (alter posts assoc id
+ (assoc post-in-ref :comments
+ (conj (:comments post-in-ref)
+ (make-comment post comment)))))))
+
+(defn db-watcher-status []
+ (agent-errors (:watcher ^posts)))
View
86 blog/layout.clj
@@ -0,0 +1,86 @@
+(ns blog.layout
+ (:use (compojure.html gen page-helpers form-helpers)
+ (clojure.contrib pprint)
+ (blog config db util)))
+
+(defn preview-div []
+ [:div
+ [:h4 "Preview"]
+ [:div#preview]])
+
+(defmulti url type)
+
+(defmethod url :tag [tag]
+ (str "/tag/" (tag :id)))
+
+(defmethod url :category [cat]
+ (str "/category/" (cat :id)))
+
+(defmethod url :post [post]
+ (str "/post/" (post :id)))
+
+(defmethod url :default [x]
+ (die "Don't know how to make a url out of a " (type x)))
+
+(defn link [x]
+ (link-to {:class (str (type x) "-link")}
+ (url x)
+ (x :title)))
+
+(defn post-comments-link [post]
+ (when post
+ (link-to (str "/post/" (post :id) "#comments")
+ (cl-format nil "~a Comment~:*~[s~;~:;s~]"
+ (count (post :comments))))))
+
+(defn- nav [admin]
+ [:div.navigation
+ [:ul "Categories"
+ (map #(vector :li (link %)) (all-categories))]
+ [:ul "Tags"
+ (map #(vector :li (link %)) (all-tags))]
+ [:ul "Meta"
+ (comment "TODO"
+ [:li (link-to "/archives" "Archives")]
+ [:li (link-to "/tag-cloud" "Tag Cloud")])
+ [:li (link-to "/rss.xml" "RSS")]]
+ (if admin
+ [:div.admin
+ [:ul "Hello, " admin
+ [:li (link-to "/admin/add-post" "Add Post")]
+ [:li (form-to [:post "/admin/logout"]
+ (submit-button "Log out"))]]
+ [:ul "DB Status: "
+ [:li [:strong (if-let [errors (db-watcher-status)]
+ [:div [:span.error "ERROR!"]
+ [:div errors]]
+ [:span.message "OK"])]]]]
+ [:ul "Log in?"
+ [:li (link-to "/admin/login" "Log in")]])])
+
+(defn messages [flash]
+ (list
+ (when-let [e (:error flash)]
+ [:div.error e])
+ (when-let [m (:message flash)]
+ [:div.message m])))
+
+(defn page [admin title flash session & body]
+ (html
+ [:html
+ [:head
+ [:title SITE-TITLE " - " title]
+ (include-css "/css/style.css")
+ (include-js "/js/combined.js")] ;; magic
+ [:body
+ [:div#page
+ [:div#header [:h1 (link-to SITE-URL SITE-TITLE)]]
+ [:div#nav (nav admin)]
+ [:div#body.body
+ (messages flash)
+ body]
+ [:div#footer
+ "Powered by "
+ (link-to "http://clojure.org" "Clojure") " and "
+ (link-to "http://github.com/weavejester/compojure" "Compojure") " and "
+ (link-to "http://briancarper.net" "Cows") "."]]]]))
View
33 blog/markdown.clj
@@ -0,0 +1,33 @@
+(ns blog.markdown
+ (:use (clojure.contrib str-utils shell-out))
+ (:import (org.mozilla.javascript Context ScriptableObject)))
+
+(defmacro with-tmp-file [[file text] & rest]
+ `(let [tmp# (tempfile)]
+ (try
+ (with-open [f# (java.io.FileWriter. tmp#)]
+ (.append f# ~text))
+ (let [~file (.getAbsolutePath tmp#)]
+ ~@rest)
+ (finally
+ (.delete tmp#)))))
+
+;; NOTE: Edit to point to showdown.js
+
+(defn markdown-to-html [txt safe]
+ (let [cx (Context/enter)
+ scope (.initStandardObjects cx)
+ input (Context/javaToJS txt scope)
+ script (str (slurp "deps/showdown.js")
+ "new Showdown.converter().makeHtml(input, " (if safe "true" "false") ");")]
+ (try
+ (ScriptableObject/putProperty scope "input" input)
+ (let [result (.evaluateString cx scope script "<cmd>" 1 nil)]
+ (Context/toString result))
+ (finally (Context/exit)))))
+
+(comment
+ ;;examples
+ (markdown-to-html "*foo <br/> bar*" false) ; => "<p><em>foo <br/> bar</em></p>"
+ (markdown-to-html "*foo <br/> bar*" true) ; => "<p><em>foo &lt;br/> bar</em></p>"
+ )
View
109 blog/pages.clj
@@ -0,0 +1,109 @@
+(ns blog.pages
+ (:use (clojure.contrib def
+ str-utils
+ pprint)
+ (compojure.html gen page-helpers form-helpers)
+ (compojure.http session helpers)
+ (blog config layout db util)))
+
+(defn- render-post
+ ([admin post] (render-post admin post false))
+ ([admin post front-page?]
+ [:div.post
+ [:h2 (link post)
+ (when admin
+ [:span " [" (link-to (str "/admin/edit-post/" (post :id)) "Edit") "]"])]
+ [:div.post-category
+ "Posted into category " (link (:category post))]
+ [:div.post-body (post :html)]
+ [:div.post-tags "Tags: " (interpose ", " (map link (post :tags)))]
+ [:div.post-meta "Posted " (pretty-date (post :date))]
+ (when front-page?
+ [:div.post-comments-link
+ (post-comments-link post)])
+ ]))
+
+(defn- gravatar [comment]
+ (let [md5 (md5sum (or (:email comment) (:ip comment)))]
+ (str "http://gravatar.com/avatar/" md5 ".jpg?d=identicon")))
+
+(defn- render-comment [admin comment]
+ [:div.comment
+ [:div.comment-gravatar (img {:alt (:author comment)}
+ (gravatar comment))]
+ [:div.comment-content
+ [:h3 "Quoth " (comment :author) ":"
+ (when admin
+ [:span " [" (link-to (str "/admin/edit-comment/" (comment :id)) "Edit") "]"])]
+ [:div.comment-body (comment :html)]
+ [:div.comment-meta (comment :date)]]])
+
+(defn- render-comments [admin post]
+ [:div#comments
+ [:h2 (cl-format nil "~d Comment~:p" (count (get-comments post)))]
+ (map (partial render-comment admin) (get-comments post))])
+
+(defn- comment-form [post]
+ [:div.comment-form
+ [:h2 "Add Comment"]
+ [:div#add-comment
+ (form-to [:post (str "/add-comment/" (post :id))]
+ (form-row text-field "author" "Author")
+ (form-row text-field "email" "Email")
+ (form-row text-field "url" "URL")
+ (form-row text-area "markdown" "Comment")
+ (submit-row "Submit"))
+ (preview-div)]])
+
+(defn- post-list-page
+ ([admin title posts] (post-list-page admin title nil posts))
+ ([admin title subtitle posts]
+ {:title title
+ :body [:div
+ (when subtitle
+ [:h2 subtitle])
+ (map (partial render-post admin) posts)]}))
+
+;; Public pages
+
+(defn do-add-comment [post-id ip author email homepage markdown]
+ (if-let [post (get-post post-id)]
+ (do (add-comment post {:author (escape-html author)
+ :email (escape-html email)
+ :url (escape-html homepage)
+ :markdown markdown
+ :ip ip})
+ [(flash-assoc :message "Comment added.")
+ (redirect-to (url post))])
+ (die "Can't find post " post-id)))
+
+(defn combined-js []
+ (apply str (mapcat #(slurp (str-join "/" [PUBLIC-DIR "js" (str % ".js")]))
+ ["jquery" "typewatch" "showdown" "editor"])))
+
+(defn index-page [admin]
+ {:title "Index"
+ :body [:div
+ (or (map #(render-post admin % true) (all-posts))
+ [:h2 "No posts yet. :("])]})
+
+(defn post-page [admin post-id]
+ (if-let [post (get-post post-id)]
+ {:title (post :title)
+ :body (list
+ (render-post admin post)
+ (render-comments admin post)
+ (comment-form post))}
+ :next))
+
+(defn tag-page [admin tag]
+ (let [tag (get-tag (escape-html tag))
+ title (str "All Posts Tagged '" (:title tag) "'")
+ header (html "All Posts Tagged '" (link tag) "'")]
+ (post-list-page admin title header (all-posts-with-tag tag))))
+
+(defn category-page [admin category]
+ (let [category (get-category (escape-html category))
+ title (str "All Posts in Category '" (:title category) "'")
+ header (html "All Posts in Category '" (link category) "'")]
+ (post-list-page admin title header (all-posts-with-category category))))
View
50 blog/rss.clj
@@ -0,0 +1,50 @@
+(ns blog.rss
+ (:use (compojure.html (gen))
+ (blog config db util layout)))
+
+;; RSS
+
+(defn rss [title site-url description & body]
+ (html "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
+ [:rss {:version "2.0"
+ :xmlns:content "http://purl.org/rss/1.0/modules/content/"
+ :xmlns:wfw "http://wellformedweb.org/CommentAPI/"
+ :xmlns:dc " http://purl.org/dc/elements/1.1/"}
+ [:channel
+ [:title title]
+ [:link site-url]
+
+ [:description description]
+ body]]))
+
+(defn rss-item [post]
+ (html
+ [:item
+ [:title (:title post)]
+ [:link (str SITE-URL (url post))]
+ [:guid (str SITE-URL (url post))]
+ [:pubDate (rfc822-date (:date post))]
+ [:description (escape-html (:html post))]]))
+
+(defn rss-index []
+ (rss
+ SITE-TITLE
+ SITE-URL
+ SITE-DESCRIPTION
+ (map rss-item (take 25 (all-posts)))))
+
+(defn tag-rss [tagname]
+ (if-let [tag (get-tag tagname)]
+ (rss
+ (str SITE-TITLE " Tag: " (:name tag))
+ (str SITE-URL (url tag))
+ SITE-DESCRIPTION
+ (map rss-item (take 25 (all-posts-with-tag tag))))))
+
+(defn category-rss [catname]
+ (if-let [category (get-category catname)]
+ (rss
+ (str SITE-TITLE " Category: " (:name category))
+ (str SITE-URL (url category))
+ SITE-DESCRIPTION
+ (map rss-item (take 25 (all-posts-with-category category))))))
View
97 blog/server.clj
@@ -0,0 +1,97 @@
+(ns blog.server
+ (:use (compojure control)
+ (compojure.server jetty)
+ (compojure.http servlet
+ routes
+ helpers
+ session
+ request
+ middleware)
+ (blog util layout pages user admin rss)))
+
+(defn- admin [session]
+ (:username session))
+
+(defn- ip [request]
+ (or ((:headers request) "x-forwarded-for")
+ (:remote-addr request)))
+
+(defroutes blog-routes
+ (GET "/" (index-page (admin session)))
+ (GET "/post/:id" (post-page (admin session) (:id params)))
+ (GET "/tag/:tag" (tag-page (admin session) (:tag params)))
+ (GET "/category/:category" (category-page (admin session) (:category params)))
+ (GET "/admin/login" (login-page)))
+
+(defroutes form-routes
+ (POST "/admin/login" (do-login (:username params) (:password params)))
+ (POST "/add-comment/:post-id" (:email params)))
+
+(defroutes admin-routes
+ (GET "/admin/add-post" (add-post-page))
+ (GET "/admin/edit-post/:id" (edit-post-page (:id params))))
+
+(defroutes admin-form-routes
+ (POST "/admin/logout" (do-logout))
+ (POST "/admin/do-add-post" (apply do-add-post
+ (ip request)
+ (map params [:id :title :category :tags :markdown])))
+ (POST "/admin/do-edit-post/:old-id" (apply do-edit-post
+ (:old-id params)
+ (ip request)
+ (map params [:id :title :category :tags :markdown]))))
+
+(defroutes static-routes
+ (GET "/rss.xml" (rss-index))
+ (GET "/js/combined.js" (combined-js))
+ (GET "/*" (or (serve-file (:* params)) :next)))
+
+(defroutes error-routes
+ (ANY "/*" [404 "404 - Page not found"]))
+
+;; This is to work around a bug in Compojure
+;; (or a misunderstanding on my part about how Compojure should work)
+;; This prevents NPEs and INTERNAL_SERVER_ERRORS due to with-mimetypes
+;; barfing on requests with no :body (e.g. when file isn't found and
+;; we want to fallthrough to error-routes
+(defn short-circuit [handler]
+ (fn [request]
+ (let [response (handler request)]
+ (when (:body response)
+ response))))
+
+(defn with-layout [handler]
+ (fn [request]
+ (when-let [response (handler request)]
+ (assoc response
+ :headers (merge (:headers response)
+ {"Content-Type" "text/html;charset=UTF-8"})
+ :body (page
+ (admin (:session request))
+ (:title response)
+ (:flash request)
+ (:session request)
+ (:body response))))))
+
+(defn admin-only [handler]
+ (fn [request]
+ (when (admin (:session request))
+ (handler request))))
+
+(decorate blog-routes with-layout with-session)
+(decorate form-routes with-session)
+(decorate admin-routes with-layout admin-only with-session)
+(decorate admin-form-routes admin-only with-session)
+(decorate static-routes with-mimetypes short-circuit) ; FIXME
+
+(defroutes all-routes
+ admin-routes
+ admin-form-routes
+ blog-routes
+ form-routes
+ static-routes
+ error-routes)
+
+(defserver blog-server
+ {:port 8080 :host "localhost"}
+ "/*" (servlet all-routes))
View
24 blog/test.clj
@@ -0,0 +1,24 @@
+(ns blog.test
+ (:use (blog db util)))
+
+(defn stress-test
+ "Create a new dummy post called post-name, then simulate n users simultaneously trying to add comments to it. Tests thread safety. Values of n above 100 cause my computer to die."
+ [post-name n]
+ (remove-post post-name)
+ (add-post {:id post-name :title post-name :markdown "foo" :category (make-category {:title "foo"})})
+ (let [post (get-post post-name)]
+ (dotimes [i n]
+ (let [name (str "Foo" i)]
+ (.start
+ (Thread.
+ (fn []
+ (add-comment post
+ {:author name
+ :email "brian@briancarper.net"
+ :markdown (str "This is some *text* (" i ")")}))))))))
+
+(defn double-stress-test
+ "Run the stress test in parallel on two posts. Tests thread safety."
+ [post-name1 post-name2 n]
+ (.start (Thread. #(stress-test post-name1 n)))
+ (.start (Thread. #(stress-test post-name2 n))))
View
62 blog/tokyocabinet.clj
@@ -0,0 +1,62 @@
+(ns blog.tokyocabinet
+ (:import (tokyocabinet HDB)))
+
+(declare DB)
+
+(defn- bit-or* [& xs]
+ (reduce bit-or xs))
+
+(defmacro with-db [file & body]
+ `(binding [DB (.newInstance HDB)]
+ (try
+ (.open DB ~file (bit-or* HDB/OWRITER HDB/OCREAT HDB/OTSYNC))
+ ~@body
+ (finally (.close DB)))))
+
+(defmethod clojure.core/print-dup java.util.Date [o w]
+ (.write w (str "#=" `(java.util.Date. ~(.getTime o)))))
+
+(defn store [key val]
+ (binding [*print-dup* true]
+ (.put DB (str key) (pr-str val))))
+
+(defn fetch [key]
+ (when-let [s (.get DB (str key))]
+ (read-string s)))
+
+(defn delete [key]
+ (.out DB key))
+
+(defn fetch-keys []
+ (if (.iterinit DB)
+ (doall (take-while identity
+ (repeatedly #(.iternext2 DB))))
+ (throw (Exception. "Failed to acquire iterator."))))
+
+(defn fetch-keyvals []
+ (let [keys (fetch-keys)]
+ (doall
+ (zipmap keys
+ (map fetch keys)))))
+
+(defn- persist
+ "Persists a ref to disk. Slurps the whole DB into memory, compares all the keys, and stores any keys that have been changed. This is very inefficient and can be improved, but it's fast enough for my blog."
+ [a data]
+ (with-db (:file ^data)
+ (let [on-disk (fetch-keyvals)]
+ (doseq [[k _] on-disk]
+ (when-not (@data k)
+ (delete k)))
+ (doseq [[k v] @data]
+ (when-not (= v (on-disk k))
+ (store k v))))))
+
+(defn make-dataref
+ "Make a ref with a watcher agent that will persist any changes to the ref to disk via Tokyo Cabinet."
+ [file]
+ (let [watcher (agent 0)
+ x (ref (with-db file (fetch-keyvals))
+ :meta {:file file :watcher watcher})]
+ (add-watcher x :send-off watcher persist)
+ x))
+
View
7 blog/user.clj
@@ -0,0 +1,7 @@
+(ns blog.user
+ (:use (compojure.http session helpers)
+ (compojure.html gen form-helpers)
+ (blog config util layout)))
+
+
+
View
49 blog/util.clj
@@ -0,0 +1,49 @@
+(ns blog.util
+ (:use (compojure.html gen form-helpers)
+ (clojure.contrib str-utils)))
+
+(defn now []
+ (.getTime (java.util.Calendar/getInstance)))
+
+(defn pretty-date [date]
+ (.format (java.text.SimpleDateFormat. "MMM dd, yyyy")
+ (now)))
+
+(defn rfc822-date [date]
+ (let [f (java.text.SimpleDateFormat. "EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z")]
+ (.format f date)))
+
+(defn timestamp []
+ (pretty-date (now)))
+
+(defn form-row
+ ([f name lab] (form-row f name lab nil))
+ ([f name lab val]
+ [:div
+ (label name (str lab ":"))
+ (f name val)]))
+
+(defn submit-row [lab]
+ [:div.submit
+ (submit-button lab)])
+
+(defn sha-256 [s]
+ (let [md (java.security.MessageDigest/getInstance "SHA-256")]
+ (.update md (.getBytes s))
+ (str-join ""
+ (mapcat #(Integer/toHexString (bit-and 0xff %))
+ (.digest md)))))
+
+(defn die [& xs]
+ (throw (Exception. (apply str xs))))
+
+(defn md5sum [s]
+ (let [md5 (doto (java.security.MessageDigest/getInstance "MD5")
+ (.update (.getBytes (str s))))]
+ (apply str (map #(Integer/toHexString (bit-and 0xFF %))
+ (.digest md5)))))
+
+(defn img
+ ([src] [:img {:src src :alt src}])
+ ([opts src] [:img (merge {:src src :alt src} opts)]))
+
View
1,313 deps/showdown.js
@@ -0,0 +1,1313 @@
+//
+// showdown.js -- A javascript port of Markdown.
+//
+// Copyright (c) 2007 John Fraser.
+//
+// Original Markdown Copyright (c) 2004-2005 John Gruber
+// <http://daringfireball.net/projects/markdown/>
+//
+// Redistributable under a BSD-style open source license.
+// See license.txt for more information.
+//
+// The full source distribution is at:
+//
+// A A L
+// T C A
+// T K B
+//
+// <http://www.attacklab.net/>
+//
+
+//
+// Wherever possible, Showdown is a straight, line-by-line port
+// of the Perl version of Markdown.
+//
+// This is not a normal parser design; it's basically just a
+// series of string substitutions. It's hard to read and
+// maintain this way, but keeping Showdown close to the original
+// design makes it easier to port new features.
+//
+// More importantly, Showdown behaves like markdown.pl in most
+// edge cases. So web applications can do client-side preview
+// in Javascript, and then build identical HTML on the server.
+//
+// This port needs the new RegExp functionality of ECMA 262,
+// 3rd Edition (i.e. Javascript 1.5). Most modern web browsers
+// should do fine. Even with the new regular expression features,
+// We do a lot of work to emulate Perl's regex functionality.
+// The tricky changes in this file mostly have the "attacklab:"
+// label. Major or self-explanatory changes don't.
+//
+// Smart diff tools like Araxis Merge will be able to match up
+// this file with markdown.pl in a useful way. A little tweaking
+// helps: in a copy of markdown.pl, replace "#" with "//" and
+// replace "$text" with "text". Be sure to ignore whitespace
+// and line endings.
+//
+
+
+//
+// Showdown usage:
+//
+// var text = "Markdown *rocks*.";
+//
+// var converter = new Showdown.converter();
+// var html = converter.makeHtml(text);
+//
+// alert(html);
+//
+// Note: move the sample code to the bottom of this
+// file before uncommenting it.
+//
+
+
+//
+// Showdown namespace
+//
+var Showdown = {};
+
+//
+// converter
+//
+// Wraps all "globals" so that the only thing
+// exposed is makeHtml().
+//
+Showdown.converter = function() {
+
+//
+// Globals:
+//
+
+// Global hashes, used by various utility routines
+var g_urls;
+var g_titles;
+var g_html_blocks;
+
+// Used to track when we're inside an ordered or unordered list
+// (see _ProcessListItems() for details):
+var g_list_level = 0;
+
+var SAFE = true;
+
+this.makeHtml = function(text,safe) {
+//
+// Main function. The order in which other subs are called here is
+// essential. Link and image substitutions need to happen before
+// _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a>
+// and <img> tags get encoded.
+//
+
+ if(! text) {
+ return "";
+ }
+ // Clear the global hashes. If we don't clear these, you get conflicts
+ // from other articles when generating a page which contains more than
+ // one article (e.g. an index page that shows the N most recent
+ // articles):
+ g_urls = new Array();
+ g_titles = new Array();
+ g_html_blocks = new Array();
+
+ // attacklab: Replace ~ with ~T
+ // This lets us use tilde as an escape char to avoid md5 hashes
+ // The choice of character is arbitray; anything that isn't
+ // magic in Markdown will work.
+ text = text.replace(/~/g,"~T");
+
+ // attacklab: Replace $ with ~D
+ // RegExp interprets $ as a special character
+ // when it's in a replacement string
+ text = text.replace(/\$/g,"~D");
+
+ SAFE = safe;
+ if(SAFE) {
+ text = text.replace(/</g, '~Q');
+ }
+
+ // Standardize line endings
+ text = text.replace(/\r\n/g,"\n"); // DOS to Unix
+ text = text.replace(/\r/g,"\n"); // Mac to Unix
+
+ // Make sure text begins and ends with a couple of newlines:
+ text = "\n\n" + text + "\n\n";
+
+ // Convert all tabs to spaces.
+ text = _Detab(text);
+
+ // Strip any lines consisting only of spaces and tabs.
+ // This makes subsequent regexen easier to write, because we can
+ // match consecutive blank lines with /\n+/ instead of something
+ // contorted like /[ \t]*\n+/ .
+ text = text.replace(/^[ \t]+$/mg,"");
+
+ // Turn block-level HTML blocks into hash entries
+ text = _HashHTMLBlocks(text);
+
+ // Strip link definitions, store in hashes.
+ text = _StripLinkDefinitions(text);
+
+ text = _RunBlockGamut(text);
+
+ text = _UnescapeSpecialChars(text);
+
+ if(SAFE) {
+ text = text.replace(/~Q/g, "&lt;");
+ }
+
+ // attacklab: Restore dollar signs
+ text = text.replace(/~D/g,"$$");
+
+ // attacklab: Restore tildes
+ text = text.replace(/~T/g,"~");
+
+ return text;
+}
+
+
+var _StripLinkDefinitions = function(text) {
+//
+// Strips link definitions from text, stores the URLs and titles in
+// hash references.
+//
+
+ // Link defs are in the form: ^[id]: url "optional title"
+
+ /*
+ var text = text.replace(/
+ ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
+ [ \t]*
+ \n? // maybe *one* newline
+ [ \t]*
+ <?(\S+?)>? // url = $2
+ [ \t]*
+ \n? // maybe one newline
+ [ \t]*
+ (?:
+ (\n*) // any lines skipped = $3 attacklab: lookbehind removed
+ ["(]
+ (.+?) // title = $4
+ [")]
+ [ \t]*
+ )? // title is optional
+ (?:\n+|$)
+ /gm,
+ function(){...});
+ */
+ var text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?((https?|\/)\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(]([A-Za-z0-9\-\. ]+?)[")][ \t]*)?(?:\n+|\Z)/gm,
+ function (wholeMatch,m1,m2,m3,m4) {
+ m1 = m1.toLowerCase();
+ g_urls[m1] = _EncodeAmpsAndAngles(m2); // Link IDs are case-insensitive
+ if (m3) {
+ // Oops, found blank lines, so it's not a title.
+ // Put back the parenthetical statement we stole.
+ return m3+m4;
+ } else if (m4) {
+ g_titles[m1] = m4.replace(/"/g,"&quot;");
+ }
+
+ // Completely remove the definition from the text
+ return "";
+ }
+ );
+
+ return text;
+}
+
+
+var _HashHTMLBlocks = function(text) {
+ // attacklab: Double up blank lines to reduce lookaround
+ text = text.replace(/\n/g,"\n\n");
+
+ // Hashify HTML blocks:
+ // We only want to do this for block-level HTML tags, such as headers,
+ // lists, and tables. That's because we still want to wrap <p>s around
+ // "paragraphs" that are wrapped in non-block-level tags, such as anchors,
+ // phrase emphasis, and spans. The list of tags we're looking for is
+ // hard-coded:
+ var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"
+ var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"
+
+ // First, look for nested blocks, e.g.:
+ // <div>
+ // <div>
+ // tags for inner block must be indented.
+ // </div>
+ // </div>
+ //
+ // The outermost tags must start at the left margin for this to match, and
+ // the inner nested divs must be indented.
+ // We need to do this before the next, more liberal match, because the next
+ // match will start at the first `<div>` and stop at the first `</div>`.
+
+ // attacklab: This regex can be expensive when it fails.
+ /*
+ var text = text.replace(/
+ ( // save in $1
+ ^ // start of line (with /m)
+ <($block_tags_a) // start tag = $2
+ \b // word break
+ // attacklab: hack around khtml/pcre bug...
+ [^\r]*?\n // any number of lines, minimally matching
+ </\2> // the matching end tag
+ [ \t]* // trailing spaces/tabs
+ (?=\n+) // followed by a newline
+ ) // attacklab: there are sentinel newlines at end of document
+ /gm,function(){...}};
+ */
+ text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b[^\r]*?\n<\/\2>[ \t]*(?=\n+))/gm,hashElement);
+
+ //
+ // Now match more liberally, simply from `\n<tag>` to `</tag>\n`
+ //
+
+ /*
+ var text = text.replace(/
+ ( // save in $1
+ ^ // start of line (with /m)
+ <($block_tags_b) // start tag = $2
+ \b // word break
+ // attacklab: hack around khtml/pcre bug...
+ [^\r]*? // any number of lines, minimally matching
+ .*</\2> // the matching end tag
+ [ \t]* // trailing spaces/tabs
+ (?=\n+) // followed by a newline
+ ) // attacklab: there are sentinel newlines at end of document
+ /gm,function(){...}};
+ */
+ text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\b[^\r]*?.*<\/\2>[ \t]*(?=\n+)\n)/gm,hashElement);
+
+ // Special case just for <hr />. It was easier to make a special case than
+ // to make the other regex more complicated.
+
+ /*
+ text = text.replace(/
+ ( // save in $1
+ \n\n // Starting after a blank line
+ [ ]{0,3}
+ (<(hr) // start tag = $2
+ \b // word break
+ ([^<>])*? //
+ \/?>) // the matching end tag
+ [ \t]*
+ (?=\n{2,}) // followed by a blank line
+ )
+ /g,hashElement);
+ */
+ text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement);
+
+ // Special case for standalone HTML comments:
+
+ /*
+ text = text.replace(/
+ ( // save in $1
+ \n\n // Starting after a blank line
+ [ ]{0,3} // attacklab: g_tab_width - 1
+ <!
+ (--[^\r]*?--\s*)+
+ >
+ [ \t]*
+ (?=\n{2,}) // followed by a blank line
+ )
+ /g,hashElement);
+ */
+ text = text.replace(/(\n\n[ ]{0,3}<!(--[^\r]*?--\s*)+>[ \t]*(?=\n{2,}))/g,hashElement);
+
+ // PHP and ASP-style processor instructions (<?...?> and <%...%>)
+
+ /*
+ text = text.replace(/
+ (?:
+ \n\n // Starting after a blank line
+ )
+ ( // save in $1
+ [ ]{0,3} // attacklab: g_tab_width - 1
+ (?:
+ <([?%]) // $2
+ [^\r]*?
+ \2>
+ )
+ [ \t]*
+ (?=\n{2,}) // followed by a blank line
+ )
+ /g,hashElement);
+ */
+ text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement);
+
+ // attacklab: Undo double lines (see comment at top of this function)
+ text = text.replace(/\n\n/g,"\n");
+ return text;
+}
+
+var hashElement = function(wholeMatch,m1) {
+ var blockText = m1;
+
+ // Undo double lines
+ blockText = blockText.replace(/\n\n/g,"\n");
+ blockText = blockText.replace(/^\n/,"");
+
+ // strip trailing blank lines
+ blockText = blockText.replace(/\n+$/g,"");
+
+ // Replace the element text with a marker ("~KxK" where x is its key)
+ blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n";
+
+ return blockText;
+};
+
+var _RunBlockGamut = function(text) {
+//
+// These are all the transformations that form block-level
+// tags like paragraphs, headers, and list items.
+//
+ text = _DoHeaders(text);
+
+ // Do Horizontal Rules:
+ var key = hashBlock("<hr />");
+ text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key);
+ text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm,key);
+ text = text.replace(/^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$/gm,key);
+
+ text = _DoLists(text);
+ text = _DoCodeBlocks(text);
+ text = _DoBlockQuotes(text);
+
+ // We already ran _HashHTMLBlocks() before, in Markdown(), but that
+ // was to escape raw HTML in the original Markdown source. This time,
+ // we're escaping the markup we've just created, so that we don't wrap
+ // <p> tags around block-level tags.
+ text = _HashHTMLBlocks(text);
+ text = _FormParagraphs(text);
+
+ return text;
+}
+
+
+var _RunSpanGamut = function(text) {
+//
+// These are all the transformations that occur *within* block-level
+// tags like paragraphs, headers, and list items.
+//
+
+ text = _DoCodeSpans(text);
+ text = _EscapeSpecialCharsWithinTagAttributes(text);
+ text = _EncodeBackslashEscapes(text);
+
+ // Process anchor and image tags. Images must come first,
+ // because ![foo][f] looks like an anchor.
+ text = _DoImages(text);
+ text = _DoAnchors(text);
+
+ // Make links out of things like `<http://example.com/>`
+ // Must come after _DoAnchors(), because you can use < and >
+ // delimiters in inline links like [this](<url>).
+ text = _DoAutoLinks(text);
+ text = _EncodeAmpsAndAngles(text);
+ text = _DoItalicsAndBold(text);
+
+ // Do hard breaks:
+ text = text.replace(/ +\n/g," <br />\n");
+
+ return text;
+}
+
+var _EscapeSpecialCharsWithinTagAttributes = function(text) {
+//
+// Within tags -- meaning between < and > -- encode [\ ` * _] so they
+// don't conflict with their use in Markdown for code, italics and strong.
+//
+
+ // Build a regex to find HTML tags and comments. See Friedl's
+ // "Mastering Regular Expressions", 2nd Ed., pp. 200-201.
+ var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
+
+ text = text.replace(regex, function(wholeMatch) {
+ var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`");
+ tag = escapeCharacters(tag,"\\`*_");
+ return tag;
+ });
+
+ return text;
+}
+
+var _DoAnchors = function(text) {
+//
+// Turn Markdown link shortcuts into XHTML <a> tags.
+//
+ //
+ // First, handle reference-style links: [link text] [id]
+ //
+
+ /*
+ text = text.replace(/
+ ( // wrap whole match in $1
+ \[
+ (
+ (?:
+ \[[^\]]*\] // allow brackets nested one level
+ |
+ [^\[] // or anything else
+ )*
+ )
+ \]
+
+ [ ]? // one optional space
+ (?:\n[ ]*)? // one optional newline followed by spaces
+
+ \[
+ (.*?) // id = $3
+ \]
+ )()()()() // pad remaining backreferences
+ /g,_DoAnchors_callback);
+ */
+ text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag);
+
+ //
+ // Next, inline-style links: [link text](url "optional title")
+ //
+
+ /*
+ text = text.replace(/
+ ( // wrap whole match in $1
+ \[
+ (
+ (?:
+ \[[^\]]*\] // allow brackets nested one level
+ |
+ [^\[\]] // or anything else
+ )
+ )
+ \]
+ \( // literal paren
+ [ \t]*
+ () // no id, so leave $3 empty
+ <?(.*?)>? // href = $4
+ [ \t]*
+ ( // $5
+ (['"]) // quote char = $6
+ ([A-Za-z0-9\-\. ]?) // Title = $7
+ \6 // matching quote
+ [ \t]* // ignore any spaces/tabs between closing quote and )
+ )? // title is optional
+ \)
+ )
+ /g,writeAnchorTag);
+ */
+ text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?((https?|\/).+?)>?[ \t]*((['"])([A-Za-z0-9\-\. ]*?)\6[ \t]*)?\))/g,writeAnchorTag);
+
+ //
+ // Last, handle reference-style shortcuts: [link text]
+ // These must come last in case you've also got [link test][1]
+ // or [link test](/foo)
+ //
+
+ /*
+ text = text.replace(/
+ ( // wrap whole match in $1
+ \[
+ ([^\[\]]+) // link text = $2; can't contain '[' or ']'
+ \]
+ )()()()()() // pad rest of backreferences
+ /g, writeAnchorTag);
+ */
+ text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
+
+ return text;
+}
+
+var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
+ if (m7 == undefined) m7 = "";
+ var whole_match = m1;
+ var link_text = m2;
+ var link_id = m3.toLowerCase();
+ var url = m4;
+ var title = m7;
+
+ if (url == "") {
+ if (link_id == "") {
+ // lower-case and turn embedded newlines into spaces
+ link_id = link_text.toLowerCase().replace(/ ?\n/g," ");
+ }
+ url = "#"+link_id;
+
+ if (g_urls[link_id] != undefined) {
+ url = g_urls[link_id];
+ if (g_titles[link_id] != undefined) {
+ title = g_titles[link_id];
+ }
+ }
+ else {
+ if (whole_match.search(/\(\s*\)$/m)>-1) {
+ // Special case for explicit empty url
+ url = "";
+ } else {
+ return whole_match;
+ }
+ }
+ }
+
+ url = encodeURI(escapeCharacters(url,"*_"));
+ var result = "<a href=\"" + url + "\"";
+
+ if (title != "") {
+ title = title.replace(/"/g,"&quot;");
+ title = escapeCharacters(title,"*_");
+ result += " title=\"" + title + "\"";
+ }
+
+ result += ">" + link_text + "</a>";
+
+ return result;
+}
+
+
+var _DoImages = function(text) {
+//
+// Turn Markdown image shortcuts into <img> tags.
+//
+
+ //
+ // First, handle reference-style labeled images: ![alt text][id]
+ //
+
+ /*
+ text = text.replace(/
+ ( // wrap whole match in $1
+ !\[
+ (.*?) // alt text = $2
+ \]
+
+ [ ]? // one optional space
+ (?:\n[ ]*)? // one optional newline followed by spaces
+
+ \[
+ (.*?) // id = $3
+ \]
+ )()()()() // pad rest of backreferences
+ /g,writeImageTag);
+ */
+ text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag);
+
+ //
+ // Next, handle inline images: ![alt text](url "optional title")
+ // Don't forget: encode * and _
+
+ /*
+ text = text.replace(/
+ ( // wrap whole match in $1
+ !\[
+ (.*?) // alt text = $2
+ \]
+ \s? // One optional whitespace character
+ \( // literal paren
+ [ \t]*
+ () // no id, so leave $3 empty
+ <?(\S+?)>? // src url = $4
+ [ \t]*
+ ( // $5
+ (['"]) // quote char = $6
+ (.*?) // title = $7
+ \6 // matching quote
+ [ \t]*
+ )? // title is optional
+ \)
+ )
+ /g,writeImageTag);
+ */
+ text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?((https|\/)\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag);
+
+ return text;
+}
+
+var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) {
+ var whole_match = m1;
+ var alt_text = m2;
+ var link_id = m3.toLowerCase();
+ var url = m4;
+ var title = m7;
+
+ if (!title) title = "";
+
+ if (url == "") {
+ if (link_id == "") {
+ // lower-case and turn embedded newlines into spaces
+ link_id = alt_text.toLowerCase().replace(/ ?\n/g," ");
+ }
+ url = "#"+link_id;
+
+ if (g_urls[link_id] != undefined) {
+ url = g_urls[link_id];
+ if (g_titles[link_id] != undefined) {
+ title = g_titles[link_id];
+ }
+ }
+ else {
+ return whole_match;
+ }
+ }
+
+ alt_text = alt_text.replace(/"/g,"&quot;");
+ url = escapeCharacters(url,"*_");
+ var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
+
+ // attacklab: Markdown.pl adds empty title attributes to images.
+ // Replicate this bug.
+
+ //if (title != "") {
+ title = title.replace(/"/g,"&quot;");
+ title = escapeCharacters(title,"*_");
+ result += " title=\"" + title + "\"";
+ //}
+
+ result += " />";
+
+ return result;
+}
+
+
+var _DoHeaders = function(text) {
+
+ // Setext-style headers:
+ // Header 1
+ // ========
+ //
+ // Header 2
+ // --------
+ //
+ text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
+ function(wholeMatch,m1){return hashBlock("<h1>" + _RunSpanGamut(m1) + "</h1>");});
+
+ text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm,
+ function(matchFound,m1){return hashBlock("<h2>" + _RunSpanGamut(m1) + "</h2>");});
+
+ // atx-style headers:
+ // # Header 1
+ // ## Header 2
+ // ## Header 2 with closing hashes ##
+ // ...
+ // ###### Header 6
+ //
+
+ /*
+ text = text.replace(/
+ ^(\#{1,6}) // $1 = string of #'s
+ [ \t]*
+ (.+?) // $2 = Header text
+ [ \t]*
+ \#* // optional closing #'s (not counted)
+ \n+
+ /gm, function() {...});
+ */
+
+ text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
+ function(wholeMatch,m1,m2) {
+ var h_level = m1.length;
+ return hashBlock("<h" + h_level + ">" + _RunSpanGamut(m2) + "</h" + h_level + ">");
+ });
+
+ return text;
+}
+
+// This declaration keeps Dojo compressor from outputting garbage:
+var _ProcessListItems;
+
+var _DoLists = function(text) {
+//
+// Form HTML ordered (numbered) and unordered (bulleted) lists.
+//
+
+ // attacklab: add sentinel to hack around khtml/safari bug:
+ // http://bugs.webkit.org/show_bug.cgi?id=11231
+ text += "~0";
+
+ // Re-usable pattern to match any entirel ul or ol list:
+
+ /*
+ var whole_list = /
+ ( // $1 = whole list
+ ( // $2
+ [ ]{0,3} // attacklab: g_tab_width - 1
+ ([*+-]|\d+[.]) // $3 = first list item marker
+ [ \t]+
+ )
+ [^\r]+?
+ ( // $4
+ ~0 // sentinel for workaround; should be $
+ |
+ \n{2,}
+ (?=\S)
+ (?! // Negative lookahead for another list item marker
+ [ \t]*
+ (?:[*+-]|\d+[.])[ \t]+
+ )
+ )
+ )/g
+ */
+ var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
+
+ if (g_list_level) {
+ text = text.replace(whole_list,function(wholeMatch,m1,m2) {
+ var list = m1;
+ var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol";
+
+ // Turn double returns into triple returns, so that we can make a
+ // paragraph for the last item in a list, if necessary:
+ list = list.replace(/\n{2,}/g,"\n\n\n");;
+ var result = _ProcessListItems(list);
+
+ // Trim any trailing whitespace, to put the closing `</$list_type>`
+ // up on the preceding line, to get it past the current stupid
+ // HTML block parser. This is a hack to work around the terrible
+ // hack that is the HTML block parser.
+ result = result.replace(/\s+$/,"");
+ result = "<"+list_type+">" + result + "</"+list_type+">\n";
+ return result;
+ });
+ } else {
+ whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
+ text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) {
+ var runup = m1;
+ var list = m2;
+
+ var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol";
+ // Turn double returns into triple returns, so that we can make a
+ // paragraph for the last item in a list, if necessary:
+ var list = list.replace(/\n{2,}/g,"\n\n\n");;
+ var result = _ProcessListItems(list);
+ result = runup + "<"+list_type+">\n" + result + "</"+list_type+">\n";
+ return result;
+ });
+ }
+
+ // attacklab: strip sentinel
+ text = text.replace(/~0/,"");
+
+ return text;
+}
+
+_ProcessListItems = function(list_str) {
+//
+// Process the contents of a single ordered or unordered list, splitting it
+// into individual list items.
+//
+ // The $g_list_level global keeps track of when we're inside a list.
+ // Each time we enter a list, we increment it; when we leave a list,
+ // we decrement. If it's zero, we're not in a list anymore.
+ //
+ // We do this because when we're not inside a list, we want to treat
+ // something like this:
+ //
+ // I recommend upgrading to version
+ // 8. Oops, now this line is treated
+ // as a sub-list.
+ //
+ // As a single paragraph, despite the fact that the second line starts
+ // with a digit-period-space sequence.
+ //
+ // Whereas when we're inside a list (or sub-list), that line will be
+ // treated as the start of a sub-list. What a kludge, huh? This is
+ // an aspect of Markdown's syntax that's hard to parse perfectly
+ // without resorting to mind-reading. Perhaps the solution is to
+ // change the syntax rules such that sub-lists must start with a
+ // starting cardinal number; e.g. "1." or "a.".
+
+ g_list_level++;
+
+ // trim trailing blank lines:
+ list_str = list_str.replace(/\n{2,}$/,"\n");
+
+ // attacklab: add sentinel to emulate \z
+ list_str += "~0";
+
+ /*
+ list_str = list_str.replace(/
+ (\n)? // leading line = $1
+ (^[ \t]*) // leading whitespace = $2
+ ([*+-]|\d+[.]) [ \t]+ // list marker = $3
+ ([^\r]+? // list item text = $4
+ (\n{1,2}))
+ (?= \n* (~0 | \2 ([*+-]|\d+[.]) [ \t]+))
+ /gm, function(){...});
+ */
+ list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
+ function(wholeMatch,m1,m2,m3,m4){
+ var item = m4;
+ var leading_line = m1;
+ var leading_space = m2;
+
+ if (leading_line || (item.search(/\n{2,}/)>-1)) {
+ item = _RunBlockGamut(_Outdent(item));
+ }
+ else {
+ // Recursion for sub-lists:
+ item = _DoLists(_Outdent(item));
+ item = item.replace(/\n$/,""); // chomp(item)
+ item = _RunSpanGamut(item);
+ }
+
+ return "<li>" + item + "</li>\n";
+ }
+ );
+
+ // attacklab: strip sentinel
+ list_str = list_str.replace(/~0/g,"");
+
+ g_list_level--;
+ return list_str;
+}
+
+
+var _DoCodeBlocks = function(text) {
+//
+// Process Markdown `<pre><code>` blocks.
+//
+
+ /*
+ text = text.replace(text,
+ /(?:\n\n|^)
+ ( // $1 = the code block -- one or more lines, starting with a space/tab
+ (?:
+ (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
+ .*\n+
+ )+
+ )
+ (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width
+ /g,function(){...});
+ */
+
+ // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
+ text += "~0";
+
+ text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
+ function(wholeMatch,m1,m2) {
+ var codeblock = m1;
+ var nextChar = m2;
+
+ codeblock = _EncodeCode( _Outdent(codeblock));
+ codeblock = _Detab(codeblock);
+ codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
+ codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
+
+ codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
+
+ return hashBlock(codeblock) + nextChar;
+ }
+ );
+
+ // attacklab: strip sentinel
+ text = text.replace(/~0/,"");
+
+ return text;
+}
+
+var hashBlock = function(text) {
+ text = text.replace(/(^\n+|\n+$)/g,"");
+ return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
+}
+
+
+var _DoCodeSpans = function(text) {
+//
+// * Backtick quotes are used for <code></code> spans.
+//
+// * You can use multiple backticks as the delimiters if you want to
+// include literal backticks in the code span. So, this input:
+//
+// Just type ``foo `bar` baz`` at the prompt.
+//
+// Will translate to:
+//
+// <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
+//
+// There's no arbitrary limit to the number of backticks you
+// can use as delimters. If you need three consecutive backticks
+// in your code, use four for delimiters, etc.
+//
+// * You can use spaces to get literal backticks at the edges:
+//
+// ... type `` `bar` `` ...
+//
+// Turns to:
+//
+// ... type <code>`bar`</code> ...
+//
+
+ /*
+ text = text.replace(/
+ (^|[^\\]) // Character before opening ` can't be a backslash
+ (`+) // $2 = Opening run of `
+ ( // $3 = The code block
+ [^\r]*?
+ [^`] // attacklab: work around lack of lookbehind
+ )
+ \2 // Matching closer
+ (?!`)
+ /gm, function(){...});
+ */
+
+ text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
+ function(wholeMatch,m1,m2,m3,m4) {
+ var c = m3;
+ c = c.replace(/^([ \t]*)/g,""); // leading whitespace
+ c = c.replace(/[ \t]*$/g,""); // trailing whitespace
+ c = _EncodeCode(c);
+ return m1+"<code>"+c+"</code>";
+ });
+
+ return text;
+}
+
+
+var _EncodeCode = function(text) {
+//
+// Encode/escape certain characters inside Markdown code runs.
+// The point is that in code, these characters are literals,
+// and lose their special Markdown meanings.
+//
+ // Encode all ampersands; HTML entities are not
+ // entities within a Markdown code span.
+ text = text.replace(/&/g,"&amp;");
+
+ if(SAFE) {
+ text = text.replace(/~Q/g, '<');
+ }
+
+ // Do the angle bracket song and dance:
+ text = text.replace(/</g,"&lt;");
+ text = text.replace(/>/g,"&gt;");
+
+ // Now, escape characters that are magic in Markdown:
+ text = escapeCharacters(text,"\*_{}[]\\",false);
+
+// jj the line above breaks this:
+//---
+
+//* Item
+
+// 1. Subitem
+
+// special char: *
+//---
+
+ return text;
+}
+
+
+var _DoItalicsAndBold = function(text) {
+
+ // <strong> must go first:
+ text = text.replace(/(^|[^\w*_])(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\2/g,
+ "$1<strong>$3</strong>");
+
+ text = text.replace(/(^|[^\w*_])(\*|_)(?=\S)([^\r]*?\S)\2/g,
+ "$1<em>$3</em>");
+
+ return text;
+}
+
+
+var _DoBlockQuotes = function(text) {
+
+ /*
+ text = text.replace(/
+ ( // Wrap whole match in $1
+ (
+ ^[ \t]*>[ \t]? // '>' at the start of a line
+ .+\n // rest of the first line
+ (.+\n)* // subsequent consecutive lines
+ \n* // blanks
+ )+
+ )
+ /gm, function(){...});
+ */
+
+ text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
+ function(wholeMatch,m1) {
+ var bq = m1;
+
+ // attacklab: hack around Konqueror 3.5.4 bug:
+ // "----------bug".replace(/^-/g,"") == "bug"
+
+ bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting
+
+ // attacklab: clean up hack
+ bq = bq.replace(/~0/g,"");
+
+ bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines
+ bq = _RunBlockGamut(bq); // recurse
+
+ bq = bq.replace(/(^|\n)/g,"$1 ");
+ // These leading spaces screw with <pre> content, so we need to fix that:
+ bq = bq.replace(
+ /(\s*<pre>[^\r]+?<\/pre>)/gm,
+ function(wholeMatch,m1) {
+ var pre = m1;
+ // attacklab: hack around Konqueror 3.5.4 bug:
+ pre = pre.replace(/^ /mg,"~0");
+ pre = pre.replace(/~0/g,"");
+ return pre;
+ });
+
+ return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
+ });
+ return text;
+}
+
+
+var _FormParagraphs = function(text) {
+//
+// Params:
+// $text - string to process with html <p> tags
+//
+
+ // Strip leading and trailing lines:
+ text = text.replace(/^\n+/g,"");
+ text = text.replace(/\n+$/g,"");
+
+ var grafs = text.split(/\n{2,}/g);
+ var grafsOut = new Array();
+
+ //
+ // Wrap <p> tags.
+ //
+ var end = grafs.length;
+ for (var i=0; i<end; i++) {
+ var str = grafs[i];
+
+ // if this is an HTML marker, copy it
+ if (str.search(/~K(\d+)K/g) >= 0) {
+ grafsOut.push(str);
+ }
+ else if (str.search(/\S/) >= 0) {
+ str = _RunSpanGamut(str);
+ str = str.replace(/^([ \t]*)/g,"<p>");
+ str += "</p>"
+ grafsOut.push(str);
+ }
+
+ }
+
+ //
+ // Unhashify HTML blocks
+ //
+ end = grafsOut.length;
+ for (var i=0; i<end; i++) {
+ // if this is a marker for an html block...
+ while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
+ var blockText = g_html_blocks[RegExp.$1];
+ blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs
+ grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText);
+ }
+ }
+
+ return grafsOut.join("\n\n");
+}
+
+
+var _EncodeAmpsAndAngles = function(text) {
+// Smart processing for ampersands and angle brackets that need to be encoded.
+
+ // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
+ // http://bumppo.net/projects/amputator/
+ text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&amp;");
+
+ // Encode naked <'s
+ text = text.replace(/<(?![a-z\/?\$!])/gi,"&lt;");
+
+ return text;
+}
+
+
+var _EncodeBackslashEscapes = function(text) {
+//
+// Parameter: String.
+// Returns: The string, with after processing the following backslash
+// escape sequences.
+//
+
+ // attacklab: The polite way to do this is with the new
+ // escapeCharacters() function:
+ //
+ // text = escapeCharacters(text,"\\",true);
+ // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
+ //
+ // ...but we're sidestepping its use of the (slow) RegExp constructor
+ // as an optimization for Firefox. This function gets called a LOT.
+
+ text = text.replace(/\\(\\)/g,escapeCharacters_callback);
+ text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback);
+ return text;
+}
+
+
+var _DoAutoLinks = function(text) {
+
+ text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"<a href=\"$1\">$1</a>");
+
+ // Email addresses: <address@domain.foo>
+
+ /*
+ text = text.replace(/
+ <
+ (?:mailto:)?
+ (
+ [-.\w]+
+ \@
+ [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
+ )
+ >
+ /gi, _DoAutoLinks_callback());
+ */
+ text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
+ function(wholeMatch,m1) {
+ return _EncodeEmailAddress( _UnescapeSpecialChars(m1) );
+ }
+ );
+
+ return text;
+}
+
+
+var _EncodeEmailAddress = function(addr) {
+//
+// Input: an email address, e.g. "foo@example.com"
+//
+// Output: the email address as a mailto link, with each character
+// of the address encoded as either a decimal or hex entity, in
+// the hopes of foiling most address harvesting spam bots. E.g.:
+//
+// <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
+// x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
+// &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
+//
+// Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
+// mailing list: <http://tinyurl.com/yu7ue>
+//
+
+ // attacklab: why can't javascript speak hex?
+ function char2hex(ch) {
+ var hexDigits = '0123456789ABCDEF';
+ var dec = ch.charCodeAt(0);
+ return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15));
+ }
+
+ var encode = [
+ function(ch){return "&#"+ch.charCodeAt(0)+";";},
+ function(ch){return "&#x"+char2hex(ch)+";";},
+ function(ch){return ch;}
+ ];
+
+ addr = "mailto:" + addr;
+
+ addr = addr.replace(/./g, function(ch) {
+ if (ch == "@") {
+ // this *must* be encoded. I insist.
+ ch = encode[Math.floor(Math.random()*2)](ch);
+ } else if (ch !=":") {
+ // leave ':' alone (to spot mailto: later)
+ var r = Math.random();
+ // roughly 10% raw, 45% hex, 45% dec
+ ch = (
+ r > .9 ? encode[2](ch) :
+ r > .45 ? encode[1](ch) :
+ encode[0](ch)
+ );
+ }
+ return ch;
+ });
+
+ addr = "<a href=\"" + addr + "\">" + addr + "</a>";
+ addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part
+
+ return addr;
+}
+
+
+var _UnescapeSpecialChars = function(text) {
+//
+// Swap back in all the special characters we've hidden.
+//
+ text = text.replace(/~E(\d+)E/g,
+ function(wholeMatch,m1) {
+ var charCodeToReplace = parseInt(m1);
+ return String.fromCharCode(charCodeToReplace);
+ }
+ );
+ return text;
+}
+
+
+var _Outdent = function(text) {
+//
+// Remove one level of line-leading tabs or spaces
+//
+
+ // attacklab: hack around Konqueror 3.5.4 bug:
+ // "----------bug".replace(/^-/g,"") == "bug"
+
+ text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width
+
+ // attacklab: clean up hack
+ text = text.replace(/~0/g,"")
+
+ return text;
+}
+
+var _Detab = function(text) {
+// attacklab: Detab's completely rewritten for speed.
+// In perl we could fix it by anchoring the regexp with \G.
+// In javascript we're less fortunate.
+
+ // expand first n-1 tabs
+ text = text.replace(/\t(?=\t)/g," "); // attacklab: g_tab_width
+
+ // replace the nth with two sentinels
+ text = text.replace(/\t/g,"~A~B");
+
+ // use the sentinel to anchor our regex so it doesn't explode
+ text = text.replace(/~B(.+?)~A/g,
+ function(wholeMatch,m1,m2) {
+ var leadingText = m1;
+ var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width
+
+ // there *must* be a better way to do this:
+ for (var i=0; i<numSpaces; i++) leadingText+=" ";
+
+ return leadingText;
+ }
+ );
+
+ // clean up sentinels
+ text = text.replace(/~A/g," "); // attacklab: g_tab_width
+ text = text.replace(/~B/g,"");
+
+ return text;
+}
+
+
+//
+// attacklab: Utility functions
+//
+
+
+var escapeCharacters = function(text, charsToEscape, afterBackslash) {
+ // First we have to escape the escape characters so that
+ // we can build a character class out of them
+ var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";
+
+ if (afterBackslash) {
+ regexString = "\\\\" + regexString;
+ }
+
+ var regex = new RegExp(regexString,"g");
+ text = text.replace(regex,escapeCharacters_callback);
+
+ return text;
+}
+
+
+var escapeCharacters_callback = function(wholeMatch,m1) {
+ var charCodeToEscape = m1.charCodeAt(0);
+ return "~E"+charCodeToEscape+"E";
+}
+
+} // end of Showdown.converter
View
117 public/css/style.css
@@ -0,0 +1,117 @@
+
+body {
+ font-family: Verdana;
+}
+
+#page {
+ width: 605px;
+ margin: auto;
+}
+
+#header {
+ text-align: center;
+ border-bottom: 1px grey dotted;
+}
+
+#nav {
+ float: right;
+ width: 140px;
+
+}
+
+#nav ul {
+ font-size: 12pt;
+ font-weight: bold;
+ margin: 0;
+ padding: 10px 0;
+}
+
+#nav ul li {
+ font-size: 10pt;
+ font-weight: normal;
+ list-style-type: none;
+ padding: 5px 0 0 10px;
+}
+
+.body {
+ float: left;
+ width: 450px;
+ min-height: 400px;
+ border-right: 1px grey dotted;
+ padding-bottom: 20px;
+}
+
+.post {
+ clear: both;
+ padding-bottom: 20px;
+ padding-right: 10px;
+}
+
+.post-body {
+ padding: 20px;
+}
+
+.post-meta {
+ float: left;
+}
+.post-comments-link {
+ float: right;
+}
+
+
+label {
+ display: block;
+ float: left;
+ text-align: right;
+ width: 100px;
+ padding-right: 5px;
+}
+
+div.submit {
+ padding-left: 105px;
+}
+
+textarea {
+ width: 300px;
+ height: 200px;
+}
+
+div#preview {
+ background: #eee;
+ padding: 5px;
+ margin: 5px;
+ border: 1px dotted grey;
+}
+
+#footer {
+ clear: both;
+ border-top: 1px grey dotted;
+ padding: 10px 0;
+ text-align: center;
+}
+
+.message {
+ color: green;
+}
+
+.error {
+ color: red;
+}
+
+div#comments {
+ border-top: 1px grey dotted;
+ clear: both;
+}
+
+div.comment-gravatar {
+ float: left;
+ width: 80px;
+}
+
+div.comment-content {
+ padding-left: 90px;
+}
+
+.admin {
+ border-top: 1px grey dotted;
+}
View
41 public/js/editor.js
@@ -0,0 +1,41 @@
+var markdown = new Showdown.converter();
+
+function updatePreview() {
+ var mdtext = $("textarea#markdown").val();
+ var htmltext = markdown.makeHtml(mdtext, true);
+ $("div#preview").html(htmltext);
+}
+
+function title_to_id(title) {
+ return title.toLowerCase().replace(/\s/g, '-').replace(/[^-A-Za-z0-9_]/g, '');
+}
+
+var hidden = true;
+$(document).ready(function() {
+ var options = {
+ callback:updatePreview,
+ wait:250, // milliseconds
+ highlight:false, // highlight text on focus
+ enterkey:false, // allow "Enter" to submit data on INPUTs
+ };
+ $("textarea#markdown").typeWatch( options );
+
+ updatePreview();
+
+ $("input#test").focus(function() {
+ if($(this).val() == "<= Type this word") {
+ $(this).val('');
+ }
+ });
+ $("input#test").blur(function() {
+ if($(this).val() == "") {
+ $(this).val("<= Type this word");
+ }
+ });
+
+ $("input#title").blur(function() {
+ var title = $(this).val();
+ $("input#id").val(title_to_id(title));
+ });
+ });
+
View
19 public/js/jquery.js
@@ -0,0 +1,19 @@
+/*
+ * jQuery JavaScript Library v1.3.2
+ * http://jquery.com/
+ *
+ * Copyright (c) 2009 John Resig
+ * Dual licensed under the MIT and GPL licenses.
+ * http://docs.jquery.com/License
+ *
+ * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
+ * Revision: 6246
+ */
+(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},e