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

Drew
  • 75,699
  • 9
  • 109
  • 225
vcr
  • 83
  • 8

1 Answers1

3

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
andykais
  • 146
  • 2