2

I know how to count the number of words.

How to count the number of characters in the marked (selected) region?

2
  • 1
    FYI, if you use library Modeline Region (code: modeline-region.el) then you can have the count shown in the mode-line whenever the region is active. Automatically updates as you change the region size.
    – Drew
    Sep 21, 2022 at 22:16
  • 1
    Indeed, my modeline (which is some Doom modeline package thing)was showing it too! I need to pay attention to what Emacs already does for me in front of my eyes... Sep 21, 2022 at 23:05

4 Answers 4

3

The command name count-words is a bit misleading. It shows the number of words. But, it also counts the number of lines and the number of characters.

An output illustration:

Region has 1 line, 51 words, and 280 characters.

1

M-x region-length shows you the number of characters. It does this using:

(abs (- (mark) (point)))
1

At the risk of sounding like an idiot:

(length (buffer-substring-no-properties START END))

If you want to know how many characters it contains, including whatever properties and space they take up, you can leave out the words "no properties".

1

The command shell-command-on-region (bound to M-|) passes the region to the standard input of any shell command you want. The output is sent to the echo area if it is short enough or to a buffer whose name is stored in the variable shell-command-buffer-name (whose value is *Shell Command Output* by default) - or you can call the command with a prefix argument to replace the region by the output of the command.

Since you can use wc from the shell to count (lines, words, characters), you can do that from emacs by selecting the region and then M-| wc. Or to uppercase the region: C-u M-| tr a-z A-Z, or to get an uppercase copy of the region in the output buffer: M-| tr a-z A-Z. You can probably easily come up with a dozen more.

There are emacs equivalents to those and many more and it is often better to use them, but I find M-| to be a useful tool in my toolbox. It lets me use shell commands I know well to do some things that might require some time and effort to research, were I to use native tools.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.