Skip to content

Commit

Permalink
Use prettier on Shift+tab inside codemirror
Browse files Browse the repository at this point in the history
  • Loading branch information
chinchang committed Oct 24, 2018
1 parent 6361034 commit 2091df6
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
8 changes: 6 additions & 2 deletions src/components/ContentWrap.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -818,7 +818,9 @@ export default class ContentWrap extends Component {
'CodeMirror-linenumbers',
'CodeMirror-foldgutter'
],
emmet: true
emmet: true,
prettier: true,
prettierParser: 'css'
}}
prefs={this.props.prefs}
onChange={this.onCssCodeChange.bind(this)}
Expand Down Expand Up @@ -870,7 +872,9 @@ export default class ContentWrap extends Component {
'error-gutter',
'CodeMirror-linenumbers',
'CodeMirror-foldgutter'
]
],
prettier: true,
prettierParser: 'js'
}}
prefs={this.props.prefs}
autoComplete={this.props.prefs.autoComplete}
Expand Down
9 changes: 8 additions & 1 deletion src/components/UserCodeMirror.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import 'codemirror/keymap/vim.js';
import 'code-blast-codemirror/code-blast.js';

import emmet from '@emmetio/codemirror-plugin';
import { prettify } from '../utils';

emmet(CodeMirror);

Expand Down Expand Up @@ -79,7 +80,13 @@ export default class UserCodeMirror extends Component {
CodeMirror.commands.goLineDown(editor);
},
'Shift-Tab': function(editor) {
CodeMirror.commands.indentAuto(editor);
if (options.prettier) {
editor.setValue(
prettify(editor.getValue(), options.prettierParser)
);
} else {
CodeMirror.commands.indentAuto(editor);
}
},
Tab: function(editor) {
if (options.emmet) {
Expand Down
21 changes: 21 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,27 @@ export function getFilenameFromUrl(url) {
return url.match(/\/([^/]*)$/)[1];
}

export function prettify(content, type = 'js') {
const prettier = require('prettier/standalone');
let plugins, parser;
if (type === 'js') {
parser = 'babylon';
plugins = [require('prettier/parser-babylon')];
} else if (type === 'css') {
parser = 'css';
plugins = [require('prettier/parser-postcss')];
}

if (!parser) {
return content;
}
const formattedContent = prettier.format(content, {
parser,
plugins
});
return formattedContent || content;
}

if (window.IS_EXTENSION) {
document.body.classList.add('is-extension');
} else {
Expand Down

0 comments on commit 2091df6

Please sign in to comment.