ELisp: Get Buffer String

By Xah Lee. Date: . Last updated: .

Get String from Region

Grab text of given begin/end positions.

;; return string between position 3 to 99
(buffer-substring-no-properties 3 99)
(buffer-substring-no-properties (region-beginning) (region-end))

[see ELisp: Mark, Region, Active Region]

Get Current Word

;; return the word under cursor
(current-word)
;; usually includes lowline _ hyphen - , but really depends on current syntax table

;; return the word cursor is on, usually not including underscore _
(current-word t t)

Exactly what characters is considered a part of word depends on current buffer's syntax table. e.g. whether low line _ or hyphen - count as part of word.

Here's how to control exactly the sequence of string you want. Suppose, you want any letter A to Z, a to z, 0 to 9, and including LOW LINE _, but exclude HYPHEN-MINUS -.

(defun my-get-word ()
  "print the word under cursor.
Word here is any A to Z, a to z, and low line _"
  (interactive)
  (let (
        p1
        p2
        (case-fold-search t))
    (save-excursion
      (skip-chars-backward "_a-z0-9" )
      (setq p1 (point))
      (skip-chars-forward "_a-z0-9" )
      (setq p2 (point))
      (message "%s" (buffer-substring-no-properties p1 p2)))))

Get Current Line

;; return current line as string
(buffer-substring-no-properties (line-beginning-position) (line-end-position) )

Get File Path, URL

Get Text Between Brackets

Grab the current text between delimiters such as between angle brackets <…>, parens (…), double quotes "…", etc.

The trick is to use skip-chars-backward and skip-chars-forward.

(defun my-select-inside-quotes ()
  "grab text between double straight quotes on each side of cursor."
  (interactive)
  (let (p1 p2)
    (skip-chars-backward "^\"")
    (setq p1 (point))
    (skip-chars-forward "^\"")
    (setq p2 (point))
    (buffer-substring-no-properties p1 p2)))

Get Current Char

char-before

return the unicode codepoint (integer) of character before cursor.

char-after

return the unicode codepoint (integer) of character after cursor.

Reference

Emacs Lisp, Convert String, Buffer