6

Inside of a jsx file, I want to use a gql template literal to define GraphQL queries.

Could I in emacs make that section of the jsx file highlight graphql syntax, instead of just showing it as a plain string?

Example:

import gql from 'graphql-tag'

const normalJavascriptCode = 42

const query = gql`
  here(a: 1, b: 2) {
    itWouldHighlightSyntax
    accordingToGraphQLMode
  }
`

const jsHighlightBackagain = () => {...}

Here you can see how it works for atom: https://github.com/apollographql/graphql-tools/issues/123#issuecomment-244830016

1 Answer 1

5

I've found a solution using the emacs package mmm-mode. Most of the information I got was from this article.

What this package does, is allow multiple major modes in the same buffer. You basically set the opening and closing clauses for whatever nested syntax you have, and that block will be highlighted in a submode.

M-x package-install RET graphql-mode
M-x package-install RET mmm-mode
(require 'graphql-mode)
(require 'mmm-mode)

(mmm-add-classes
    '((js-graphql
          :submode graphql-mode
          :face mmm-declaration-submode-face
          :front "[^a-zA-Z]gql`" ;; regex to find the opening tag
          :back "`"))) ;; regex to find the closing tag
(mmm-add-mode-ext-class 'js-mode nil 'js-graphql)
(setq mmm-global-mode 'maybe)
;; Optional configuration that hides the background color for a highlighted block
;; I find it useful for debugging emacs, but when actually coding I dont want so much emphasis on submodes
(setq mmm-submode-decoration-level 0)

There are a lot of configuration options, but for this setup, you can re-highlight your blocks in an open buffer by running this command

M-x mmm-parse-buffer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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