Synopsis

I want to bidirectionally open a question in sx after finding it in chrome or open a question in chrome after finding it in sx.

Make a CLI tool to open stackexchange in emacs from the command line

Get the question ID from the url

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
(defun sx-get-appropriate-site-and-id-from-url (url)
  (let* ((question (s-replace-regexp ".*//[^/]+/\\(questions\\|q\\)/[0-9]+/\\([a-z0-9-]+\\).*" "\\2" url))
         (id (s-replace-regexp ".*//[^/]+/\\(questions\\|q\\)/\\([0-9]+\\)" "\\2" url))
         (allsxsites (sx-site-get-api-tokens))
         (suggested
          (cond ((string-match-p "stackoverflow.com" url)
                 "stackoverflow")
                ((string-match-p "serverfault.com" url)
                 "serverfault")
                ((string-match-p "superuser.com" url)
                 "superuser")
                ((string-match-p ".stackexchange.com" url)
                 (s-replace-regexp (concat "^.*//\\([^.]+\\).*") "\\1" url))
                (t
                 "stackoverflow"))))
    (if (string-match-p "/" question)
        (setq question nil))
    (if (-contains? allsxsites suggested)
        (list suggested question id))))

Start sx, given only a URL

1
2
3
4
5
6
(defun sx-from-url (url)
  (interactive (list (read-string-hist "sx url: " (thing-at-point 'url))))
  (cl-multiple-value-bind (site question id)
      (sx-get-appropriate-site-and-id-from-url url)
    (sx-display-question (sx-question-get-question site (string-to-int id)))
    (delete-other-windows)))

Run the interactive command from the terminal

1
ln -sf sp-ic sx-from-url

Demonstration

1
sx-from-url "https://stackoverflow.com/q/4980146"
1
sx-from-url "https://stackoverflow.com/questions/997512/string-representation-of-time-t"

asciinema recording

Copy the URL of the current question from sx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
(defun sx-get-question-url ()
  (if (major-mode-p 'sx-question-mode)
      (save-excursion
        (beginning-of-buffer)
        (call-interactively 'forward-button)
        (get-text-property (point) 'sx-button-copy)
        )))

(defun sx-copy-question-url ()
  (interactive)
  (my/copy (sx-get-question-url)))

(define-key sx-question-mode-map (kbd "w") 'sx-copy-question-url)

Demonstration

asciinema recording

Automate the opening of sx from a copied url

1
2
3
4
http*stackoverflow.com/q*) {
    sx-from-url "$fp"
}
;;

Demonstration

asciinema recording

Nice things

  • Make sx a little prettier
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
(require 'sx-question)
(set-face-background 'sx-question-mode-content-face nil)

(defsetface sx-question-mode-code-block-face
  '((t :foreground "#3f5fa7"
       :background "#2e2e2e"
       :weight bold
       :underline nil))
  "Face for sx code block buttons.")

(define-button-type 'sx-question-mode-code-block
  'action    #'sx-button-edit-this
  'face      'sx-question-mode-code-block-face
  :supertype 'sx-button)