--- /dev/null
+;; Copyright (c) 2022 Jakub Czajka <jakub@ekhem.eu.org>
+;; License: GPL-3.0 or later.
+;;
+;; conf-web.el - configuration for eww.
+
+(require 'conf-package)
+
+(use-package eww
+ :bind
+ ("C-c e <RET>" . conf:eww-as-new-buffer)
+ ("C-c eb" . conf:eww-bookmark-browse-with-completion)
+ (:map eww-mode-map
+ ([remap eww-add-bookmark] . conf:eww-add-named-bookmark)
+ ;; `eww' has separate modes for listing cookies. They allow user
+ ;; to remove bookmark/cookie. However, both bind this functionality to `C-k'.
+ ;; I prefer having it bound to `k'.
+ :map eww-bookmark-mode-map
+ ("k" . eww-bookmark-kill)
+ :map url-cookie-mode-map
+ ("k" . url-cookie-delete))
+ :custom
+ ;; Prompt for a directory where the downloaded file should be saved.
+ (eww-download-directory #'conf:eww-download-with-prompt)
+ (eww-browse-url-new-window-is-tab nil)
+ :config
+ (defun conf:eww-as-new-buffer (url)
+ "Like `eww' but opens each page in a new buffer and renames it using page's
+url."
+ (interactive "sURL: ")
+ (with-temp-buffer
+ (eww url)
+ (let* ((url (plist-get eww-data :url))
+ (title (replace-regexp-in-string "^https?://\\|/$" "" url)))
+ (rename-buffer (concat title " | eww")))))
+
+ (defun conf:eww-download-with-prompt ()
+ "Like `eww-download' but prompts for the download directory."
+ (read-directory-name "Directory: " "~/"))
+
+ (defun conf:eww--trim-page-title ()
+ "Returns title of the current page without unnecessary characters."
+ (replace-regexp-in-string "\\` +\\| +\\'" ""
+ (replace-regexp-in-string "[\n\t\r]" " "
+ (plist-get eww-data :title))))
+
+ (defun conf:eww-add-named-bookmark ()
+ "Like `eww-add-bookmark' but doesn't require y-or-n confirmation and prompts
+for name for the bookmark."
+ (interactive nil eww-mode)
+ (eww-read-bookmarks)
+ (dolist (bookmark eww-bookmarks)
+ (when (equal (plist-get eww-data :url) (plist-get bookmark :url))
+ (user-error "Already bookmarked")))
+ (let* ((title (conf:eww--trim-page-title))
+ (name (read-string "Bookmark: " title)))
+ (push (list :url (plist-get eww-data :url)
+ :title name
+ :time (current-time-string))
+ eww-bookmarks)
+ (eww-write-bookmarks)
+ (message "Bookmarked %s (%s)" (plist-get eww-data :url) name)))
+
+ (defun conf:eww--select-bookmark-with-completion ()
+ "Select a bookmark from `eww-bookmarks' using `completion-read'."
+ (eww-read-bookmarks "No bookmarks available")
+ (let* ((bookmarks (mapcar
+ (lambda (bookmark)
+ (plist-get bookmark :title))
+ eww-bookmarks))
+ (title (completing-read "Bookmark: " bookmarks)))
+ (seq-find
+ (lambda (bookmark)
+ (equal (plist-get bookmark :title) title))
+ eww-bookmarks)))
+
+ (defun conf:eww-bookmark-browse-with-completion ()
+ "Open a bookmark from `eww-bookmark' using `completion-read'."
+ (interactive)
+ (eww-read-bookmarks "No bookmarks available")
+ (let* ((bookmark (conf:eww--select-bookmark-with-completion)))
+ (conf:eww-as-new-buffer (plist-get bookmark :url)))))
+
+(provide 'conf-web)