indentcodeblockcommand.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module code-block/indentcodeblockcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import {
  10. getIndentOutdentPositions,
  11. isModelSelectionInCodeBlock
  12. } from './utils';
  13. /**
  14. * The code block indentation increase command plugin.
  15. *
  16. * @extends module:core/command~Command
  17. */
  18. export default class IndentCodeBlockCommand extends Command {
  19. constructor( editor ) {
  20. super( editor );
  21. /**
  22. * A sequence of characters added to the line when the command is executed.
  23. *
  24. * @readonly
  25. * @private
  26. * @member {String}
  27. */
  28. this._indentSequence = editor.config.get( 'codeBlock.indentSequence' );
  29. }
  30. /**
  31. * @inheritDoc
  32. */
  33. refresh() {
  34. this.isEnabled = this._checkEnabled();
  35. }
  36. /**
  37. * Executes the command. When the command {@link #isEnabled is enabled}, the indentation of the
  38. * code lines in the selection will be increased.
  39. *
  40. * @fires execute
  41. */
  42. execute() {
  43. const editor = this.editor;
  44. const model = editor.model;
  45. model.change( writer => {
  46. const positions = getIndentOutdentPositions( model );
  47. // Indent all positions, for instance assuming the indent sequence is 4x space (" "):
  48. //
  49. // <codeBlock>^foo</codeBlock> -> <codeBlock> foo</codeBlock>
  50. //
  51. // <codeBlock>foo^bar</codeBlock> -> <codeBlock>foo bar</codeBlock>
  52. //
  53. // Also, when there is more than one position:
  54. //
  55. // <codeBlock>
  56. // ^foobar
  57. // <softBreak></softBreak>
  58. // ^bazqux
  59. // </codeBlock>
  60. //
  61. // ->
  62. //
  63. // <codeBlock>
  64. // foobar
  65. // <softBreak></softBreak>
  66. // bazqux
  67. // </codeBlock>
  68. //
  69. for ( const position of positions ) {
  70. writer.insertText( this._indentSequence, position );
  71. }
  72. } );
  73. }
  74. /**
  75. * Checks whether the command can be enabled in the current context.
  76. *
  77. * @private
  78. * @returns {Boolean} Whether the command should be enabled.
  79. */
  80. _checkEnabled() {
  81. if ( !this._indentSequence ) {
  82. return false;
  83. }
  84. // Indent (forward) command is always enabled when there's any code block in the selection
  85. // because you can always indent code lines.
  86. return isModelSelectionInCodeBlock( this.editor.model.document.selection );
  87. }
  88. }