Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-language syntax highlighting in Emacs

Tags:

python

sql

emacs

Say I have code from multiple languages in a single buffer, can I have emacs syntax highlight each snippet according to its corresponding language?

For example, the following code is part of a python script, but it contains SQL code:

import psycopg2 as pg
import pandas.io.sql as psql

# Some SQL code:
my_query ='''
select count(distinct s.object_uid) 
from dx.dx_segment as s;
'''
# end of SQL code

dataframe = psql.frame_query(my_query, connection)

It would be great to have the SQL part highlighted as SQL syntax, while the rest of the file highlighted as Python.

Is this possible in Emacs? Any way to hint to Emacs what highlighter to use, perhaps taking advantage of the comments?

like image 980
Amelio Vazquez-Reina Avatar asked Feb 10 '14 18:02

Amelio Vazquez-Reina


1 Answers

When I'm using some SQL in C, I have a system using MMM-Mode; wrapping the required statement in a set of comments,

/* SQL */ 

and

/* #SQL */

the following will give me SQL syntax highlighting:

 (require 'mmm-mode)
 (set-face-background 'mmm-default-submode-face nil)

 (mmm-add-classes
  '((embedded-sql
     :submode sql-mode
     :front "/* SQL */"
     :back "/* #SQL */")))

 (mmm-add-mode-ext-class 'c-mode "*.c" 'c-sql)
 (setq mmm-never-modes
               (append '(ediff-mode) '(text-mode) mmm-never-modes))

I can then use the mmm-ify-by-class to apply the c-sql class - Perhaps you can do similar in Python?

For me, the following lisp allows Emacs to see the sample SQL string in the sample python as SQL (Light gray background indicates where MMM mode is active)

enter image description here

(Modified again to allow single line statements)

(require 'mmm-mode)

(mmm-add-classes
 '((python-sql
    :submode sql-mode
    :face mmm-code-submode-face
    :front "# SQL\\(\n\\|\t\\)*\\(\[ -_A-Z0-9\]+\\)\\(\[ =\]\\)\\(\"\"\"\\|'''\\)"
    :back "\\(\"\"\"\\|'''\\)\\( \\|\t\\|\n\\)*\\# /SQL")))

(mmm-add-mode-ext-class 'python-mode "*.py" 'python-sql)
like image 134
Orpheus Avatar answered Oct 17 '22 14:10

Orpheus