Search code examples
pythonemacselisp

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))))

Solution

  • 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) "")