How to automatically pick a "mode" for Ace Editor, given a file extension

Dylan picture Dylan · Apr 9, 2013 · Viewed 9.3k times · Source

I'm working on a project that uses a java/scala backend (Lift, to be precise, though that shouldn't affect this question), and as part of the frontend we use Ace Editor. I've been googling for a while and have yet to find an answer to this question:

Given a file extension (e.g. js, c, cpp, h, java, rb, etc), how can I automatically pick an Ace "mode" for the appropriate language?

I'm hoping to avoid manually creating a map, a la js -> javascript, c -> c_cpp, java -> java. Is there a java/scala library available for this? Or better yet, does Ace have this functionality built in somehow?

Answer

a user picture a user · Apr 9, 2013

Ace now provides modelist extension to do this.

var modelist = ace.require("ace/ext/modelist")
var filePath = "blahblah/weee/some.js"
var mode = modelist.getModeForPath(filePath).mode
editor.session.setMode(mode) // mode now contains "ace/mode/javascript".

Note that if you are using prebuilt version of ace you need to include ace.js and ext-modelist.js files in your page.
With source version, you need to replace ace.require with require and require.js will load all dependencies automatically.

See https://github.com/ajaxorg/ace/blob/master/demo/modelist.html and https://github.com/ajaxorg/ace-builds/blob/master/demo/modelist.html for examples of how to use it