/** * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ /** * @module code-block/codeblockediting */ import Plugin from '@ckeditor/ckeditor5-core/src/plugin'; import ShiftEnter from '@ckeditor/ckeditor5-enter/src/shiftenter'; import CodeBlockCommand from './codeblockcommand'; import IndentCodeBlockCommand from './indentcodeblockcommand'; import { getLocalizedLanguageDefinitions, getLeadingWhiteSpaces, rawSnippetTextToModelDocumentFragment } from './utils'; import { modelToViewCodeBlockInsertion, modelToDataViewSoftBreakInsertion, dataViewToModelCodeBlockInsertion } from './converters'; const DEFAULT_ELEMENT = 'paragraph'; /** * The editing part of the code block feature. * * Introduces the `'codeBlock'` command and the `'codeBlock'` model element. * * @extends module:core/plugin~Plugin */ export default class CodeBlockEditing extends Plugin { /** * @inheritDoc */ static get pluginName() { return 'CodeBlockEditing'; } /** * @inheritDoc */ static get requires() { return [ ShiftEnter ]; } /** * @inheritDoc */ constructor( editor ) { super( editor ); editor.config.define( 'codeBlock', { languages: [ { class: 'plaintext', label: 'Plain text' }, { class: 'c', label: 'C' }, { class: 'cs', label: 'C#' }, { class: 'cpp', label: 'C++' }, { class: 'css', label: 'CSS' }, { class: 'diff', label: 'Diff' }, { class: 'xml', label: 'HTML/XML' }, { class: 'java', label: 'Java' }, { class: 'javascript', label: 'JavaScript' }, { class: 'php', label: 'PHP' }, { class: 'python', label: 'Python' }, { class: 'ruby', label: 'Ruby' }, { class: 'typescript', label: 'TypeScript' }, ], // A single tab. indentSequence: ' ' } ); } /** * @inheritDoc */ init() { const editor = this.editor; const schema = editor.model.schema; const model = editor.model; const localizedLanguageDefinitions = getLocalizedLanguageDefinitions( editor ); const languageClasses = localizedLanguageDefinitions.map( def => def.class ); const languageLabels = Object.assign( {}, ...localizedLanguageDefinitions.map( def => ( { [ def.class ]: def.label } ) ) ); // The main command. editor.commands.add( 'codeBlock', new CodeBlockCommand( editor ) ); // Commands that change the indentation. editor.commands.add( 'indentCodeBlock', new IndentCodeBlockCommand( editor, 'forward' ) ); editor.commands.add( 'outdentCodeBlock', new IndentCodeBlockCommand( editor, 'backward' ) ); const getCommandExecuter = commandName => { return ( data, cancel ) => { const command = this.editor.commands.get( commandName ); if ( command.isEnabled ) { this.editor.execute( commandName ); cancel(); } }; }; editor.keystrokes.set( 'Tab', getCommandExecuter( 'indentCodeBlock' ) ); editor.keystrokes.set( 'Shift+Tab', getCommandExecuter( 'outdentCodeBlock' ) ); // Schema. schema.register( 'codeBlock', { inheritAllFrom: '$block', allowAttributes: [ 'language' ] } ); // Disallow codeBlock in codeBlock. schema.addChildCheck( ( context, childDef ) => { if ( context.endsWith( 'codeBlock' ) && childDef.name === 'codeBlock' ) { return false; } } ); // Disallow all attributes in `codeBlock`. schema.addAttributeCheck( ( context, attributeName ) => { if ( context.endsWith( 'codeBlock' ) || context.endsWith( 'codeBlock $text' ) ) { return attributeName === 'language'; } } ); // Conversion. editor.editing.downcastDispatcher.on( 'insert:codeBlock', modelToViewCodeBlockInsertion( model, languageLabels ) ); editor.data.downcastDispatcher.on( 'insert:codeBlock', modelToViewCodeBlockInsertion( model ) ); editor.data.downcastDispatcher.on( 'insert:softBreak', modelToDataViewSoftBreakInsertion( model ), { priority: 'high' } ); editor.data.upcastDispatcher.on( 'element:pre', dataViewToModelCodeBlockInsertion( editor.data, languageClasses ) ); // Intercept the clipboard input (paste) when the selection is anchored in the code block and force the clipboard // data to be pasted as a single plain text. Otherwise, the code lines will split the code block and // "spill out" as separate paragraphs. this.listenTo( editor.editing.view.document, 'clipboardInput', ( evt, data ) => { const modelSelection = model.document.selection; if ( !modelSelection.anchor.parent.is( 'codeBlock' ) ) { return; } const text = data.dataTransfer.getData( 'text/plain' ); model.change( writer => { model.insertContent( rawSnippetTextToModelDocumentFragment( writer, text ), modelSelection ); evt.stop(); } ); } ); // Make sure multi–line selection is always wrapped in a code block when `getSelectedContent()` // is used (e.g. clipboard copy). Otherwise, only the raw text will be copied to the clipboard and, // upon next paste, this bare text will not be inserted as a code block, which is not the best UX. // Similarly, when the selection in a single line, the selected content should be an inline code // so it can be pasted later on and retain it's preformatted nature. this.listenTo( model, 'getSelectedContent', ( evt, [ selection ] ) => { const anchor = selection.anchor; if ( selection.isCollapsed || !anchor.parent.is( 'codeBlock' ) || !anchor.hasSameParentAs( selection.focus ) ) { return; } model.change( writer => { const docFragment = evt.return; // fo[ob]ar -> [ob] if ( docFragment.childCount > 1 || selection.containsEntireContent( anchor.parent ) ) { const codeBlock = writer.createElement( 'codeBlock', anchor.parent.getAttributes() ); writer.append( docFragment, codeBlock ); const newDocumentFragment = writer.createDocumentFragment(); writer.append( codeBlock, newDocumentFragment ); evt.return = newDocumentFragment; } // "f[oo]" -> <$text code="true">oo else { writer.setAttribute( 'code', true, docFragment.getChild( 0 ) ); } } ); } ); } /** * @inheritDoc */ afterInit() { const editor = this.editor; const commands = editor.commands; const indent = commands.get( 'indent' ); const outdent = commands.get( 'outdent' ); if ( indent ) { indent.registerChildCommand( commands.get( 'indentCodeBlock' ) ); } if ( outdent ) { outdent.registerChildCommand( commands.get( 'outdentCodeBlock' ) ); } // Customize the response to the Enter and Shift+Enter // key press when the selection is in the code block. Upon enter key press we can either // leave the block if it's "two enters" in a row or create a new code block line, preserving // previous line's indentation. this.listenTo( editor.editing.view.document, 'enter', ( evt, data ) => { const positionParent = editor.model.document.selection.getLastPosition().parent; if ( !positionParent.is( 'codeBlock' ) ) { return; } leaveBlockOnEnter( editor, data.isSoft ) || breakLineOnEnter( editor ); data.preventDefault(); evt.stop(); } ); } } // Normally, when the Enter (or Shift+Enter) key is pressed, a soft line break is to be added to the // code block. Let's try to follow the indentation of the previous line when possible, for instance: // // // Before pressing enter (or shift enter) // // " foo()"[] // Indent of 4 spaces. // // // // After pressing: // // " foo()" // Indent of 4 spaces. // // A new soft break created by pressing enter. // " "[] // Retain the indent of 4 spaces. // // // @param {module:core/editor/editor~Editor} editor function breakLineOnEnter( editor ) { const model = editor.model; const modelDoc = model.document; const lastSelectionPosition = modelDoc.selection.getLastPosition(); const node = lastSelectionPosition.nodeBefore || lastSelectionPosition.textNode; let leadingWhiteSpaces; // Figure out the indentation (white space chars) at the beginning of the line. if ( node && node.is( 'text' ) ) { leadingWhiteSpaces = getLeadingWhiteSpaces( node ); } // Keeping everything in a change block for a single undo step. editor.model.change( writer => { editor.execute( 'shiftEnter' ); // If the line before being broken in two had some indentation, let's retain it // in the new line. if ( leadingWhiteSpaces ) { writer.insertText( leadingWhiteSpaces, modelDoc.selection.anchor ); } } ); } // Leave the code block when Enter (but NOT Shift+Enter) has been pressed twice at the end // of the code block: // // // Before: // foo[] // // // After first press: // foo[] // // // After second press: // foo[] // // @param {module:core/editor/editor~Editor} editor // @param {Boolean} isSoftEnter When `true`, enter was pressed along with Shift. // @returns {Boolean} `true` when selection left the block. `false` if stayed. function leaveBlockOnEnter( editor, isSoftEnter ) { const model = editor.model; const modelDoc = model.document; const view = editor.editing.view; const lastSelectionPosition = modelDoc.selection.getLastPosition(); const nodeBefore = lastSelectionPosition.nodeBefore; let emptyLineRangeToRemoveOnDoubleEnter; if ( isSoftEnter || !modelDoc.selection.isCollapsed || !lastSelectionPosition.isAtEnd || !nodeBefore ) { return false; } // When the position is directly preceded by a soft break // // foo[] // // it creates the following range that will be cleaned up before leaving: // // foo[] // if ( nodeBefore.is( 'softBreak' ) ) { emptyLineRangeToRemoveOnDoubleEnter = model.createRangeOn( nodeBefore ); } // When there's some text before the position made purely of white–space characters // // foo [] // // but NOT when it's the first one of the kind // // [] // // it creates the following range to clean up before leaving: // // foo[ ] // else if ( nodeBefore.is( 'text' ) && !nodeBefore.data.match( /\S/ ) && nodeBefore.previousSibling && nodeBefore.previousSibling.is( 'softBreak' ) ) { emptyLineRangeToRemoveOnDoubleEnter = model.createRange( model.createPositionBefore( nodeBefore.previousSibling ), model.createPositionAfter( nodeBefore ) ); } // Not leaving the block in the following cases: // // [] // a [] // foobar[] // foo a [] // else { return false; } // We're doing everything in a single change block to have a single undo step. editor.model.change( writer => { // Remove the last and all white space characters that followed it. writer.remove( emptyLineRangeToRemoveOnDoubleEnter ); // "Clone" the in the standard way. editor.execute( 'enter' ); const newBlock = modelDoc.selection.anchor.parent; // Make the cloned a regular (with clean attributes, so no language). writer.rename( newBlock, DEFAULT_ELEMENT ); editor.model.schema.removeDisallowedAttributes( [ newBlock ], writer ); // Eye candy. view.scrollToTheSelection(); } ); return true; }