Skip to content

Instantly share code, notes, and snippets.

@rangeoshun
Last active June 12, 2023 15:45
Show Gist options
  • Save rangeoshun/67cb17392c523579bc6cbd758b2315c1 to your computer and use it in GitHub Desktop.
Save rangeoshun/67cb17392c523579bc6cbd758b2315c1 to your computer and use it in GitHub Desktop.
Typescript with CSS in JS (styled-components, Emotion), JSX and graphql highlight and major mode for Emacs Doom with `mmm-mode` for *.tsx
;; Assign typescript-mode to .tsx files
(add-to-list 'auto-mode-alist '("\\.tsx\\'" . typescript-mode))
(require 'mmm-mode)
(setq mmm-global-mode t)
(setq mmm-submode-decoration-level 0) ;; Turn off background highlight
;; Add css mode for CSS in JS blocks
(mmm-add-classes
'((mmm-styled-mode
:submode css-mode
:front "\\(styled\\|css\\)[.()<>[:alnum:]]?+`"
:back "`;")))
(mmm-add-mode-ext-class 'typescript-mode nil 'mmm-styled-mode)
;; Add submodule for graphql blocks
(mmm-add-classes
'((mmm-graphql-mode
:submode graphql-mode
:front "gr?a?p?h?ql`"
:back "`;")))
(mmm-add-mode-ext-class 'typescript-mode nil 'mmm-graphql-mode)
;; Add JSX submodule, because typescript-mode is not that great at it
(mmm-add-classes
'((mmm-jsx-mode
:front "\\(return\s\\|n\s\\|(\n\s*\\)<"
:front-offset -1
:back ">\n?\s*)"
:back-offset 1
:submode web-mode)))
(mmm-add-mode-ext-class 'typescript-mode nil 'mmm-jsx-mode)
(defun mmm-reapply ()
(mmm-mode)
(mmm-mode))
(add-hook 'after-save-hook
(lambda ()
(when (string-match-p "\\.tsx?" buffer-file-name)
(mmm-reapply))))
;; Packages used in config.el for regular emacs you'll need `use-package` I guess
(package! mmm-mode)
(package! typescript-mode)
(package! web-mode)
(package! graphql-mode)
@peter-wd-1
Copy link

;; use css in js with polymode
(use-package! polymode
   :ensure t
   :after rjsx-mode
   :config
   (define-hostmode poly-rjsx-hostmode nil
     "RJSX hostmode."
     :mode 'rjsx-mode)
   (define-innermode poly-rjsx-cssinjs-innermode nil
     :mode 'css-mode
     :head-matcher "\\(styled\\|css\\)[.()<>[:alnum:]]?+`"
     :tail-matcher "\`"
     :head-mode 'host
     :tail-mode 'host)
   (define-polymode poly-rjsx-mode
     :hostmode 'poly-rjsx-hostmode
     :innermodes '(poly-rjsx-cssinjs-innermode))
   (add-to-list 'auto-mode-alist '("\\.js?\\'" . poly-rjsx-mode)))

Now I'm using this instead
Not a perfect solution but I just excepted there isn't such a reliable solution with RSJX mode yet
Thank you!

@jvrmalv
Copy link

jvrmalv commented Apr 1, 2022

Hello, I'm trying to use this previous snippet with typescript-mode, but it really just doesn't work right for me. It does change the mode to css-mode when I enter between the two backticks, but syntax highlight and code completion still is from typescript

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment