aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--sx.el35
-rw-r--r--test/tests.el16
2 files changed, 44 insertions, 7 deletions
diff --git a/sx.el b/sx.el
index a31c0a0..d93719e 100644
--- a/sx.el
+++ b/sx.el
@@ -318,6 +318,41 @@ removed from the display name before it is returned."
(format "[%s]" (car kar)) (cdr kar) string)))
string))
+
+;;; Site
+(defun sx--site (data)
+ "Get the site in which DATA belongs.
+DATA can be a question, answer, comment, or user (or any object
+with a `link' property).
+DATA can also be the link itself."
+ (let ((link (if (stringp data) data
+ (cdr (assoc 'link data)))))
+ (when (stringp link)
+ (replace-regexp-in-string
+ "^https?://\\(?:\\(?1:[^/]+\\)\\.stackexchange\\|\\(?2:[^/]+\\)\\)\\.[^.]+/.*$"
+ "\\1\\2" link))))
+
+(defun sx--ensure-site (data)
+ "Add a `site' property to DATA if it doesn't have one. Return DATA.
+DATA can be a question, answer, comment, or user (or any object
+with a `link' property)."
+ (when data
+ (unless (assq 'site data)
+ (setcdr data (cons (cons 'site (sx--site data))
+ (cdr data))))
+ data))
+
+(defmacro sx-assoc-let (alist &rest body)
+ "Identical to `let-alist', except `.site' has a special meaning.
+If ALIST doesn't have a `site' property, one is created using the
+`link' property."
+ (declare (indent 1) (debug t))
+ (require 'let-alist)
+ `(progn
+ (sx--ensure-site ,alist)
+ ,(macroexpand
+ `(let-alist ,alist ,@body))))
+
(defcustom sx-init-hook nil
"Hook run when SX initializes.
Run after `sx-init--internal-hook'."
diff --git a/test/tests.el b/test/tests.el
index 66d8d88..cc58105 100644
--- a/test/tests.el
+++ b/test/tests.el
@@ -121,14 +121,16 @@
(ert-deftest macro-test--sx-assoc-let ()
"Tests macro expansion for `sx-assoc-let'"
(should
- (equal '(progn (require 'let-alist)
- (sx--ensure-site data)
- (let-alist data .test))
- (macroexpand '(sx-assoc-let data .test))))
+ (equal `(progn (sx--ensure-site data)
+ ,(macroexpand
+ '(let-alist data .test)))
+ (macroexpand
+ '(sx-assoc-let data .test))))
(should
- (equal '(progn (require 'let-alist)
- (sx--ensure-site data)
- (let-alist data (cons .test-one .test-two)))
+ (equal `(progn (sx--ensure-site data)
+ ,(macroexpand
+ '(let-alist data
+ (cons .test-one .test-two))))
(macroexpand
'(sx-assoc-let data (cons .test-one .test-two))))))