public
Last active

I like to know how many words are in my markdown files.

  • Download Gist
count-words.el
Emacs Lisp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
;; this function is included in modern emacs, but here it is in case you haven't upgraded
 
(defun count-words (start end)
"Count words between START and END.
If called interactively, START and END are normally the start and
end of the buffer; but if the region is active, START and END are
the start and end of the region. Print a message reporting the
number of lines, words, and chars.
 
If called from Lisp, return the number of words between START and
END, without printing any message."
(interactive (list nil nil))
(cond ((not (called-interactively-p 'any))
(let ((words 0))
(save-excursion
(save-restriction
(narrow-to-region start end)
(goto-char (point-min))
(while (forward-word 1)
(setq words (1+ words)))))
words))
((use-region-p)
(call-interactively 'count-words-region))
(t
(count-words--buffer-message))))
wordcount-mode.el
Emacs Lisp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
(defvar wordcount-timer nil
"Timer to kick off word count recomputation.")
 
(defvar wordcount-current-count 0
"The result of the last word count.")
 
(defun wordcount-update-word-count ()
"Recompute the word count."
(setq wordcount-current-count (count-words (point-min) (point-max))))
 
(define-minor-mode wordcount-mode
"Toggle wordcount mode.
With no argument, this command toggles the mode.
A non-null prefix argument turns the mode on.
A null prefix argument turns it off.
 
When enabled, the word count for the current buffer
is displayed in the mode-line."
:init-value nil
:lighter (:eval (format " [%d words]" wordcount-current-count))
(if wordcount-mode
(progn
(set (make-local-variable 'wordcount-current-count)
(count-words (point-min) (point-max)))
(set (make-local-variable 'wordcount-timer)
(run-with-idle-timer 3 't #'wordcount-update-word-count)))
(cancel-timer wordcount-timer)))
 
(add-hook 'markdown-mode-hook (lambda () (wordcount-mode)))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.