Elisp: Get Buffer String

By Xah Lee. Date: . Last updated: .

Get String from Region

Grab text of given begin/end positions.

The property means Text Properties. Usually you no need it.

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

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 xword (case-fold-search t))
    (save-excursion
      (skip-chars-backward "_a-z0-9")
      (setq p1 (point))
      (skip-chars-forward "_a-z0-9")
      (setq p2 (point))
      (setq xword (buffer-substring-no-properties p1 p2))
      (message "%s" xword)
      xword
      )))

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.

(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 integer ID of character before cursor.

char-after

return the integer ID of character after cursor.

Reference

Elisp, Convert String, Buffer

Elisp, text processing functions