Skip to content

Instantly share code, notes, and snippets.

@wfarr
Created August 26, 2008 20:12
Show Gist options
  • Save wfarr/7336 to your computer and use it in GitHub Desktop.
Save wfarr/7336 to your computer and use it in GitHub Desktop.
(defun gist-language ()
"Sniffs for the language of the region that is being pasted"
(or (when (boundp 'rails-view-minor-mode) (if rails-view-minor-mode ".rhtml"))
(when (boundp 'rails-minor-mode) (if rails-minor-mode ".rhtml"))
(cdr (assoc major-mode '((c-mode . ".c")
(c++-mode . ".cpp")
(css-mode . ".css")
(diff-mode . ".diff")
(erlang-mode . ".erl")
(haskell-mode . ".hs")
(html-mode . ".html")
(io-mode . ".io")
(java-mode . ".java")
(javascript-mode . ".js")
(jde-mode . ".java")
(js2-mode . ".js")
(lua-mode . ".lua")
(ocaml-mode . ".ml")
(objective-c-mode . ".m")
(perl-mode ".pl")
(php-mode . ".php")
(python-mode . ".sc")
(ruby-mode . ".rbx")
(text-mode . ".txt")
(sql-mode . ".sql")
(scheme-mode . ".scm")
(smalltalk-mode . ".st")
(sh-mode . ".sh")
(xml-mode . ".xml"))))
".txt"))
(defun gist-region (begin end)
"Post the current region as a new gist at gist.github.com.
Copies the URL into the kill ring."
(interactive "r")
(let* ((body-raw (buffer-substring begin end))
(body (replace-regexp-in-string
"[<>&]"
(lambda (match)
(case (string-to-char match)
(?< "&lt;")
(?> "&gt;")
(?& "&amp;")))
body-raw))
;; Adjust as needed.
(mode (gist-language))
(url-request-method "POST")
(url-mime-accept-string "application/xml")
(url-request-extra-headers '(("Content-Type" . "application/xml")))
(url (url-generic-parse-url "http://gist.github.com/gists"))
(url-request-data
(concat "<gistfile1>"
"<file_ext>" mode "</file_ext>"
"<file_contents>" body "</file_contents>"
"</gistfile1>")))
(let ((gist-buffer (url-retrieve-synchronously url)))
(with-current-buffer gist-buffer
(goto-char (point-min))
(search-forward-regexp "^Status: \\([0-9]+.*\\)")
(let ((status (match-string 1)))
(if (string-match "^20[01]" status)
(progn
(goto-char (point-max))
(beginning-of-line)
(let ((id (buffer-substring (point) (point-max))))
(message "Paste created: http://gist.github.com/%s" id)
(kill-new (format "http://gist.github.com/%s" id))))
(message "Error occured: %s" status))))
(kill-buffer gist-buffer))))
(defun gist-buffer ()
"Post the current buffer as a new gist at gist.github.com.
Copies the URL into the kill ring."
(interactive)
(gist-region (point-min) (point-max)))
(provide 'gist)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment