Vitalii Drevenchuk
Vitalii Drevenchuk

Reputation: 43

Emacs: check if filepath contains directory name

I try to write code in emacs. I have many different python projects, all of them have space indentation, except one. I want to check if open file path contains directory name of this project and set tabs instead of spaces, only for files in this directory.

I try

(when (string-match "project_name" buffer-file-name)
     do sth)

But it wasn`t work

Also, if you write how to set tabs for python and javascript files it will helps a lot)

UPD

My work code

(add-hook 'python-mode-hook
  (lambda()
   (setq tab-width 4)
   (setq python-indent 4)
   (if (string-match-p "project_name" (or (buffer-file-name) ""))
       (setq indent-tabs-mode t)
     (setq indent-tabs-mode nil))))

Upvotes: 2

Views: 1257

Answers (2)

tom
tom

Reputation: 1344

Simple answer

 (when (string-prefix-p "/home/user/project-path" (buffer-file-name))
   ;;do sth
   )

You may also need to use expand-file-name to get a full path to match buffer-file-name so that you can handle something like "~/project-paht".

(expand-file-name (buffer-file-name))

You may also need to take care nil result from buffer-file-name by

(or (buffer-file-name) "")

Upvotes: 5

Jules
Jules

Reputation: 973

All you have to do for the check is:

(when (string-match-p "project_name" (buffer-file-name))
      (message "cat"))

buffer-file-name is a function and string-match-p returns true or false regarding a string match

Upvotes: 1

Related Questions