diff --git a/src/components/views/rooms/BasicMessageComposer.js b/src/components/views/rooms/BasicMessageComposer.js index 38cfff9b65..cd8589ee29 100644 --- a/src/components/views/rooms/BasicMessageComposer.js +++ b/src/components/views/rooms/BasicMessageComposer.js @@ -24,6 +24,7 @@ import {setCaretPosition} from '../../../editor/caret'; import { replaceRangeAndExpandSelection, formatRangeAsQuote, + formatRangeAsCode, formatInline, } from '../../../editor/operations'; import {getCaretOffsetAndText, getRangeForSelection} from '../../../editor/dom'; @@ -457,8 +458,12 @@ export default class BasicMessageEditor extends React.Component { formatRangeAsQuote(range); } - _formatCodeBlock = () => { - + _formatCode = () => { + const range = getRangeForSelection( + this._editorRef, + this.props.model, + document.getSelection()); + formatRangeAsCode(range); } render() { diff --git a/src/editor/operations.js b/src/editor/operations.js index be979c275a..df3047618b 100644 --- a/src/editor/operations.js +++ b/src/editor/operations.js @@ -67,6 +67,29 @@ export function formatRangeAsQuote(range) { replaceRangeAndExpandSelection(model, range, parts); } +export function formatRangeAsCode(range) { + const {model, parts} = range; + const {partCreator} = model; + const needsBlock = parts.some(p => p.type === "newline"); + if (needsBlock) { + parts.unshift(partCreator.plain("```"), partCreator.newline()); + if (!rangeStartsAtBeginningOfLine(range)) { + parts.unshift(partCreator.newline()); + } + parts.push( + partCreator.newline(), + partCreator.plain("```")); + if (rangeEndsAtEndOfLine(range)) { + parts.push(partCreator.newline()); + } + replaceRangeAndExpandSelection(model, range, parts); + } else { + parts.unshift(partCreator.plain("`")); + parts.push(partCreator.plain("`")); + replaceRangeAndExpandSelection(model, range, parts); + } +} + export function formatInline(range, prefix, suffix = prefix) { const {model, parts} = range; const {partCreator} = model;