📜 ⬆️ ⬇️

Convert long links to short

A small script to bring the URL in the email to a decent view. Works through the bit.ly service.

The interface is represented by the function short-url-dwim. If it is called when the cursor is over the URL (a protocol is required), then the URL is replaced with a short link. In another case, you will be prompted to enter the URL in the minibuffer, a short link will be inserted in place of the cursor.
Error messages are displayed in the minibuffer.

Script code:


(defvar short-url-user "emacsshorturl")
(defvar short-url-apiKey "R_ac13b2e481b5a73db361ddfa1430fef5")

(defun short-url (url place-url)
(unless url (error "Url is nil"))
(let ((reply (replace-regexp-in-string
"\n" ""
(shell-command-to-string
(concat "curl --url \"api.bit.ly/shorten\" -F version=\"2.0.1\" -F"
"longUrl=\"" url "\""
" -F login=\"" short-url-user
"\" -F apiKey=\"" short-url-apiKey
"\" 2> /dev/null")))))
(when (string-match ".*\"errorMessage\": \"\\([^\"]+\\)\".*" reply)
(error (concat
"ERROR: "
(replace-regexp-in-string
".*\"errorMessage\": \"\\([^\"]+\\)\".*"
"\\1" reply))))
(let ((shortUrl (replace-regexp-in-string
".*\"shortUrl\": \"\\([^\"]*\\)\".*"
"\\1" reply)))
(when place-url
(delete-region (car place-url) (cdr place-url)))
(insert shortUrl))))

(defun short-url-dwim ()
(interactive)
(let ((bounds-url (bounds-of-thing-at-point 'url)))
(if bounds-url
(short-url (thing-at-point 'url) bounds-url)
(short-url-user-url (read-from-minibuffer "URL: ")))))

(provide 'short-url)

Installation and Setup


The code must be placed in a file with the name "short-url.el" in your load-path folder. Next in .emacs put the following code:

(require 'short-url)

I highly recommend registering at bit.ly and setting up a script for your account. There are at least 2 reasons for this:

To do this, add the following in .emacs:
')
(setq short-url-user < >)
(setq short-url-apiKey < apiKey>)

Source: https://habr.com/ru/post/63995/


All Articles