Emacs Lisp: Twitterfy

By Xah Lee. Date: . Last updated: .

Here's a emacs lisp command that shortens text to fit twitter's 140 chars.

(defun xah-twitterfy (*begin *end &optional *to-direction)
  "Shorten words for Twitter 140 char limit on current line or selection.
The conversion direction is automatically determined.

If `universal-argument' is called, ask for conversion direction.

Note: calling this function twice in opposite direction does not necessarily return the origial, because the map is not one-to-one, also the string in the map overlaps.

When called in lisp code, *begin *end are region begin/end positions. *to-direction must be one of the following values:
 'auto
 'shorten
 'lengthen

URL `http://ergoemacs.org/emacs/elisp_twitterfy.html'
Version 2016-08-02"
  (interactive
   (list
    (if (use-region-p) (region-beginning) (line-beginning-position))
    (if (use-region-p) (region-end) (line-end-position))
    (intern
     (if current-prefix-arg
         (ido-completing-read
          "Direction: "
          '( "shorten"  "lengthen")
          "PREDICATE"
          "REQUIRE-MATCH")
       "auto"
       ))))
  (let ((-shorten-map
         [
          [" are " " r "]
          [" are, " " r,"]
          [" you " " u "]
          [" you," " u,"]
          [" you." " u."]
          [" you." " u。"]
          [" to " " 2 "]
          [" your" " ur "]
          [" and " "&"]
          ["because" "cuz"]
          [" at " " @ "]
          [" love " " ♥ "]
          [" one " " 1 "]
          [" two " " 2 "]
          [" three " " 3 "]
          [" four " " 4 "]
          [" zero " " 0 "]
          ["hexadecimal " "hex "]
          [", " ","]
          ["..." "…"]
          [". " "。"]
          ["? " "?"]
          [": " ":"]
          ["! " "!"]]
         ))
    (save-excursion
      (save-restriction
        (narrow-to-region *begin *end)
        (when (string= *to-direction 'auto)
          (goto-char (point-min))
          (if
              (re-search-forward "。\\|,\\|?\\|!" nil "NOERROR")
              (setq *to-direction 'lengthen)
            (setq *to-direction 'shorten)))
        (let ( (case-fold-search nil))
          (mapc
           (lambda (-x)
             (goto-char (point-min))
             (while (search-forward (elt -x 0) nil t)
               (replace-match (elt -x 1) "FIXEDCASE" "LITERAL")))
           (if (string= *to-direction 'shorten)
               -shorten-map
             (mapcar (lambda (-pair) (vector (elt -pair 1) (elt -pair 0))) -shorten-map)))

          (goto-char (point-min))
          (while (search-forward "  " nil t)
            (replace-match " " "FIXEDCASE" "LITERAL"))

          (goto-char (point-min))
          (while (search-forward "  " nil t)
            (replace-match " " "FIXEDCASE" "LITERAL")))))))
Like it? Buy Xah Emacs Tutorial. Thanks.

or, buy something from Best Keyboard for Emacs