how to enable and disable syntax highlighting in emacs

Emacs comes with syntax highlighting enabled out of the box for most modes or file types. So it should work just fine in most cases. The standard way that Emacs perform syntax highlighting is using the font-lock-mode function. It is turned on by default.

enabling the syntax highlighting

If for some reason you find that the buffer is not being highlighted, then try toggling the font-lock-mode and ensure that it is on.

M-x font-lock-mode

disabling the syntax highlighting

Highlighting the buffer with font-lock-mode is a resource intensive process and sometimes is the reason for "laggy" buffer. If you need to speed up the buffer and the syntax highlighting can be toggled off using the same command as before.

M-x font-lock-mode

It goes without saying that the buffer need to be in the "correct" major mode for the syntax highlighting to work correctly.

enabling syntax highlighting on new file types or extensions

If you have a file with a custom extension or just a generic file type, and you want to enable highlighting on it, then you will need to add the file type to the mode list.

For example, you want to add all files with the extension .style to be treated the same way as the css files and have syntax highlighting, then add the following to your configuration file:

(setq auto-mode-alist (append '((".*\\.style$" . css-mode)) auto-mode-alist))

auto-mode-alist is a list that Emacs maintains to determine the major mode to use. We have just added .style files to the list to use the css-mode.

The issue with font-lock-mode has always been of performance. Recently there has been some packages that aim to help with the performance and correctness of the syntax highlighting. Tree Sitter is one such package and it has recently been rolled into the core emacs. We can probably see it being used in the upcoming releases.

using tree sitter

You can start using tree sitter as a package, but all the languages may not be supported at this time. My current configuration to use tree-sitter is:

(use-package tree-sitter :ensure t :diminish
      :config (global-tree-sitter-mode)
      :hook (tree-sitter-mode . tree-sitter-hl-mode))

(use-package tree-sitter-langs :ensure t :after tree-sitter)

This will use the tree-sitter package instead of the font-lock-mode to perform the syntax highlighting.