13

I have a face, created this way:

(defface test-face
  '((t . (:height 2.0)))
  "A face for testing.")

I'd like to insert some text with that face. But these ways insert the text without the face:

(insert (propertize "text to insert" 'face 'test-face))

(let ((current-string "text to insert"))
  (put-text-property 1 (length current-string) 'face 'test-face)
  (insert current-string))

And even inserting the text first, then going back to put the face on it isn't working:

(progn
  (insert "text to insert")
  (add-text-properties
   (save-excursion
     (backward-word 3)
     (point))
   (point)
   '(face test-face)))

The problem isn't the definition of the face, because if I go to customize it, it's already showing up with height twice as big. Even so, inlining the face also doesn't work:

(insert (propertize "to insert" 'face '(:height 2.0)))

So how can I put in some text with the specific face? I know I can use an overlay, but that seems like overkill because it's more verbose, requires the text to be inserted first (so we have to find out the size and position of the text to be overlaid) and requires making more garbage to be collected.

  • 2
    Try the above examples in fundamental mode or any other mode with font-lock disabled (they would work fine). The issue is that font-lock also uses face for syntax highlighting code, so it is replacing your face property. I am sure there must be some way to disable font-lock for a given text but I will have to research the code a bit (no time right now). Perhaps reading font-lock.el code would give some clue – Iqbal Ansari Oct 5 '15 at 6:39
15

There are some problem with the code:

  • put-text-property is applied to an object. In this case your string. You need to pass it as as the last parameter.
  • put-text-property starts counting at zero.
  • If font-lock-mode is enabled, it will strip any text of the face property.

The following piece of code works, if font-lock mode is disabled:

(let ((current-string "text to insert"))
  (put-text-property 0 (length current-string) 'face 'font-lock-warning-face
                     current-string)
  (insert current-string))

If you want to use this with font-lock enabled, you can set the property font-lock-face instead. It has the same effect but isn't affected by font-lock.

  • Clear and complete answer. – Drew Oct 5 '15 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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