8
0
Просмотр исходного кода

Merge branch 'master' into unification

Maciej Bukowski 5 лет назад
Родитель
Сommit
cec41a844d
74 измененных файлов с 1457 добавлено и 2939 удалено
  1. 0 8
      docs/_snippets/features/wproofreader.html
  2. 47 1
      docs/_snippets/features/wproofreader.js
  3. 58 39
      docs/features/spelling-and-grammar-checking.md
  4. 2 2
      docs/framework/guides/architecture/editing-engine.md
  5. 1 0
      package.json
  6. 3 2
      packages/ckeditor5-autoformat/docs/features/autoformat.md
  7. 1 0
      packages/ckeditor5-code-block/package.json
  8. 62 0
      packages/ckeditor5-code-block/tests/codeblock-integration.js
  9. 1 1
      packages/ckeditor5-engine/docs/_snippets/framework/extending-content-add-unsafe-link-class.html
  10. 2 2
      packages/ckeditor5-engine/docs/_snippets/framework/extending-content-allow-div-attributes.html
  11. 26 8
      packages/ckeditor5-engine/docs/_snippets/framework/extending-content-custom-element-converter.html
  12. 53 54
      packages/ckeditor5-engine/docs/framework/guides/deep-dive/conversion-extending-output.md
  13. 9 9
      packages/ckeditor5-engine/docs/framework/guides/deep-dive/conversion-introduction.md
  14. 43 43
      packages/ckeditor5-engine/docs/framework/guides/deep-dive/conversion-preserving-custom-content.md
  15. 8 8
      packages/ckeditor5-engine/docs/framework/guides/deep-dive/schema.md
  16. 2 2
      packages/ckeditor5-engine/src/dev-utils/view.js
  17. 7 2
      packages/ckeditor5-engine/src/model/utils/insertcontent.js
  18. 15 14
      packages/ckeditor5-engine/src/view/domconverter.js
  19. 87 45
      packages/ckeditor5-engine/src/view/downcastwriter.js
  20. 21 21
      packages/ckeditor5-engine/src/view/rawelement.js
  21. 3 4
      packages/ckeditor5-image/tests/imagetoolbar.js
  22. 11 4
      packages/ckeditor5-link/src/linkui.js
  23. 17 0
      packages/ckeditor5-link/tests/linkui.js
  24. 1 5
      packages/ckeditor5-markdown-gfm/docs/_snippets/features/markdown.js
  25. 2 7
      packages/ckeditor5-markdown-gfm/docs/features/markdown.md
  26. 10 1
      packages/ckeditor5-markdown-gfm/package.json
  27. 17 14
      packages/ckeditor5-markdown-gfm/src/gfmdataprocessor.js
  28. 93 0
      packages/ckeditor5-markdown-gfm/src/html2markdown/html2markdown.js
  29. 0 1286
      packages/ckeditor5-markdown-gfm/src/lib/marked/marked.js
  30. 0 175
      packages/ckeditor5-markdown-gfm/src/lib/marked/renderer.js
  31. 0 68
      packages/ckeditor5-markdown-gfm/src/lib/to-markdown/converters.js
  32. 0 785
      packages/ckeditor5-markdown-gfm/src/lib/to-markdown/to-markdown.js
  33. 36 0
      packages/ckeditor5-markdown-gfm/src/markdown.js
  34. 37 0
      packages/ckeditor5-markdown-gfm/src/markdown2html/markdown2html.js
  35. 26 3
      packages/ckeditor5-markdown-gfm/tests/_utils/utils.js
  36. 31 13
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/blockquotes.js
  37. 56 20
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/code.js
  38. 42 8
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/escaping.js
  39. 12 2
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/headers.js
  40. 26 26
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/horizontal-rules.js
  41. 26 0
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/html.js
  42. 3 3
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/images.js
  43. 47 125
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/links.js
  44. 42 0
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/lists.js
  45. 6 3
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/manual/gfmdataprocessor.js
  46. 3 42
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/paragraphs.js
  47. 2 2
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/strikethrough.js
  48. 12 0
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/strong-emphasis.js
  49. 2 2
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/tables.js
  50. 50 0
      packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/text.js
  51. 31 0
      packages/ckeditor5-markdown-gfm/tests/manual/markdown.html
  52. 71 0
      packages/ckeditor5-markdown-gfm/tests/manual/markdown.js
  53. 9 0
      packages/ckeditor5-markdown-gfm/tests/manual/markdown.md
  54. BIN
      packages/ckeditor5-markdown-gfm/tests/manual/sample.jpg
  55. 26 0
      packages/ckeditor5-markdown-gfm/tests/markdown.js
  56. 3 3
      packages/ckeditor5-media-embed/docs/features/media-embed.md
  57. 1 1
      packages/ckeditor5-media-embed/src/mediaregistry.js
  58. 3 3
      packages/ckeditor5-media-embed/src/utils.js
  59. 3 4
      packages/ckeditor5-media-embed/tests/mediaembedtoolbar.js
  60. 3 2
      packages/ckeditor5-mention/docs/features/mentions.md
  61. 1 2
      packages/ckeditor5-mention/src/mentionui.js
  62. 23 5
      packages/ckeditor5-mention/tests/mentionui.js
  63. 19 4
      packages/ckeditor5-table/src/tablewalker.js
  64. 13 28
      packages/ckeditor5-table/src/utils/ui/contextualballoon.js
  65. 6 8
      packages/ckeditor5-table/tests/tabletoolbar.js
  66. 4 4
      packages/ckeditor5-table/tests/tablewalker.js
  67. 3 2
      packages/ckeditor5-typing/docs/features/text-transformation.md
  68. 5 4
      packages/ckeditor5-utils/src/collection.js
  69. 17 5
      packages/ckeditor5-utils/src/dom/emittermixin.js
  70. 36 1
      packages/ckeditor5-utils/src/dom/rect.js
  71. 6 1
      packages/ckeditor5-utils/src/focustracker.js
  72. 26 0
      packages/ckeditor5-utils/tests/dom/emittermixin.js
  73. 86 0
      packages/ckeditor5-utils/tests/dom/rect.js
  74. 1 3
      scripts/docs/snippetadapter.js

+ 0 - 8
docs/_snippets/features/wproofreader.html

@@ -1,11 +1,3 @@
-<script type="text/javascript" src="https://svc.webspellchecker.net/spellcheck31/wscbundle/wscbundle.js"></script>
-<script>
-	window.WEBSPELLCHECKER_CONFIG = {
-		autoSearch: true,
-		enableGrammar: true,
-		serviceId: '1:Eebp63-lWHbt2-ASpHy4-AYUpy2-fo3mk4-sKrza1-NsuXy4-I1XZC2-0u2F54-aqYWd1-l3Qf14-umd'
-	};
-</script>
 <div id="snippet-wproofreader">
 	<p>Typos hapen. We striving to correct them. Hover on the marked words for instant correction suggestions or click the dialog icon in the bottom right corner to have the whole text proofread at once.</p>
 	<p>You can also paste your own text here to have its spelling and grammar checked.</p>

+ 47 - 1
docs/_snippets/features/wproofreader.js

@@ -3,15 +3,61 @@
  * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  */
 
-/* globals ClassicEditor, console, window, document */
+/* globals console, window, document */
+
+import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';
+import ArticlePluginSet from '@ckeditor/ckeditor5-core/tests/_utils/articlepluginset';
+import EasyImage from '@ckeditor/ckeditor5-easy-image/src/easyimage';
+import WProofreader from '@webspellchecker/wproofreader-ckeditor5/src/wproofreader';
 
 import { CS_CONFIG } from '@ckeditor/ckeditor5-cloud-services/tests/_utils/cloud-services-config';
 
 ClassicEditor
 	.create( document.querySelector( '#snippet-wproofreader' ), {
+		plugins: [ ArticlePluginSet, EasyImage, WProofreader ],
+		wproofreader: {
+			serviceId: '1:Eebp63-lWHbt2-ASpHy4-AYUpy2-fo3mk4-sKrza1-NsuXy4-I1XZC2-0u2F54-aqYWd1-l3Qf14-umd',
+			srcUrl: 'https://svc.webspellchecker.net/spellcheck31/wscbundle/wscbundle.js'
+		},
 		cloudServices: CS_CONFIG,
 		toolbar: {
+			items: [
+				'heading',
+				'|',
+				'bold',
+				'italic',
+				'bulletedList',
+				'numberedList',
+				'|',
+				'outdent',
+				'indent',
+				'|',
+				'blockQuote',
+				'link',
+				'mediaEmbed',
+				'insertTable',
+				'|',
+				'undo',
+				'redo'
+			],
 			viewportTopOffset: window.getViewportTopOffsetConfig()
+		},
+		image: {
+			styles: [
+				'full',
+				'alignLeft',
+				'alignRight'
+			],
+			toolbar: [
+				'imageStyle:alignLeft',
+				'imageStyle:full',
+				'imageStyle:alignRight',
+				'|',
+				'imageTextAlternative'
+			]
+		},
+		table: {
+			contentToolbar: [ 'tableColumn', 'tableRow', 'mergeTableCells' ]
 		}
 	} )
 	.then( editor => {

+ 58 - 39
docs/features/spelling-and-grammar-checking.md

@@ -5,8 +5,6 @@ menu-title: Spelling and grammar checking
 
 # Proofreading, spelling and grammar checking
 
-{@snippet build-classic-source}
-
 <info-box>
 	The spell checker for CKEditor 5 is a commercial solution provided by our partner, [WebSpellChecker](https://webspellchecker.com/). You can report any issues in its [GitHub repository](https://github.com/WebSpellChecker/wproofreader). The license can be purchased [here](https://ckeditor.com/contact/).
 </info-box>
@@ -29,63 +27,84 @@ There are also over 150 additional languages and specialized dictionaries such a
 
 ## Installation
 
-WProofreader is installed separately from CKEditor 5 and does not need to be combined into an editor build as other features. To use this tool, it is necessary to load the WProofreader script on your page and provide the configuration.
+WProofreader is delivered as a CKEditor 5 plugin, so it could be combined into an editor build as other features. To add this feature to your rich-text editor, install the [`@webspellchecker/wproofreader-ckeditor5`](https://www.npmjs.com/package/@webspellchecker/wproofreader-ckeditor5) package:
+
+```bash
+npm install --save @webspellchecker/wproofreader-ckeditor5
+```
+
+Then, add it to your plugin list:
+
+```js
+import WProofreader from '@webspellchecker/wproofreader-ckeditor5/src/wproofreader';
+// ...
+
+ClassicEditor
+	.create( editorElement, {
+		plugins: [ ..., WProofreader ],
+		// ...
+	} )
+	.then( ... )
+	.catch( ... );
+```
+
+<info-box info>
+	Read more about {@link builds/guides/integration/installing-plugins installing plugins}.
+</info-box>
 
-The proofreader can be used either as a [cloud solution](#wproofreader-cloud) or [hosted on your own server](#wproofreader-server).
+At this step, it is required to provide a proper configuration. The proofreader can be used either as a [cloud solution](#wproofreader-cloud) or [hosted on your own server](#wproofreader-server).
 
 ### WProofreader Cloud
 
 After signing up for a [trial or paid version](https://ckeditor.com/contact/), you will receive your service ID which is used to activate the service.
 
-Add the following configuration to your page:
-
-```html
-<script>
-	window.WEBSPELLCHECKER_CONFIG = {
-		autoSearch: true,
-		enableGrammar: true,
-		serviceId: 'your-service-ID'
-	};
-</script>
-```
+Add the following configuration to your editor:
 
-And then load the proofreader script:
+```js
+import WProofreader from '@webspellchecker/wproofreader-ckeditor5/src/wproofreader';
+// ...
 
-```html
-<script src="https://svc.webspellchecker.net/spellcheck31/wscbundle/wscbundle.js"></script>
+ClassicEditor
+	.create( editorElement, {
+		plugins: [ ..., WProofreader ],
+		wproofreader: {
+			serviceId: 'your-service-ID',
+			srcUrl: 'https://svc.webspellchecker.net/spellcheck31/wscbundle/wscbundle.js'
+		}
+	} )
 ```
 
-Refer to the [official documentation](https://github.com/WebSpellChecker/wproofreader#wproofreader-cloud) for more details about the cloud setup and available configuration options.
+Refer to the [official documentation](https://github.com/WebSpellChecker/wproofreader-ckeditor5#install-instructions) for more details about the cloud setup and available configuration options.
 
 ### WProofreader Server
 
 After signing up for a [trial or paid version](https://ckeditor.com/contact/), you will receive access to the WebSpellChecker Server package to install on your own server.
 
-You will need to add the following configuration to your page:
-
-```html
-<script>
-	window.WEBSPELLCHECKER_CONFIG = {
-		autoSearch: true,
-		enableGrammar: true,
-		servicePort: '2880',
-		servicePath: '/'
-	};
-</script>
-```
-
-Then specify the path to the service on your page:
-
-```html
-<script src="http(s)://your_host_name/spellcheck/wscbundle/wscbundle.js"></script>
+You will need to add the following configuration to your editor:
+
+```js
+import WProofreader from '@webspellchecker/wproofreader-ckeditor5/src/wproofreader';
+// ...
+
+ClassicEditor
+	.create( editorElement, {
+		plugins: [ ..., WProofreader ],
+		wproofreader: {
+			serviceProtocol: 'https',
+			serviceHost: 'localhost',
+			servicePort: '2880',
+			servicePath: '/',
+			srcUrl: 'https://host_name/virtual_directory/wscbundle/wscbundle.js'
+		}
+	} )
 ```
 
-Refer to the [official documentation](https://github.com/WebSpellChecker/wproofreader#wproofreader-server) for more details about the server setup and available configuration options.
+Refer to the [official documentation](https://github.com/WebSpellChecker/wproofreader-ckeditor5#install-instructions) for more details about the server setup and available configuration options.
 
 ## Configuration
 
-WProofreader configuration is set outside the CKEditor 5 configuration. Refer to the [WProofreader API](http://dev.webspellchecker.net/api/wscbundle/) for further information.
+WProofreader configuration is set inside the CKEditor 5 configuration in `wproofreader` object. Refer to the [WProofreader API](https://webspellchecker.com/docs/api/wscbundle/Options.html) for further information.
 
 ## Contribute
 
-You can report issues and request features in the [official WProofreader repository](https://github.com/WebSpellChecker/wproofreader/issues).
+You can report issues and request features in the [official WProofreader for CKEditor 5 repository](https://github.com/WebSpellChecker/wproofreader-ckeditor5/issues).

+ 2 - 2
docs/framework/guides/architecture/editing-engine.md

@@ -226,14 +226,14 @@ editor.data;                    // The data pipeline (DataController).
 
 ### Element types and custom data
 
-The structure of the view resembles the structure in the DOM very closely. The semantics of HTML is defined in its specification. The view structure comes "DTD-free", so in order to provide additional information and to better express the semantics of the content, the view structure implements 6 element types ({@link module:engine/view/containerelement~ContainerElement}, {@link module:engine/view/attributeelement~AttributeElement}, {@link module:engine/view/emptyelement~EmptyElement}, {@link module:engine/view/rawelement~RawElement}, {@link module:engine/view/uielement~UIElement}, and {@link module:engine/view/editableelement~EditableElement}) and so called {@link module:engine/view/element~Element#getCustomProperty "custom properties"} (i.e. custom element properties which are not rendered). This additional information provided by editor features is then used by the {@link module:engine/view/renderer~Renderer} and [converters](#conversion).
+The structure of the view resembles the structure in the DOM very closely. The semantics of HTML is defined in its specification. The view structure comes "DTD-free", so in order to provide additional information and to better express the semantics of the content, the view structure implements 6 element types ({@link module:engine/view/containerelement~ContainerElement}, {@link module:engine/view/attributeelement~AttributeElement}, {@link module:engine/view/emptyelement~EmptyElement}, {@link module:engine/view/rawelement~RawElement}, {@link module:engine/view/uielement~UIElement}, and {@link module:engine/view/editableelement~EditableElement}) and so called {@link module:engine/view/element~Element#getCustomProperty "custom properties"} (i.e. custom element properties which are not rendered). This additional information provided by the editor features is then used by the {@link module:engine/view/renderer~Renderer} and [converters](#conversion).
 
 The element types can be defined as follows:
 
 * **Container element** &ndash; The elements that build the structure of the content. Used for block elements such as `<p>`, `<h1>`, `<blockQuote>`, `<li>`, etc.
 * **Attribute element** &ndash; The elements that cannot hold container elements inside them. Most model text attributes are converted to view attribute elements. They are used mostly for inline styling elements such as `<strong>`, `<i>`, `<a>`, `<code>`. Similar attribute elements are flattened by the view writer, so e.g. `<a href="..."><a class="bar">x</a></a>` would automatically be optimized to `<a href="..." class="bar">x</a>`.
 * **Empty element** &ndash; The elements that must not have any child nodes, for example `<img>`.
-* **UI elements** &ndash; The elements that are not a part of the "data" but need to be "inlined" in the content. They are ignored by the selection (it jumps over them) and the view writer in general. The contents of these elements and events coming from them are filtered out, too.
+* **UI element** &ndash; The elements that are not a part of the "data" but need to be "inlined" in the content. They are ignored by the selection (it jumps over them) and the view writer in general. The contents of these elements and events coming from them are filtered out, too.
 * **Raw element** &ndash; The elements that work as data containers ("wrappers", "sandboxes") but their children are transparent to the editor. Useful when non-standard data must be rendered but the editor should not be concerned what it is and how it works. Users cannot put the selection inside a raw element, split it into smaller chunks or directly modify its content.
 * **Editable element** &ndash; The elements used as "nested editables" of non-editable fragments of the content, for example a caption in the image widget, where the `<figure>` wrapping the image is not editable (it is a widget) and the `<figcaption>` inside it is an editable element.
 

+ 1 - 0
package.json

@@ -86,6 +86,7 @@
     "@ckeditor/ckeditor5-react": "^2.1.0",
     "@ckeditor/ckeditor5-real-time-collaboration": "^21.0.0",
     "@ckeditor/ckeditor5-track-changes": "^21.0.0",
+    "@webspellchecker/wproofreader-ckeditor5": "^1.0.5",
     "@wiris/mathtype-ckeditor5": "7.20.0",
     "babel-standalone": "^6.26.0",
     "coveralls": "^3.1.0",

+ 3 - 2
packages/ckeditor5-autoformat/docs/features/autoformat.md

@@ -42,8 +42,9 @@ Example:
 
 In addition to enabling automatic text formatting, you may want to check the following productivity features:
 
-* {@link features/text-transformation Automatic text transformation} &ndash; It enables automatic turning snippets such as `(tm)` into `™` and `"foo"` into `“foo”`.
-* {@link features/mentions Mentions} &ndash; It brings support for smart autocompletion.
+* {@link features/text-transformation Automatic text transformation} &ndash; Enables automatic turning snippets such as `(tm)` into `™` and `"foo"` into `“foo”`.
+* {@link features/link#autolink-feature Autolink} &ndash; Turns the links and email addresses typed or pasted into the editor into active URLs.
+* {@link features/mentions Mentions} &ndash; Brings support for smart autocompletion.
 
 ## Installation
 

+ 1 - 0
packages/ckeditor5-code-block/package.json

@@ -24,6 +24,7 @@
     "@ckeditor/ckeditor5-editor-classic": "^21.0.0",
     "@ckeditor/ckeditor5-engine": "^21.0.0",
     "@ckeditor/ckeditor5-indent": "^21.0.0",
+    "@ckeditor/ckeditor5-markdown-gfm": "^21.0.0",
     "@ckeditor/ckeditor5-paragraph": "^21.0.0",
     "@ckeditor/ckeditor5-undo": "^21.0.0"
   },

+ 62 - 0
packages/ckeditor5-code-block/tests/codeblock-integration.js

@@ -0,0 +1,62 @@
+/**
+ * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
+ */
+
+import ClassicTestEditor from '@ckeditor/ckeditor5-core/tests/_utils/classictesteditor';
+import Enter from '@ckeditor/ckeditor5-enter/src/enter';
+import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
+import GFMDataProcessor from '@ckeditor/ckeditor5-markdown-gfm/src/gfmdataprocessor';
+import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
+
+import CodeBlockEditing from '../src/codeblockediting';
+
+// A simple plugin that enables the GFM data processor.
+class CodeBlockIntegration extends Plugin {
+	constructor( editor ) {
+		super( editor );
+		editor.data.processor = new GFMDataProcessor( editor.data.viewDocument );
+	}
+}
+
+function getEditor( initialData = '' ) {
+	return ClassicTestEditor
+		.create( initialData, {
+			plugins: [ CodeBlockIntegration, CodeBlockEditing, Enter, Paragraph ]
+		} );
+}
+
+describe( 'CodeBlock - integration', () => {
+	describe( 'with Markdown GFM', () => {
+		it( 'should be loaded and returned from the editor (for plain text)', async () => {
+			const editor = await getEditor(
+				'```\n' +
+				'test()\n' +
+				'```'
+			);
+
+			expect( editor.getData() ).to.equal(
+				'```plaintext\n' +
+				'test()\n' +
+				'```'
+			);
+
+			await editor.destroy();
+		} );
+		it( 'should be loaded and returned from the editor (for defined language)', async () => {
+			const editor = await getEditor(
+				'```javascript\n' +
+				'test()\n' +
+				'```'
+			);
+
+			expect( editor.getData() ).to.equal(
+				'```javascript\n' +
+				'test()\n' +
+				'```'
+			);
+
+			await editor.destroy();
+		} );
+	} );
+} );

+ 1 - 1
packages/ckeditor5-engine/docs/_snippets/framework/extending-content-add-unsafe-link-class.html

@@ -8,6 +8,6 @@
 
 <div id="snippet-link-unsafe-classes">
 	<p>All links in this <a href="https://ckeditor.com">editor</a> that do not use the <a href="http://developer.mozilla.org/en-US/docs/Glossary/https">HTTPS</a> protocol
-	have a custom <code>.unsafe-link</code> CSS <a href="http://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/class">class</a> that marks them red.</p>
+	have a custom <code>.unsafe-link</code> CSS <a href="http://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/class">class</a> that marks them with a predefined graphic differentiator.</p>
 	<p>Edit the URL of the links using "http://" or "https://" to see them marked as "safe" or "unsafe".</p>
 </div>

+ 2 - 2
packages/ckeditor5-engine/docs/_snippets/framework/extending-content-allow-div-attributes.html

@@ -1,12 +1,12 @@
 <div id="snippet-div-attributes">
 	<div id="special-section-a" style="background: #eafbd7;padding:.8em .8em 0;margin-bottom:.8em;border:1px solid #8bc34a;">
-		<p><strong>Special section A</strong>: It has set "style" and "id" attributes.</p>
+		<p><strong>Special section A</strong>: It has both the "style" and "id" attributes set.</p>
 	</div>
 
 	<p>Regular content of the editor.</p>
 
 	<div id="special-section-b" style="background: #ffeed0;padding:.8em .8em 0;margin-bottom:.8em;border:1px solid #ff8f00;" spellcheck="false">
-		<p><strong>Special section B</strong>: It has set "style", "id" and spellcheck="false" attributes.</p>
+		<p><strong>Special section B</strong>: It has the "style", "id" and spellcheck="false" attributes set.</p>
 		<p>This section disables the native browser spellchecker.</p>
 	</div>
 </div>

+ 26 - 8
packages/ckeditor5-engine/docs/_snippets/framework/extending-content-custom-element-converter.html

@@ -1,27 +1,45 @@
 <style>
 	.info-box {
+		background: hsl(0, 0%, 45%);
 		border: 1px solid hsl(0, 0%, 80%);
 		padding: 1em;
-		background: hsl(0, 0%, 45%);
+		border-radius: 8px;
+	}
+
+	.info-box-title {
+		margin-bottom: 0.5em;
+		font-size: 1.4em;
+		font-weight: bold;
+		color: inherit;
 	}
 
 	.info-box-warning {
-		background: hsl(64, 74%, 85%);
+		background: hsl(48, 100%, 87%);
+		border: 1px solid hsl(47, 100%, 62%);
+	}
+
+	.info-box-warning .info-box-title  {
+		color: hsl(47, 100%, 32%)
 	}
 
 	.info-box-info {
-		background: hsl(205, 100%, 90%);
+		background: hsl(205, 100%, 95%);
+		border: 1px solid hsl(205, 91%, 82%);
 	}
 
-	.info-box-title {
-		margin-bottom: 1em;
-		font-weight: bold;
-		color: inherit;
+	.info-box-info .info-box-title  {
+		color: hsl(204, 79%, 41%)
 	}
 
 	.info-box-content {
-		padding: 0 1em;
+		padding: 8px 10px;
 		background: hsl(0, 0%, 100%);
+		border-radius: 6px;
+	}
+
+	.info-box-content p:only-child,
+	.info-box-content p:last-child {
+		margin-bottom: 0;
 	}
 </style>
 

+ 53 - 54
packages/ckeditor5-engine/docs/framework/guides/deep-dive/conversion-extending-output.md

@@ -16,17 +16,17 @@ If you want to learn how to load some extra content (element, attributes, classe
 
 ### Code architecture
 
-It is recommended that the code that customizes the editor data and editing pipelines is delivered as {@link framework/guides/architecture/core-editor-architecture#plugins plugins} and all examples in this guide follow this convention.
+It is recommended for the code that customizes the editor data and editing pipelines to be delivered as {@link framework/guides/architecture/core-editor-architecture#plugins plugins} and all examples in this guide follow this convention.
 
 Also for the sake of simplicity all examples use the same {@link module:editor-classic/classiceditor~ClassicEditor `ClassicEditor`}, but keep in mind that code snippets will work with other editors, too.
 
-Finally, none of the converters covered in this guide require to import any module from CKEditor 5 Framework, hence, you can write them without rebuilding the editor. In other words, such converters can easily be added to existing {@link builds/guides/overview CKEditor 5 builds}.
+Finally, none of the converters covered in this guide requires to import any modules from CKEditor 5 Framework, hence, you can write them without rebuilding the editor. In other words, such converters can easily be added to existing {@link builds/guides/overview CKEditor 5 builds}.
 
 ### Granular converters
 
 You can create separate converters for the data and editing (downcast) pipelines. The former (`dataDowncast`) will customize the data in the editor output (e.g. when {@link builds/guides/integration/saving-data#manually-retrieving-the-data obtaining the editor data}). The latter (`editingDowncast`) will only work for the content of the editor when editing.
 
-If you do not want to complicate your conversion, you can just add a single (`downcast`) converter which will apply both to the data and the editing view. We did that in all examples to keep them simple but keep in mind you have options:
+If you do not want to complicate your conversion, you can just add a single (`downcast`) converter which will apply both to the data and the editing view. We did that in all the examples to keep them simple but keep in mind you have several options:
 
 ```js
 // Adds a conversion dispatcher for the editing downcast pipeline only.
@@ -47,32 +47,32 @@ editor.conversion.for( 'downcast' ).add( dispatcher => {
 
 ### CKEditor 5 inspector
 
-{@link framework/guides/development-tools#ckeditor-5-inspector CKEditor 5 inspector} is an invaluable help when working with the model and view structures. It allows browsing their structure and checking selection positions like in typical browser developer tools. Make sure to enable the inspector when playing with CKEditor 5.
+The {@link framework/guides/development-tools#ckeditor-5-inspector CKEditor 5 inspector} is an invaluable help when working with the model and view structures. It allows browsing their structure and checking selection positions like in typical browser developer tools. Make sure to enable the inspector when playing with CKEditor 5.
 
 ## Adding a CSS class to inline elements
 
 In this example all links (`<a href="...">...</a>`) get the `.my-green-link` CSS class. This includes all links in the editor output (`editor.getData()`) and all links in the edited content (existing and future ones).
 
-<info-box>
-	Note that the same behavior can be obtained with {@link features/link#custom-link-attributes-decorators link decorators}:
-
-	```js
-	ClassicEditor
-		.create( ..., {
-			// ...
-			link: {
-				decorators: {
-					addGreenLink: {
-						mode: 'automatic',
-						attributes: {
-							class: 'my-green-link'
-						}
+
+Note that the same behavior can be obtained with {@link features/link#custom-link-attributes-decorators link decorators}:
+
+```js
+ClassicEditor
+	.create( ..., {
+		// ...
+		link: {
+			decorators: {
+				addGreenLink: {
+					mode: 'automatic',
+					attributes: {
+						class: 'my-green-link'
 					}
 				}
 			}
-		} )
-	```
-</info-box>
+		}
+	} )
+```
+
 
 {@snippet framework/extending-content-add-link-class}
 
@@ -136,21 +136,20 @@ Add some CSS styles for `.my-green-link` to see the customization in action:
 
 ## Adding an HTML attribute to certain inline elements
 
-In this example all links (`<a href="...">...</a>`) that do not have "ckeditor.com" in their `href="..."` get the `target="_blank"` attribute. This includes all links in the editor output (`editor.getData()`) and all links in the edited content (existing and future ones).
+In this example all the links (`<a href="...">...</a>`) that do not have "ckeditor.com" in their `href="..."` get the `target="_blank"` attribute. This includes all links in the editor output (`editor.getData()`) and all links in the edited content (existing and future ones).
 
-<info-box>
-	Note that similar behavior can be obtained with {@link module:link/link~LinkConfig#addTargetToExternalLinks link decorators}:
-
-	```js
-	ClassicEditor
-		.create( ..., {
-			// ...
-			link: {
-				addTargetToExternalLinks: true
-			}
-		} )
-	```
-</info-box>
+
+Note that similar behavior can be obtained with {@link module:link/link~LinkConfig#addTargetToExternalLinks link decorators}:
+
+```js
+ClassicEditor
+	.create( ..., {
+		// ...
+		link: {
+			addTargetToExternalLinks: true
+		}
+	} )
+```
 
 {@snippet framework/extending-content-add-external-link-target}
 
@@ -216,27 +215,27 @@ a[target="_blank"]::after {
 
 In this example all links (`<a href="...">...</a>`) that do not have `https://` in their `href="..."` attribute get the `.unsafe-link` CSS class. This includes all links in the editor output (`editor.getData()`) and all links in the edited content (existing and future ones).
 
-<info-box>
-	Note that the same behavior can be obtained with {@link features/link#custom-link-attributes-decorators link decorators}:
-
-	```js
-	ClassicEditor
-		.create( ..., {
-			// ...
-			link: {
-				decorators: {
-					markUnsafeLink: {
-						mode: 'automatic',
-						callback: url => /^(http:)?\/\//.test( url ),
-						attributes: {
-							class: 'unsafe-link'
-						}
+
+Note that the same behavior can be obtained with {@link features/link#custom-link-attributes-decorators link decorators}:
+
+```js
+ClassicEditor
+	.create( ..., {
+		// ...
+		link: {
+			decorators: {
+				markUnsafeLink: {
+					mode: 'automatic',
+					callback: url => /^(http:)?\/\//.test( url ),
+					attributes: {
+						class: 'unsafe-link'
 					}
 				}
 			}
-		} )
-	```
-</info-box>
+		}
+	} )
+```
+
 
 {@snippet framework/extending-content-add-unsafe-link-class}
 
@@ -302,7 +301,7 @@ Add some CSS styles for "unsafe" links to make them visible:
 
 ## Adding a CSS class to block elements
 
-In this example all second–level headings (`<h2>...</h2>`) get the `.my-heading` CSS class. This includes all heading elements in the editor output (`editor.getData()`) and in the edited content (existing and future ones).
+In this example all second–level headings (`<h2>...</h2>`) get the `.my-heading` CSS class. This includes all the heading elements in the editor output (`editor.getData()`) and in the edited content (existing and future ones).
 
 {@snippet framework/extending-content-add-heading-class}
 

+ 9 - 9
packages/ckeditor5-engine/docs/framework/guides/deep-dive/conversion-introduction.md

@@ -12,13 +12,13 @@ order: 10
 
 This guide extends the {@link framework/guides/architecture/editing-engine introduction to CKEditor 5 editing engine architecture}. Therefore, we highly recommend reading the former guide first.
 
-In this guide we will dive deeper into some of the conversion concepts related to model attributes.
+In this guide you will dive deeper into some of the conversion concepts.
 
 ## Inline and block content
 
-Generally speaking, there are two main types of the content in the editor view and data output: inline and block.
+Generally speaking, there are two main types of content in the editor view and data output: inline and block.
 
-The inline content means elements like `<strong>`, `<a>` or `<span>`. Unlike `<p>`, `<blockquote>` or `<div>`, inline elements do not structure the data. Instead, they mark some text in a specific (visual and semantical) way. These elements are a characteristic of a text. For instance, you could say that some part of the text is bold, or is linked, etc.. This concept has its reflection in the model of the rich-text editor where `<a>` or `<strong>` are not represented as elements. Instead, they are attributes of the text.
+The inline content means elements like `<strong>`, `<a>` or `<span>`. Unlike `<p>`, `<blockquote>` or `<div>`, inline elements do not structure the data. Instead, they format some text in a specific (visual and semantical) way. These elements are a characteristic of a text. For instance, you could say that some part of the text is bold, or is linked, etc. This concept has its reflection in the model of the rich-text editor where `<a>` or `<strong>` are not represented as elements. Instead, they are the attributes of the text.
 
 For example &mdash; in the model, you might have a `<paragraph>` element with the "Foo bar" text, where "bar" has the `bold` attribute set to `true`. A pseudo–code of this *model* data structure could look as follows:
 
@@ -30,7 +30,7 @@ For example &mdash; in the model, you might have a `<paragraph>` element with th
 ```
 
 <info-box>
-	Throughout the rest of this guide the following, shorter convention will be used to represent model text attributes:
+	Throughout the rest of this guide the following, shorter convention will be used to represent model text attributes for the sake of clarity:
 
 	```html
 	<paragraph>Foo <$text bold="true">bar</$text></paragraph>
@@ -39,11 +39,11 @@ For example &mdash; in the model, you might have a `<paragraph>` element with th
 
 Note that there is no `<strong>` or any other additional element there, it is just some text with an attribute.
 
-So, when does this text become wrapped with a `<strong>` element? This happens during the conversion to the view. It is also important to know which type of a view element needs to be used. In case of elements that represent inline formatting, this should be an {@link module:engine/view/attributeelement~AttributeElement}.
+So, when does this text become wrapped with a `<strong>` element? This happens during the conversion to the view. It is also important to know what type of a view element needs to be used. In the case of the elements that represent inline formatting, this should be an {@link module:engine/view/attributeelement~AttributeElement}.
 
 ## Conversion of multiple text attributes
 
-A model text node may have multiple attributes (e.g. be bolded and linked) and all of them are converted to their respective view elements by independent converters.
+A model text node may have multiple attributes (e.g. be bolded and linked) and all of them are converted into their respective view elements by independent converters.
 
 Keep in mind that in the model, attributes do not have any specific order. This is contrary to the editor view or HTML output, where inline elements are nested in one another. Fortunately, the nesting happens automatically during the conversion from the model to the view. This makes working in the model simpler, as features do not need to take care of breaking or rearranging elements in the model.
 
@@ -73,7 +73,7 @@ Note that the `<a>` element is converted in such way that it always becomes the
 </p>
 ```
 
-There are two links with the same `href` attribute next to each other in the generated view (editor output), which is semantically wrong. To make sure that it never happens, the view element that represents a link must have a *priority* defined. Most elements, like for instance `<strong>`, do not care about it and stick to the default priority (`10`). The {@link features/link link feature} ensures that all view `<a>` elements have the priority set to `5` so they are kept outside other elements.
+There are two links with the same `href` attribute next to each other in the generated view (editor output), which is semantically wrong. To make sure that it never happens, the view element that represents a link must have a *priority* defined. Most elements, like for instance `<strong>`, do not care about it and stick to the default priority (`10`). The {@link features/link link feature} ensures that all `<a>` view elements have the priority set to `5` therefore they are kept outside other elements.
 
 ## Merging attribute elements during conversion
 
@@ -112,9 +112,9 @@ But this is not the most optimal output you can get from the rich-text editor. W
 </p>
 ```
 
-Obviously a single `<span>` makes more sense. And thanks to the merging mechanism built into the conversion process, this would be the actual result of the conversion.
+Obviously a single `<span>` makes more sense. And thanks to the merging mechanism built into the conversion process, this would be the actual output of the conversion.
 
-Why is it so? In the above scenario, two model attributes are converted to `<span>` elements. When the first attribute (say, `fontFamily`) is converted, there is no `<span>` in the view yet. So the first `<span>` is added with the `style` attribute. But then, when `fontSize` is converted, the `<span>` is already in the view. The {@link module:engine/view/downcastwriter~DowncastWriter downcast writer} recognizes it and checks whether the elements can be merged, following these 3 rules:
+Why is it so? In the above scenario, two model attributes are converted to `<span>` elements. When the first attribute (say, `fontFamily`) is converted, there is no `<span>` in the view yet. So the first `<span>` is added with the `style` attribute. But then, when `fontSize` is converted, the `<span>` is already in the view. The {@link module:engine/view/downcastwriter~DowncastWriter downcast writer} recognizes it and checks whether these elements can be merged, following these 3 rules:
 
 1. Both elements must have the same {@link module:engine/view/element~Element#name name}.
 2. Both elements must have the same {@link module:engine/view/attributeelement~AttributeElement#priority priority}.

+ 43 - 43
packages/ckeditor5-engine/docs/framework/guides/deep-dive/conversion-preserving-custom-content.md

@@ -16,42 +16,41 @@ Eventually, this knowledge will allow you to create your custom features on top
 
 ### Code architecture
 
-It is recommended that the code that customizes the editor data and editing pipelines is delivered as {@link framework/guides/architecture/core-editor-architecture#plugins plugins} and all examples in this guide follow this convention.
+It is recommended for the code that customizes the editor data and editing pipelines to be delivered as {@link framework/guides/architecture/core-editor-architecture#plugins plugins} and all examples in this guide follow this convention.
 
 Also for the sake of simplicity all examples use the same {@link module:editor-classic/classiceditor~ClassicEditor `ClassicEditor`}, but keep in mind that code snippets will work with other editors, too.
 
-Finally, none of the converters covered in this guide require to import any module from CKEditor 5 Framework, hence, you can write them without rebuilding the editor. In other words, such converters can easily be added to existing {@link builds/guides/overview CKEditor 5 builds}.
+Finally, none of the converters covered in this guide requires to import any modules from CKEditor 5 Framework, hence, you can write them without rebuilding the editor. In other words, such converters can easily be added to existing {@link builds/guides/overview CKEditor 5 builds}.
 
 ### CKEditor 5 inspector
 
-{@link framework/guides/development-tools#ckeditor-5-inspector CKEditor 5 inspector} is an invaluable help when working with the model and view structures. It allows browsing their structure and checking selection positions like in typical browser developer tools. Make sure to enable the inspector when playing with CKEditor 5.
+The {@link framework/guides/development-tools#ckeditor-5-inspector CKEditor 5 inspector} is an invaluable help when working with the model and view structures. It allows browsing their structure and checking selection positions like in typical browser developer tools. Make sure to enable the inspector when playing with CKEditor 5.
 
 ## Loading content with a custom attribute
 
-In this example links (`<a href="...">...</a>`) loaded into the editor content will preserve their `target` attribute, which is not supported by the {@link features/link Link} feature. The DOM `target` attribute will be stored in the editor model as a `linkTarget` attribute.
+In this example the links (`<a href="...">...</a>`) loaded into the editor content will preserve their `target` attribute, which is by default *not* supported by the {@link features/link Link} feature. The DOM `target` attribute will be stored in the editor model as a `linkTarget` attribute.
 
-Unlike the {@link framework/guides/deep-dive/conversion-extending-output#adding-an-html-attribute-to-certain-inline-elements downcast–only solution}, this approach does not change the content loaded into the editor. Links without the `target` attribute will not get one and links with the attribute will preserve its value.
+Unlike the {@link framework/guides/deep-dive/conversion-extending-output#adding-an-html-attribute-to-certain-inline-elements downcast–only solution}, this approach does not change the content loaded into the editor. Any links without the `target` attribute will not get one while all the links with the attribute will preserve its value.
 
-<info-box>
-	Note that the same behavior can be obtained with {@link features/link#custom-link-attributes-decorators link decorators}:
-
-	```js
-	ClassicEditor
-		.create( ..., {
-			// ...
-			link: {
-				decorators: {
-					addGreenLink: {
-						mode: 'automatic',
-						attributes: {
-							class: 'my-green-link'
-						}
+
+Note that the same behavior can be obtained with {@link features/link#custom-link-attributes-decorators link decorators}:
+
+```js
+ClassicEditor
+	.create( ..., {
+		// ...
+		link: {
+			decorators: {
+				addGreenLink: {
+					mode: 'automatic',
+					attributes: {
+						class: 'my-green-link'
 					}
 				}
 			}
-		} )
-	```
-</info-box>
+		}
+	} )
+```
 
 {@snippet framework/extending-content-allow-link-target}
 
@@ -119,7 +118,7 @@ a[target]::after {
 
 ## Loading content with all attributes
 
-In this example `<div>` elements (`<div>...</div>`) loaded into the editor content will preserve their attributes. All the DOM attributes will be stored in the editor model as corresponding attributes.
+In this example the `<div>` elements (`<div>...</div>`) loaded into the editor content will preserve their attributes. All the DOM attributes will be stored in the editor model as corresponding attributes.
 
 {@snippet framework/extending-content-allow-div-attributes}
 
@@ -128,10 +127,10 @@ All attributes are allowed on `<div>` elements thanks to custom "upcast" and "do
 Allowing every possible attribute on a `<div>` element in the model is done by adding an {@link module:engine/model/schema~Schema#addAttributeCheck addAttributeCheck()} callback.
 
 <info-box>
-	Allowing every attribute on `<div>` elements might introduce security issues &mdash; including XSS attacks. The production code should use only application-related attributes and/or properly encode data.
+	Allowing every attribute on `<div>` elements might introduce security issues &mdash; including XSS attacks. The production code should use only application-related attributes and/or properly encode the data.
 </info-box>
 
-Adding "upcast" and "downcast" converters for the `<div>` element is enough for cases where its attributes do not change. If the attributes in the model are modified, these `elementToElement()` converters will not be called as the `<div>` is already converted. To overcome this, a lower-level API is used.
+Adding "upcast" and "downcast" converters for the `<div>` element is enough for these cases where its attributes do not change. If the attributes in the model are modified, however, these `elementToElement()` converters will not be called as the `<div>` is already converted. To overcome this, a lower-level API is used.
 
 Instead of using predefined converters, the {@link module:engine/conversion/downcastdispatcher~DowncastDispatcher#event-attribute `attribute`} event listener is registered for the "downcast" dispatcher.
 
@@ -150,7 +149,7 @@ function ConvertDivAttributes( editor ) {
 		}
 	} );
 
-	// View-to-model converter converting a view <div> with all its attributes to the model.
+	// The view-to-model converter converting a view <div> with all its attributes to the model.
 	editor.conversion.for( 'upcast' ).elementToElement( {
 		view: 'div',
 		model: ( viewElement, modelWriter ) => {
@@ -158,13 +157,13 @@ function ConvertDivAttributes( editor ) {
 		}
 	} );
 
-	// Model-to-view converter for the <div> element (attributes are converted separately).
+	// The model-to-view converter for the <div> element (attributes are converted separately).
 	editor.conversion.for( 'downcast' ).elementToElement( {
 		model: 'div',
 		view: 'div'
 	} );
 
-	// Model-to-view converter for <div> attributes.
+	// The model-to-view converter for <div> attributes.
 	// Note that a lower-level, event-based API is used here.
 	editor.conversion.for( 'downcast' ).add( dispatcher => {
 		dispatcher.on( 'attribute', ( evt, data, conversionApi ) => {
@@ -229,8 +228,8 @@ function HandleFontSizeValue( editor ) {
 			value: viewElement => {
 				const value = parseFloat( viewElement.getStyle( 'font-size' ) ).toFixed( 0 );
 
-				// It might be needed to further convert the value to meet business requirements.
-				// In the sample the font size is configured to handle only the sizes:
+				// It might be necessary to further convert the value to meet business requirements.
+				// In the sample the font size is configured to handle only these sizes:
 				// 12, 14, 'default', 18, 20, 22, 24, 26, 28, 30
 				// Other sizes will be converted to the model but the UI might not be aware of them.
 
@@ -241,7 +240,7 @@ function HandleFontSizeValue( editor ) {
 		converterPriority: 'high'
 	} );
 
-	// Add a special converter for the font size feature to convert all (even not configured)
+	// Add a special converter for the font size feature to convert all (even the not configured)
 	// model attribute values.
 	editor.conversion.for( 'downcast' ).attributeToElement( {
 		model: {
@@ -278,7 +277,7 @@ ClassicEditor
 
 ## Adding extra attributes to elements contained in a figure
 
-The {@link features/image Image} and {@link features/table Table} features wrap view elements (`<img>` for Image nad `<table>` for Table) in `<figure>`. During the downcast conversion, the model element is mapped to `<figure>` and not the inner element. In such cases the default `conversion.attributeToAttribute()` conversion helpers could lose information about the element that the attribute should be set on.
+The {@link features/image image} and {@link features/table table} features wrap view elements (`<img>` for image and `<table>` for table, respectively) in a `<figure>` element. During the downcast conversion, the model element is mapped to `<figure>` and not the inner element. In such cases the default `conversion.attributeToAttribute()` conversion helpers could lose information about the element that the attribute should be set on.
 
 To overcome this limitation it is sufficient to write a custom converter that adds custom attributes to elements already converted by base features. The key point is to add these converters with a lower priority than the base converters so they will be called after the base ones.
 
@@ -288,11 +287,11 @@ The sample below is extensible. To add your own attributes to preserve, just add
 
 ```js
 /**
- * Plugin that converts custom attributes for elements that are wrapped in <figure> in the view.
+ * A plugin that converts custom attributes for elements that are wrapped in <figure> in the view.
  */
 class CustomFigureAttributes {
 	/**
-	 * Plugin's constructor - receives editor instance on creation.
+	 * Plugin's constructor - receives an editor instance on creation.
 	 */
 	constructor( editor ) {
 		// Save reference to the editor.
@@ -300,9 +299,9 @@ class CustomFigureAttributes {
 	}
 
 	/**
-	 * Setups conversion and extends table & image features schema.
+	 * Sets the conversion up and extends the table & image features schema.
 	 *
-	 * Schema extending must be done in the “afterInit()” call because plugins define their schema in “init()“.
+	 * Schema extending must be done in the "afterInit()" call because plugins define their schema in "init()".
 	 */
 	afterInit() {
 		const editor = this.editor;
@@ -320,23 +319,24 @@ class CustomFigureAttributes {
 }
 
 /**
- * Sets up a conversion that preservers classes on <img> and <table> elements.
+ * Sets up a conversion that preserves classes on <img> and <table> elements.
  */
 function setupCustomClassConversion( viewElementName, modelElementName, editor ) {
-	// The 'customClass' attribute will store custom classes from the data in the model so schema definitions allow this attribute.
+	// The 'customClass' attribute stores custom classes from the data in the model so that schema definitions allow this attribute.
 	editor.model.schema.extend( modelElementName, { allowAttributes: [ 'customClass' ] } );
 
-	// Define upcast converters for the <img> and <table> elements with a "low" priority so they are run after the default converters.
+	// Defines upcast converters for the <img> and <table> elements with a "low" priority so they are run after the default converters.
 	editor.conversion.for( 'upcast' ).add( upcastCustomClasses( viewElementName ), { priority: 'low' } );
 
-	// Define downcast converters for a model element with a "low" priority so they are run after the default converters.
-	// Use `downcastCustomClassesToFigure` if you'd like to keep your classes on <figure> element or `downcastCustomClassesToChild` if you'd like to keep your classes on a <figure> child element, i.e. <img>.
+	// Defines downcast converters for a model element with a "low" priority so they are run after the default converters.
+	// Use `downcastCustomClassesToFigure` if you want to keep your classes on <figure> element or `downcastCustomClassesToChild`
+	// if you would like to keep your classes on a <figure> child element, i.e. <img>.
 	editor.conversion.for( 'downcast' ).add( downcastCustomClassesToFigure( modelElementName ), { priority: 'low' } );
 	// editor.conversion.for( 'downcast' ).add( downcastCustomClassesToChild( viewElementName, modelElementName ), { priority: 'low' } );
 }
 
 /**
- * Sets up a conversion for a custom attribute on view elements contained inside a <figure>.
+ * Sets up a conversion for a custom attribute on the view elements contained inside a <figure>.
  *
  * This method:
  * - Adds proper schema rules.
@@ -344,7 +344,7 @@ function setupCustomClassConversion( viewElementName, modelElementName, editor )
  * - Adds a downcast converter.
  */
 function setupCustomAttributeConversion( viewElementName, modelElementName, viewAttribute, editor ) {
-	// Extend the schema to store an attribute in the model.
+	// Extends the schema to store an attribute in the model.
 	const modelAttribute = `custom${ viewAttribute }`;
 
 	editor.model.schema.extend( modelElementName, { allowAttributes: [ modelAttribute ] } );

+ 8 - 8
packages/ckeditor5-engine/docs/framework/guides/deep-dive/schema.md

@@ -11,9 +11,9 @@ This article assumes that you have already read the {@link framework/guides/arch
 
 The editor's schema is available in the {@link module:engine/model/model~Model#schema `editor.model.schema`} property. It defines allowed model structures (how model elements can be nested), allowed attributes (of both elements and text nodes), and other characteristics (inline vs. block, atomicity in regards of external actions). This information is later used by editing features and the editing engine to decide how to process the model, where to enable features, etc.
 
-Schema rules can be defined by using the {@link module:engine/model/schema~Schema#register `Schema#register()`} or {@link module:engine/model/schema~Schema#extend `Schema#extend()`} methods. The former can be used only once for a given item name which ensures that only a single editing feature can introduce this item. Similarly, `extend()` can only be used for defined items.
+Schema rules can be defined by using the {@link module:engine/model/schema~Schema#register `Schema#register()`} or the {@link module:engine/model/schema~Schema#extend `Schema#extend()`} methods. The former can be used only once for a given item name which ensures that only a single editing feature can introduce this item. Similarly, `extend()` can only be used for defined items.
 
-Elements and attributes are checked by features separately by using the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`} and {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} methods.
+Elements and attributes are checked by features separately by using the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`} and the {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} methods.
 
 ## Defining allowed structures
 
@@ -47,7 +47,7 @@ While this would be incorrect:
 
 ## Defining additional semantics
 
-In addition to setting allowed structures, the schema can also define additional traits of model elements. By using the `is*` properties, a feature author may declare how a certain element should be treated by other features and the engine.
+In addition to setting allowed structures, the schema can also define additional traits of model elements. By using the `is*` properties, a feature author may declare how a certain element should be treated by other features and by the engine.
 
 Here is a table listing various model elements and their properties registered in the schema:
 
@@ -292,7 +292,7 @@ The engine and various features then check it via {@link module:engine/model/sch
 
 For an image caption like in the example above it does not make much sense to select the caption box, then copy or drag it somewhere else.
 
-A caption without the image that it describes makes little sense. However, the image is more self-sufficient. Most likely users should be able to select the entire image (with all its internals), then copy or move it around. The {@link module:engine/model/schema~SchemaItemDefinition#isObject `isObject`} property should be used to mark such behavior.
+A caption without the image it describes makes little sense. The image, however, is more self-sufficient. Most likely users should be able to select the entire image (with all its internals), then copy or move it around. The {@link module:engine/model/schema~SchemaItemDefinition#isObject `isObject`} property should be used to mark such behavior.
 
 ```js
 schema.register( 'myImage', {
@@ -324,7 +324,7 @@ It is important to remember that a block should not allow another block inside.
 
 In the editor, all HTML formatting elements such as `<strong>` or `<code>` are represented by text attributes. Therefore, inline model elements are not supposed to be used for these scenarios.
 
-Currently, the {@link module:engine/model/schema~SchemaItemDefinition#isInline `isInline`} property is used for the `$text` token (so, text nodes) and elements such as `<softBreak>` or placeholder elements such as in the {@link framework/guides/tutorials/implementing-an-inline-widget Implementing an inline widget} tutorial.
+Currently, the {@link module:engine/model/schema~SchemaItemDefinition#isInline `isInline`} property is used for the `$text` token (so, text nodes) and elements such as `<softBreak>` or placeholder elements such as described in the {@link framework/guides/tutorials/implementing-an-inline-widget Implementing an inline widget} tutorial.
 
 The support for inline elements in CKEditor 5 is so far limited to self-contained elements. Because of this, all elements marked with `isInline` should also be marked with `isObject`.
 
@@ -401,7 +401,7 @@ schema.register( 'paragraph', {
 } );
 ```
 
-Which can be read as:
+And this can be read as:
 
 * The `<paragraph>` element will be allowed in elements in which `<$block>` is allowed (e.g. in `<$root>`).
 * The `<paragraph>` element will allow all nodes that are allowed in `<$block>` (e.g. `$text`).
@@ -427,7 +427,7 @@ The side effect of such a definition inheritance is that now `<blockQuote>` is a
 
 ## Defining advanced rules in `checkChild()` callbacks
 
-The {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`} method which is the base method used to check whether some element is allowed in a given structure is {@link module:utils/observablemixin~ObservableMixin#decorate a decorated method}. It means that you can add listeners to implement your specific rules which are not limited by the {@link module:engine/model/schema~SchemaItemDefinition declarative `SchemaItemDefinition` API}.
+The {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`} method which is the a base method used to check whether some element is allowed in a given structure is {@link module:utils/observablemixin~ObservableMixin#decorate a decorated method}. It means that you can add listeners to implement your specific rules which are not limited by the {@link module:engine/model/schema~SchemaItemDefinition declarative `SchemaItemDefinition` API}.
 
 These listeners can be added either by listening directly to the {@link module:engine/model/schema~Schema#event:checkChild} event or by using the handy {@link module:engine/model/schema~Schema#addChildCheck `Schema#addChildCheck()`} method.
 
@@ -485,7 +485,7 @@ While this is a relatively simple scenario (unlike most real-time collaborative
 
 Therefore, if your editor needs to implement such rules, you should do that through {@link module:engine/model/document~Document#registerPostFixer model's post-fixers} fixing incorrect content or actively prevent such situations (e.g. by disabling certain features). It means that these constraints will be defined specifically for your scenario by your code which makes their implementation much easier.
 
-To sum up, the answer to who and how should implement additional constraints is: Your features or your editor through the CKEditor 5 API.
+To sum up, the answer to who and how should implement additional constraints is: your features or your editor through the CKEditor 5 API.
 
 ## Who checks the schema?
 

+ 2 - 2
packages/ckeditor5-engine/src/dev-utils/view.js

@@ -51,9 +51,9 @@ const allowedTypes = {
  * the default `main` name will be used.
  * @param {Boolean} [options.showType=false] When set to `true`, the type of elements will be printed (`<container:p>`
  * instead of `<p>`, `<attribute:b>` instead of `<b>` and `<empty:img>` instead of `<img>`).
- * @param {Boolean} [options.showPriority=false] When set to `true`, attribute element's priority will be printed
+ * @param {Boolean} [options.showPriority=false] When set to `true`, the attribute element's priority will be printed
  * (`<span view-priority="12">`, `<b view-priority="10">`).
- * @param {Boolean} [options.showAttributeElementId=false] When set to `true`, attribute element's id will be printed
+ * @param {Boolean} [options.showAttributeElementId=false] When set to `true`, the attribute element's ID will be printed
  * (`<span id="marker:foo">`).
  * @param {Boolean} [options.renderUIElements=false] When set to `true`, the inner content of each
  * {@link module:engine/view/uielement~UIElement} will be printed.

+ 7 - 2
packages/ckeditor5-engine/src/model/utils/insertcontent.js

@@ -443,12 +443,17 @@ class Insertion {
 				// At this point the insertion position should be after the node we'll merge. If it isn't,
 				// it should need to be secured as in the left merge case.
 				/**
-				 * An internal error occured during merging insertion content with siblings.
+				 * An internal error occurred during merging inserted content with its siblings.
 				 * The insertion position should equal to the merge position.
 				 *
+				 * If you encountered this error, report it back to the CKEditor 5 team
+				 * with as many details regarding the content being inserted and the insertion position
+				 * as possible.
+				 *
 				 * @error insertcontent-invalid-insertion-position
 				 */
-				throw new CKEditorError( 'insertcontent-invalid-insertion-position', this );
+				throw new CKEditorError( 'insertcontent-invalid-insertion-position: ' +
+					'An internal error occurred during insertContent().', this );
 			}
 
 			// Move the position to the previous node, so it isn't moved to the graveyard on merge.

+ 15 - 14
packages/ckeditor5-engine/src/view/domconverter.js

@@ -32,20 +32,21 @@ const BR_FILLER_REF = BR_FILLER( document );
  * `DomConverter` is a set of tools to do transformations between DOM nodes and view nodes. It also handles
  * {@link module:engine/view/domconverter~DomConverter#bindElements bindings} between these nodes.
  *
- * The instance of `DOMConverter` is available under {@link module:engine/view/view~View#domConverter `editor.editing.view.domConverter`}.
+ * An instance of the DOM converter is available under
+ * {@link module:engine/view/view~View#domConverter `editor.editing.view.domConverter`}.
  *
- * `DomConverter` does not check which nodes should be rendered (use {@link module:engine/view/renderer~Renderer}), does not keep a
- * state of a tree nor keeps synchronization between tree view and DOM tree (use {@link module:engine/view/document~Document}).
+ * The DOM converter does not check which nodes should be rendered (use {@link module:engine/view/renderer~Renderer}), does not keep the
+ * state of a tree nor keeps the synchronization between the tree view and the DOM tree (use {@link module:engine/view/document~Document}).
  *
- * `DomConverter` keeps DOM elements to View element bindings, so when the converter gets destroyed, the bindings are lost.
+ * The DOM converter keeps DOM elements to view element bindings, so when the converter gets destroyed, the bindings are lost.
  * Two converters will keep separate binding maps, so one tree view can be bound with two DOM trees.
  */
 export default class DomConverter {
 	/**
-	 * Creates DOM converter.
+	 * Creates a DOM converter.
 	 *
 	 * @param {module:engine/view/document~Document} document The view document instance.
-	 * @param {Object} options Object with configuration options.
+	 * @param {Object} options An object with configuration options.
 	 * @param {module:engine/view/filler~BlockFillerMode} [options.blockFillerMode='br'] The type of the block filler to use.
 	 */
 	constructor( document, options = {} ) {
@@ -56,7 +57,7 @@ export default class DomConverter {
 		this.document = document;
 
 		/**
-		 * The mode of a block filler used by DOM converter.
+		 * The mode of a block filler used by the DOM converter.
 		 *
 		 * @readonly
 		 * @member {'br'|'nbsp'} module:engine/view/domconverter~DomConverter#blockFillerMode
@@ -86,7 +87,7 @@ export default class DomConverter {
 
 		/**
 		 * Block {@link module:engine/view/filler filler} creator, which is used to create all block fillers during the
-		 * view to DOM conversion and to recognize block fillers during the DOM to view conversion.
+		 * view-to-DOM conversion and to recognize block fillers during the DOM-to-view conversion.
 		 *
 		 * @readonly
 		 * @private
@@ -95,7 +96,7 @@ export default class DomConverter {
 		this._blockFiller = this.blockFillerMode == 'br' ? BR_FILLER : NBSP_FILLER;
 
 		/**
-		 * DOM to View mapping.
+		 * The DOM-to-view mapping.
 		 *
 		 * @private
 		 * @member {WeakMap} module:engine/view/domconverter~DomConverter#_domToViewMapping
@@ -103,7 +104,7 @@ export default class DomConverter {
 		this._domToViewMapping = new WeakMap();
 
 		/**
-		 * View to DOM mapping.
+		 * The view-to-DOM mapping.
 		 *
 		 * @private
 		 * @member {WeakMap} module:engine/view/domconverter~DomConverter#_viewToDomMapping
@@ -111,7 +112,7 @@ export default class DomConverter {
 		this._viewToDomMapping = new WeakMap();
 
 		/**
-		 * Holds mapping between fake selection containers and corresponding view selections.
+		 * Holds the mapping between fake selection containers and corresponding view selections.
 		 *
 		 * @private
 		 * @member {WeakMap} module:engine/view/domconverter~DomConverter#_fakeSelectionMapping
@@ -894,15 +895,15 @@ export default class DomConverter {
 	}
 
 	/**
-	 * Checks if given selection's boundaries are at correct places.
+	 * Checks if the given selection's boundaries are at correct places.
 	 *
 	 * The following places are considered as incorrect for selection boundaries:
 	 *
-	 * * before or in the middle of the inline filler sequence,
+	 * * before or in the middle of an inline filler sequence,
 	 * * inside a DOM element which represents {@link module:engine/view/uielement~UIElement a view UI element},
 	 * * inside a DOM element which represents {@link module:engine/view/rawelement~RawElement a view raw element}.
 	 *
-	 * @param {Selection} domSelection DOM Selection object to be checked.
+	 * @param {Selection} domSelection The DOM selection object to be checked.
 	 * @returns {Boolean} `true` if the given selection is at a correct place, `false` otherwise.
 	 */
 	isDomSelectionCorrect( domSelection ) {

+ 87 - 45
packages/ckeditor5-engine/src/view/downcastwriter.js

@@ -155,7 +155,7 @@ export default class DowncastWriter {
 	}
 
 	/**
-	 * Creates new {@link module:engine/view/attributeelement~AttributeElement}.
+	 * Creates a new {@link module:engine/view/attributeelement~AttributeElement}.
 	 *
 	 *		writer.createAttributeElement( 'strong' );
 	 *		writer.createAttributeElement( 'a', { href: 'foo.bar' } );
@@ -188,7 +188,7 @@ export default class DowncastWriter {
 	}
 
 	/**
-	 * Creates new {@link module:engine/view/containerelement~ContainerElement}.
+	 * Creates a new {@link module:engine/view/containerelement~ContainerElement}.
 	 *
 	 *		writer.createContainerElement( 'p' );
 	 *
@@ -210,7 +210,7 @@ export default class DowncastWriter {
 	}
 
 	/**
-	 * Creates new {@link module:engine/view/editableelement~EditableElement}.
+	 * Creates a new {@link module:engine/view/editableelement~EditableElement}.
 	 *
 	 *		writer.createEditableElement( 'div' );
 	 *		writer.createEditableElement( 'div', { id: 'foo-1234' } );
@@ -230,7 +230,7 @@ export default class DowncastWriter {
 	}
 
 	/**
-	 * Creates new {@link module:engine/view/emptyelement~EmptyElement}.
+	 * Creates a new {@link module:engine/view/emptyelement~EmptyElement}.
 	 *
 	 *		writer.createEmptyElement( 'img' );
 	 *		writer.createEmptyElement( 'img', { id: 'foo-1234' } );
@@ -244,12 +244,12 @@ export default class DowncastWriter {
 	}
 
 	/**
-	 * Creates new {@link module:engine/view/uielement~UIElement}.
+	 * Creates a new {@link module:engine/view/uielement~UIElement}.
 	 *
 	 *		writer.createUIElement( 'span' );
 	 *		writer.createUIElement( 'span', { id: 'foo-1234' } );
 	 *
-	 * Custom render function can be provided as third parameter:
+	 * A custom render function can be provided as the third parameter:
 	 *
 	 *		writer.createUIElement( 'span', null, function( domDocument ) {
 	 *			const domElement = this.toDomElement( domDocument );
@@ -263,10 +263,10 @@ export default class DowncastWriter {
 	 *
 	 * You should not use UI elements as data containers. Check out {@link #createRawElement} instead.
 	 *
-	 * @param {String} name Name of the element.
-	 * @param {Object} [attributes] Elements attributes.
-	 * @param {Function} [renderFunction] Custom render function.
-	 * @returns {module:engine/view/uielement~UIElement} Created element.
+	 * @param {String} name The name of the element.
+	 * @param {Object} [attributes] Element attributes.
+	 * @param {Function} [renderFunction] A custom render function.
+	 * @returns {module:engine/view/uielement~UIElement} The created element.
 	 */
 	createUIElement( name, attributes, renderFunction ) {
 		const uiElement = new UIElement( this.document, name, attributes );
@@ -288,18 +288,19 @@ export default class DowncastWriter {
 	 * Raw elements work as data containers ("wrappers", "sandboxes") but their children are not managed or
 	 * even recognized by the editor. This encapsulation allows integrations to maintain custom DOM structures
 	 * in the editor content without, for instance, worrying about compatibility with other editor features.
-	 * Raw elements make a perfect tool for integration with external frameworks and data sources.
+	 * Raw elements are a perfect tool for integration with external frameworks and data sources.
 	 *
-	 * Unlike {@link #createUIElement ui elements}, raw elements act like a "real" editor content (similar to
+	 * Unlike {@link #createUIElement UI elements}, raw elements act like "real" editor content (similar to
 	 * {@link module:engine/view/containerelement~ContainerElement} or {@link module:engine/view/emptyelement~EmptyElement}),
 	 * and they are considered by the editor selection.
 	 *
-	 * You should not use raw elements to render UI in the editor content. Check out {@link #createUIElement `#createUIElement()`} instead.
+	 * You should not use raw elements to render the UI in the editor content. Check out {@link #createUIElement `#createUIElement()`}
+	 * instead.
 	 *
-	 * @param {String} name Name of the element.
-	 * @param {Object} [attributes] Elements attributes.
-	 * @param {Function} [renderFunction] Custom render function.
-	 * @returns {module:engine/view/rawelement~RawElement} Created element.
+	 * @param {String} name The name of the element.
+	 * @param {Object} [attributes] Element attributes.
+	 * @param {Function} [renderFunction] A custom render function.
+	 * @returns {module:engine/view/rawelement~RawElement} The created element.
 	 */
 	createRawElement( name, attributes, renderFunction ) {
 		const rawElement = new RawElement( this.document, name, attributes );
@@ -310,12 +311,12 @@ export default class DowncastWriter {
 	}
 
 	/**
-	 * Adds or overwrite element's attribute with a specified key and value.
+	 * Adds or overwrites the element's attribute with a specified key and value.
 	 *
 	 *		writer.setAttribute( 'href', 'http://ckeditor.com', linkElement );
 	 *
-	 * @param {String} key Attribute key.
-	 * @param {String} value Attribute value.
+	 * @param {String} key The attribute key.
+	 * @param {String} value The attribute value.
 	 * @param {module:engine/view/element~Element} element
 	 */
 	setAttribute( key, value, element ) {
@@ -426,10 +427,10 @@ export default class DowncastWriter {
 	}
 
 	/**
-	 * Breaks attribute nodes at provided position or at boundaries of provided range. It breaks attribute elements inside
-	 * up to a container element.
+	 * Breaks attribute elements at provided position or at boundaries of a provided range. It breaks attribute elements
+	 * up to their first ancestor that is a container element.
 	 *
-	 * In following examples `<p>` is a container, `<b>` and `<u>` are attribute nodes:
+	 * In following examples `<p>` is a container, `<b>` and `<u>` are attribute elements:
 	 *
 	 *		<p>foo<b><u>bar{}</u></b></p> -> <p>foo<b><u>bar</u></b>[]</p>
 	 *		<p>foo<b><u>{}bar</u></b></p> -> <p>foo{}<b><u>bar</u></b></p>
@@ -684,7 +685,10 @@ export default class DowncastWriter {
 			 *
 			 * @error view-writer-invalid-position-container
 			 */
-			throw new CKEditorError( 'view-writer-invalid-position-container', this.document );
+			throw new CKEditorError(
+				'view-writer-invalid-position-container: Position\'s parent container cannot be found.',
+				this.document
+			);
 		}
 
 		const insertionPosition = this._breakAttributes( position, true );
@@ -871,7 +875,10 @@ export default class DowncastWriter {
 	 */
 	wrap( range, attribute ) {
 		if ( !( attribute instanceof AttributeElement ) ) {
-			throw new CKEditorError( 'view-writer-wrap-invalid-attribute', this.document );
+			throw new CKEditorError(
+				'view-writer-wrap-invalid-attribute: DowncastWriter#wrap() must be called with an attribute element.',
+				this.document
+			);
 		}
 
 		validateRangeContainer( range, this.document );
@@ -912,11 +919,15 @@ export default class DowncastWriter {
 	unwrap( range, attribute ) {
 		if ( !( attribute instanceof AttributeElement ) ) {
 			/**
-			 * Attribute element need to be instance of attribute element.
+			 * The `attribute` passed to {@link module:engine/view/downcastwriter~DowncastWriter#unwrap `DowncastWriter#unwrap()`}
+			 * must be an instance of {@link module:engine/view/attributeelement~AttributeElement `AttributeElement`}.
 			 *
 			 * @error view-writer-unwrap-invalid-attribute
 			 */
-			throw new CKEditorError( 'view-writer-unwrap-invalid-attribute', this.document );
+			throw new CKEditorError(
+				'view-writer-unwrap-invalid-attribute: DowncastWriter#unwrap() must be called with an attribute element.',
+				this.document
+			);
 		}
 
 		validateRangeContainer( range, this.document );
@@ -1592,31 +1603,43 @@ export default class DowncastWriter {
 		// If position is placed inside EmptyElement - throw an exception as we cannot break inside.
 		if ( position.parent.is( 'emptyElement' ) ) {
 			/**
-			 * Cannot break inside EmptyElement instance.
+			 * Cannot break an `EmptyElement` instance.
+			 *
+			 * This error is thrown if
+			 * {@link module:engine/view/downcastwriter~DowncastWriter#breakAttributes `DowncastWriter#breakAttributes()`}
+			 * was executed in an incorrect position.
 			 *
 			 * @error view-writer-cannot-break-empty-element
 			 */
-			throw new CKEditorError( 'view-writer-cannot-break-empty-element', this.document );
+			throw new CKEditorError( 'view-writer-cannot-break-empty-element: Cannot break an EmptyElement instance.', this.document );
 		}
 
 		// If position is placed inside UIElement - throw an exception as we cannot break inside.
 		if ( position.parent.is( 'uiElement' ) ) {
 			/**
-			 * Cannot break inside UIElement instance.
+			 * Cannot break a `UIElement` instance.
+			 *
+			 * This error is thrown if
+			 * {@link module:engine/view/downcastwriter~DowncastWriter#breakAttributes `DowncastWriter#breakAttributes()`}
+			 * was executed in an incorrect position.
 			 *
 			 * @error view-writer-cannot-break-ui-element
 			 */
-			throw new CKEditorError( 'view-writer-cannot-break-ui-element', this.document );
+			throw new CKEditorError( 'view-writer-cannot-break-ui-element: Cannot break a UIElement instance.', this.document );
 		}
 
 		// If position is placed inside RawElement - throw an exception as we cannot break inside.
 		if ( position.parent.is( 'rawElement' ) ) {
 			/**
-			 * Cannot break inside RawElement instance.
+			 * Cannot break a `RawElement` instance.
+			 *
+			 * This error is thrown if
+			 * {@link module:engine/view/downcastwriter~DowncastWriter#breakAttributes `DowncastWriter#breakAttributes()`}
+			 * was executed in an incorrect position.
 			 *
 			 * @error view-writer-cannot-break-raw-element
 			 */
-			throw new CKEditorError( 'view-writer-cannot-break-raw-element: Cannot break inside a RawElement instance.', this.document );
+			throw new CKEditorError( 'view-writer-cannot-break-raw-element: Cannot break a RawElement instance.', this.document );
 		}
 
 		// There are no attributes to break and text nodes breaking is not forced.
@@ -1769,7 +1792,8 @@ function _hasNonUiChildren( parent ) {
 }
 
 /**
- * Attribute element need to be instance of attribute element.
+ * The `attribute` passed to {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#wrap()`}
+ * must be an instance of {@link module:engine/view/attributeelement~AttributeElement `AttributeElement`}.
  *
  * @error view-writer-wrap-invalid-attribute
  */
@@ -1903,14 +1927,24 @@ function validateNodesToInsert( nodes, errorContext ) {
 	for ( const node of nodes ) {
 		if ( !validNodesToInsert.some( ( validNode => node instanceof validNode ) ) ) { // eslint-disable-line no-use-before-define
 			/**
-			 * Inserted nodes should be valid to insert. of {@link module:engine/view/attributeelement~AttributeElement AttributeElement},
-			 * {@link module:engine/view/containerelement~ContainerElement ContainerElement},
-			 * {@link module:engine/view/emptyelement~EmptyElement EmptyElement},
-			 * {@link module:engine/view/uielement~UIElement UIElement}, {@link module:engine/view/text~Text Text}.
+			 * One of the nodes to be inserted is of invalid type.
+			 *
+			 * Nodes to be inserted with {@link module:engine/view/downcastwriter~DowncastWriter#insert `DowncastWriter#insert()`} should be
+			 * of the following types:
 			 *
-			 * @error view-writer-insert-invalid-node
+			 * * {@link module:engine/view/attributeelement~AttributeElement AttributeElement},
+			 * * {@link module:engine/view/containerelement~ContainerElement ContainerElement},
+			 * * {@link module:engine/view/emptyelement~EmptyElement EmptyElement},
+			 * * {@link module:engine/view/uielement~UIElement UIElement},
+			 * * {@link module:engine/view/rawelement~RawElement RawElement},
+			 * * {@link module:engine/view/text~Text Text}.
+			 *
+			 * @error view-writer-insert-invalid-node-type
 			 */
-			throw new CKEditorError( 'view-writer-insert-invalid-node', errorContext );
+			throw new CKEditorError(
+				'view-writer-insert-invalid-node-type: One of the nodes to be inserted is of invalid type.',
+				errorContext
+			);
 		}
 
 		if ( !node.is( '$text' ) ) {
@@ -1941,14 +1975,22 @@ function validateRangeContainer( range, errorContext ) {
 
 	if ( !startContainer || !endContainer || startContainer !== endContainer ) {
 		/**
-		 * Range container is invalid. This can happen if {@link module:engine/view/range~Range#start range start} and
-		 * {@link module:engine/view/range~Range#end range end} positions are not placed inside same container or
-		 * parent container for these positions cannot be found.
+		 * The container of the given range is invalid.
+		 *
+		 * This may happen if {@link module:engine/view/range~Range#start range start} and
+		 * {@link module:engine/view/range~Range#end range end} positions are not placed inside the same container element or
+		 * a parent container for these positions cannot be found.
+		 *
+		 * Methods like {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#remove()`},
+		 * {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#clean()`},
+		 * {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#wrap()`},
+		 * {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#unwrap()`} need to be called
+		 * on a range that have its start and end positions located in the same container element. Both positions can be
+		 * nested within other elements (e.g. an attribute element) but the closest container ancestor must be the same.
 		 *
 		 * @error view-writer-invalid-range-container
 		 */
-
-		throw new CKEditorError( 'view-writer-invalid-range-container', errorContext );
+		throw new CKEditorError( 'view-writer-invalid-range-container: The container of the given range is invalid.', errorContext );
 	}
 }
 

+ 21 - 21
packages/ckeditor5-engine/src/view/rawelement.js

@@ -14,41 +14,41 @@ import Node from './node';
 /**
  * The raw element class.
  *
- * Raw elements work as data containers ("wrappers", "sandboxes") but their children are not managed or
+ * The raw elements work as data containers ("wrappers", "sandboxes") but their children are not managed or
  * even recognized by the editor. This encapsulation allows integrations to maintain custom DOM structures
  * in the editor content without, for instance, worrying about compatibility with other editor features.
- * Raw elements make a perfect tool for integration with external frameworks and data sources.
+ * Raw elements are a perfect tool for integration with external frameworks and data sources.
  *
- * Unlike {@link module:engine/view/uielement~UIElement ui elements}, raw elements act like a real editor
+ * Unlike {@link module:engine/view/uielement~UIElement UI elements}, raw elements act like real editor
  * content (similar to {@link module:engine/view/containerelement~ContainerElement} or
  * {@link module:engine/view/emptyelement~EmptyElement}), they are considered by the editor selection and
  * {@link module:widget/utils~toWidget they can work as widgets}.
  *
- * To create a new raw element use the
+ * To create a new raw element, use the
  * {@link module:engine/view/downcastwriter~DowncastWriter#createRawElement `downcastWriter#createRawElement()`} method.
  *
  * @extends module:engine/view/element~Element
  */
 export default class RawElement extends Element {
 	/**
-	 * Creates new instance of RawElement.
+	 * Creates a new instance of a raw element.
 	 *
-	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-rawelement-cannot-add` when `children` parameter
-	 * is passed, to inform that usage of `RawElement` is incorrect (adding child nodes to `RawElement` is forbidden).
+	 * Throws the `view-rawelement-cannot-add` {@link module:utils/ckeditorerror~CKEditorError CKEditorError} when the `children`
+	 * parameter is passed to inform that the usage of `RawElement` is incorrect (adding child nodes to `RawElement` is forbidden).
 	 *
 	 * @see module:engine/view/downcastwriter~DowncastWriter#createRawElement
 	 * @protected
 	 * @param {module:engine/view/document~Document} document The document instance to which this element belongs.
-	 * @param {String} name Node name.
-	 * @param {Object|Iterable} [attrs] Collection of attributes.
+	 * @param {String} name A node name.
+	 * @param {Object|Iterable} [attrs] The collection of attributes.
 	 * @param {module:engine/view/node~Node|Iterable.<module:engine/view/node~Node>} [children]
-	 * A list of nodes to be inserted into created element.
+	 * A list of nodes to be inserted into the created element.
 	 */
 	constructor( document, name, attrs, children ) {
 		super( document, name, attrs, children );
 
 		/**
-		 * Returns `null` because filler is not needed for RawElements.
+		 * Returns `null` because filler is not needed for raw elements.
 		 *
 		 * @method #getFillerOffset
 		 * @returns {null} Always returns null.
@@ -72,15 +72,15 @@ export default class RawElement extends Element {
 	 * Assuming that the object being checked is a raw element, you can also check its
 	 * {@link module:engine/view/rawelement~RawElement#name name}:
 	 *
-	 *		rawElement.is( 'img' ); // -> true if this is a img element
+	 *		rawElement.is( 'img' ); // -> true if this is an img element
 	 *		rawElement.is( 'rawElement', 'img' ); // -> same as above
 	 *		text.is( 'img' ); -> false
 	 *
 	 * {@link module:engine/view/node~Node#is Check the entire list of view objects} which implement the `is()` method.
 	 *
-	 * @param {String} type Type to check when `name` parameter is present.
+	 * @param {String} type The type to check when the `name` parameter is present.
 	 * Otherwise, it acts like the `name` parameter.
-	 * @param {String} [name] Element name.
+	 * @param {String} [name] The element name.
 	 * @returns {Boolean}
 	 */
 	is( type, name = null ) {
@@ -99,9 +99,9 @@ export default class RawElement extends Element {
 	}
 
 	/**
-	 * Overrides {@link module:engine/view/element~Element#_insertChild} method.
-	 * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-rawelement-cannot-add` to prevent
-	 * adding any child nodes to a `RawElement`.
+	 * Overrides the {@link module:engine/view/element~Element#_insertChild} method.
+	 * Throws the `view-rawelement-cannot-add` {@link module:utils/ckeditorerror~CKEditorError CKEditorError} to prevent
+	 * adding any child nodes to a raw element.
 	 *
 	 * @protected
 	 */
@@ -120,11 +120,11 @@ export default class RawElement extends Element {
 	}
 
 	/**
-	 * Allows rendering the children of a {@link module:engine/view/rawelement~RawElement} on the DOM level.
+	 * This allows rendering the children of a {@link module:engine/view/rawelement~RawElement} on the DOM level.
 	 * This method is called by the {@link module:engine/view/domconverter~DomConverter} with the raw DOM element
-	 * passed as an argument leaving the number and shape of the children up to the integrator.
+	 * passed as an argument, leaving the number and shape of the children up to the integrator.
 	 *
-	 * This method **must be defined** for the `RawElement` to work:
+	 * This method **must be defined** for the raw element to work:
 	 *
 	 *		const myRawElement = downcastWriter.createRawElement( 'div' );
 	 *
@@ -137,7 +137,7 @@ export default class RawElement extends Element {
 	 */
 }
 
-// Returns `null` because block filler is not needed for RawElements.
+// Returns `null` because block filler is not needed for raw elements.
 //
 // @returns {null}
 function getFillerOffset() {

+ 3 - 4
packages/ckeditor5-image/tests/imagetoolbar.js

@@ -83,10 +83,9 @@ describe( 'ImageToolbar', () => {
 
 			setData( model, '[<image src=""></image>]' );
 
-			sinon.assert.calledWithMatch( spy, {
-				view: toolbar,
-				balloonClassName: 'ck-toolbar-container'
-			} );
+			sinon.assert.calledWithMatch( spy, sinon.match( ( { balloonClassName, view } ) => {
+				return view === toolbar && balloonClassName === 'ck-toolbar-container';
+			} ) );
 		} );
 
 		it( 'should set aria-label attribute', () => {

+ 11 - 4
packages/ckeditor5-link/src/linkui.js

@@ -394,6 +394,10 @@ export default class LinkUI extends Plugin {
 	_showUI( forceVisible = false ) {
 		// When there's no link under the selection, go straight to the editing UI.
 		if ( !this._getSelectedLinkElement() ) {
+			// Show visual selection on a text without a link when the contextual balloon is displayed.
+			// See https://github.com/ckeditor/ckeditor5/issues/4721.
+			this._showFakeVisualSelection();
+
 			this._addActionsView();
 
 			// Be sure panel with link is visible.
@@ -402,9 +406,6 @@ export default class LinkUI extends Plugin {
 			}
 
 			this._addFormView();
-			// Show visual selection on a text without a link when the contextual balloon is displayed.
-			// See https://github.com/ckeditor/ckeditor5/issues/4721.
-			this._showFakeVisualSelection();
 		}
 		// If there's a link under the selection...
 		else {
@@ -586,14 +587,20 @@ export default class LinkUI extends Plugin {
 	 */
 	_getBalloonPositionData() {
 		const view = this.editor.editing.view;
+		const model = this.editor.model;
 		const viewDocument = view.document;
 		const targetLink = this._getSelectedLinkElement();
+		const range = model.markers.has( VISUAL_SELECTION_MARKER_NAME ) ?
+			// There are cases when we highlight selection using a marker (#7705, #4721).
+			this.editor.editing.mapper.toViewRange( model.markers.get( VISUAL_SELECTION_MARKER_NAME ).getRange() ) :
+			// If no markers are available refer to a regular selection.
+			viewDocument.selection.getFirstRange();
 
 		const target = targetLink ?
 			// When selection is inside link element, then attach panel to this element.
 			view.domConverter.mapViewToDom( targetLink ) :
 			// Otherwise attach panel to the selection.
-			view.domConverter.viewRangeToDom( viewDocument.selection.getFirstRange() );
+			view.domConverter.viewRangeToDom( range );
 
 		return { target };
 	}

+ 17 - 0
packages/ckeditor5-link/tests/linkui.js

@@ -162,6 +162,23 @@ describe( 'LinkUI', () => {
 			} );
 		} );
 
+		it( 'should pass a proper position target to the balloon toolbar', () => {
+			setModelData( editor.model, '<paragraph>f[o]o</paragraph>' );
+
+			linkUIFeature._showUI();
+
+			const markerModelRange = editor.model.markers.get( 'link-ui' ).getRange();
+			const markerViewRange = editor.editing.mapper.toViewRange( markerModelRange );
+			const domRange = editor.editing.view.domConverter.viewRangeToDom( markerViewRange );
+
+			expect( balloonAddSpy.calledWithExactly( {
+				view: formView,
+				position: {
+					target: domRange
+				}
+			} ), 'spy arguments' ).to.be.true;
+		} );
+
 		it( 'should add #actionsView to the balloon and attach the balloon to the link element when collapsed selection is inside ' +
 			'that link',
 		() => {

+ 1 - 5
packages/ckeditor5-markdown-gfm/docs/_snippets/features/markdown.js

@@ -11,11 +11,7 @@ import ArticlePluginSet from '@ckeditor/ckeditor5-core/tests/_utils/articleplugi
 import EasyImage from '@ckeditor/ckeditor5-easy-image/src/easyimage';
 import { CS_CONFIG } from '@ckeditor/ckeditor5-cloud-services/tests/_utils/cloud-services-config';
 
-import GFMDataProcessor from '@ckeditor/ckeditor5-markdown-gfm/src/gfmdataprocessor';
-
-function Markdown( editor ) {
-	editor.data.processor = new GFMDataProcessor( editor.editing.view.document );
-}
+import Markdown from '@ckeditor/ckeditor5-markdown-gfm/src/markdown';
 
 ClassicEditor
 	.create( document.querySelector( '#snippet-markdown' ), {

+ 2 - 7
packages/ckeditor5-markdown-gfm/docs/features/markdown.md

@@ -31,7 +31,7 @@ To enable this data processor in your editor install the [`@ckeditor/ckeditor5-m
 npm install --save @ckeditor/ckeditor5-markdown-gfm
 ```
 
-Then, you can enable this data processor by creating a simple plugin which will load it:
+Then, you can enable this data processor by using {@link module:markdown-gfm/markdown~Markdown} plugin which will change default {@link module:engine/dataprocessor/dataprocessor~DataProcessor data processor} with {@link module:markdown-gfm/gfmdataprocessor~GFMDataProcessor}:
 
 ```js
 import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';
@@ -41,12 +41,7 @@ import Bold from '@ckeditor/ckeditor5-basic-styles/src/bold';
 import Italic from '@ckeditor/ckeditor5-basic-styles/src/italic';
 // ...
 
-import GFMDataProcessor from '@ckeditor/ckeditor5-markdown-gfm/src/gfmdataprocessor';
-
-// Simple plugin which loads the data processor.
-function Markdown( editor ) {
-	editor.data.processor = new GFMDataProcessor( editor.editing.view.document );
-}
+import Markdown from '@ckeditor/ckeditor5-markdown-gfm/src/markdown';
 
 ClassicEditor
 	.create( document.querySelector( '#snippet-markdown' ), {

+ 10 - 1
packages/ckeditor5-markdown-gfm/package.json

@@ -10,7 +10,16 @@
     "ckeditor5-plugin"
   ],
   "dependencies": {
-    "@ckeditor/ckeditor5-engine": "^21.0.0"
+    "@ckeditor/ckeditor5-basic-styles": "^21.0.0",
+    "@ckeditor/ckeditor5-code-block": "^21.0.0",
+    "@ckeditor/ckeditor5-core": "^21.0.0",
+    "@ckeditor/ckeditor5-editor-classic": "^21.0.0",
+    "@ckeditor/ckeditor5-engine": "^21.0.0",
+    "@ckeditor/ckeditor5-list": "^21.0.0",
+    "@ckeditor/ckeditor5-table": "^21.0.0",
+    "marked": "^1.1.1",
+    "turndown": "^6.0.0",
+    "turndown-plugin-gfm": "^1.0.2"
   },
   "engines": {
     "node": ">=12.0.0",

+ 17 - 14
packages/ckeditor5-markdown-gfm/src/gfmdataprocessor.js

@@ -7,11 +7,10 @@
  * @module markdown-gfm/gfmdataprocessor
  */
 
-import marked from './lib/marked/marked';
-import toMarkdown from './lib/to-markdown/to-markdown';
 import HtmlDataProcessor from '@ckeditor/ckeditor5-engine/src/dataprocessor/htmldataprocessor';
-import GFMRenderer from './lib/marked/renderer';
-import converters from './lib/to-markdown/converters';
+
+import markdown2html from './markdown2html/markdown2html';
+import html2markdown, { turndownService } from './html2markdown/html2markdown';
 
 /**
  * This data processor implementation uses GitHub Flavored Markdown as input/output data.
@@ -36,6 +35,18 @@ export default class GFMDataProcessor {
 		this._htmlDP = new HtmlDataProcessor( document );
 	}
 
+	/**
+	 * Keeps the specified element in the output as HTML. This is useful if the editor contains
+	 * features that produce HTML that are not part of the markdon standards.
+	 *
+	 * By default, all HTML tags are removed.
+	 *
+	 * @param element {String} The element name to be kept.
+	 */
+	keepHtml( element ) {
+		turndownService.keep( [ element ] );
+	}
+
 	/**
 	 * Converts the provided Markdown string to view tree.
 	 *
@@ -43,14 +54,7 @@ export default class GFMDataProcessor {
 	 * @returns {module:engine/view/documentfragment~DocumentFragment} The converted view element.
 	 */
 	toView( data ) {
-		const html = marked.parse( data, {
-			gfm: true,
-			breaks: true,
-			tables: true,
-			xhtml: true,
-			renderer: new GFMRenderer()
-		} );
-
+		const html = markdown2html( data );
 		return this._htmlDP.toView( html );
 	}
 
@@ -63,7 +67,6 @@ export default class GFMDataProcessor {
 	 */
 	toData( viewFragment ) {
 		const html = this._htmlDP.toData( viewFragment );
-
-		return toMarkdown( html, { gfm: true, converters } );
+		return html2markdown( html );
 	}
 }

+ 93 - 0
packages/ckeditor5-markdown-gfm/src/html2markdown/html2markdown.js

@@ -0,0 +1,93 @@
+/**
+ * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/**
+ * @module markdown-gfm/html2markdown
+ */
+
+import TurndownService from 'turndown';
+import { gfm } from 'turndown-plugin-gfm';
+
+// Override the original escape method by not escaping links.
+const originalEscape = TurndownService.prototype.escape;
+
+function escape( string ) {
+	string = originalEscape( string );
+
+	// Escape "<".
+	string = string.replace( /</g, '\\<' );
+
+	return string;
+}
+
+// eslint-disable-next-line max-len
+const regex = /\b(?:https?:\/\/|www\.)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()[\]{};:'".,<>?«»“”‘’])/g;
+
+TurndownService.prototype.escape = function( string ) {
+	// Urls should not be escaped. Our strategy is using a regex to find them and escape everything
+	// which is out of the matches parts.
+
+	let escaped = '';
+	let lastLinkEnd = 0;
+
+	for ( const match of string.matchAll( regex ) ) {
+		const index = match.index;
+
+		// Append the substring between the last match and the current one (if anything).
+		if ( index > lastLinkEnd ) {
+			escaped += escape( string.substring( lastLinkEnd, index ) );
+		}
+
+		const matchedURL = match[ 0 ];
+
+		escaped += matchedURL;
+
+		lastLinkEnd = index + matchedURL.length;
+	}
+
+	// Add text after the last link or at the string start if no matches.
+	if ( lastLinkEnd < string.length ) {
+		escaped += escape( string.substring( lastLinkEnd, string.length ) );
+	}
+
+	return escaped;
+};
+
+const turndownService = new TurndownService( {
+	codeBlockStyle: 'fenced',
+	hr: '---',
+	headingStyle: 'atx'
+} );
+
+turndownService.use( [
+	gfm,
+	todoList
+] );
+
+/**
+ * Parses HTML to a markdown.
+ *
+ * @param {String} html
+ * @returns {String}
+ */
+export default function html2markdown( html ) {
+	return turndownService.turndown( html );
+}
+
+export { turndownService };
+
+// This is a copy of the original taskListItems rule from turdown-plugin-gfm, with minor changes.
+function todoList( turndownService ) {
+	turndownService.addRule( 'taskListItems', {
+		filter( node ) {
+			return node.type === 'checkbox' &&
+				// Changes here as CKEditor outputs a deeper structure.
+				( node.parentNode.nodeName === 'LI' || node.parentNode.parentNode.nodeName === 'LI' );
+		},
+		replacement( content, node ) {
+			return ( node.checked ? '[x]' : '[ ]' ) + ' ';
+		}
+	} );
+}

+ 0 - 1286
packages/ckeditor5-markdown-gfm/src/lib/marked/marked.js

@@ -1,1286 +0,0 @@
-/**
- * marked - a markdown parser
- * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
- * https://github.com/chjj/marked
- */
-
-;(function() {
-
-/**
- * Block-Level Grammar
- */
-
-var block = {
-  newline: /^\n+/,
-  code: /^( {4}[^\n]+\n*)+/,
-  fences: noop,
-  hr: /^( *[-*_]){3,} *(?:\n+|$)/,
-  heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
-  nptable: noop,
-  lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
-  blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
-  list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
-  html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
-  def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
-  table: noop,
-  paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
-  text: /^[^\n]+/
-};
-
-block.bullet = /(?:[*+-]|\d+\.)/;
-block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
-block.item = replace(block.item, 'gm')
-  (/bull/g, block.bullet)
-  ();
-
-block.list = replace(block.list)
-  (/bull/g, block.bullet)
-  ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
-  ('def', '\\n+(?=' + block.def.source + ')')
-  ();
-
-block.blockquote = replace(block.blockquote)
-  ('def', block.def)
-  ();
-
-block._tag = '(?!(?:'
-  + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
-  + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
-  + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
-
-block.html = replace(block.html)
-  ('comment', /<!--[\s\S]*?-->/)
-  ('closed', /<(tag)[\s\S]+?<\/\1>/)
-  ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
-  (/tag/g, block._tag)
-  ();
-
-block.paragraph = replace(block.paragraph)
-  ('hr', block.hr)
-  ('heading', block.heading)
-  ('lheading', block.lheading)
-  ('blockquote', block.blockquote)
-  ('tag', '<' + block._tag)
-  ('def', block.def)
-  ();
-
-/**
- * Normal Block Grammar
- */
-
-block.normal = merge({}, block);
-
-/**
- * GFM Block Grammar
- */
-
-block.gfm = merge({}, block.normal, {
-  fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
-  paragraph: /^/,
-  heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
-});
-
-block.gfm.paragraph = replace(block.paragraph)
-  ('(?!', '(?!'
-    + block.gfm.fences.source.replace('\\1', '\\2') + '|'
-    + block.list.source.replace('\\1', '\\3') + '|')
-  ();
-
-/**
- * GFM + Tables Block Grammar
- */
-
-block.tables = merge({}, block.gfm, {
-  nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
-  table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
-});
-
-/**
- * Block Lexer
- */
-
-function Lexer(options) {
-  this.tokens = [];
-  this.tokens.links = {};
-  this.options = options || marked.defaults;
-  this.rules = block.normal;
-
-  if (this.options.gfm) {
-    if (this.options.tables) {
-      this.rules = block.tables;
-    } else {
-      this.rules = block.gfm;
-    }
-  }
-}
-
-/**
- * Expose Block Rules
- */
-
-Lexer.rules = block;
-
-/**
- * Static Lex Method
- */
-
-Lexer.lex = function(src, options) {
-  var lexer = new Lexer(options);
-  return lexer.lex(src);
-};
-
-/**
- * Preprocessing
- */
-
-Lexer.prototype.lex = function(src) {
-  src = src
-    .replace(/\r\n|\r/g, '\n')
-    .replace(/\t/g, '    ')
-    .replace(/\u00a0/g, ' ')
-    .replace(/\u2424/g, '\n');
-
-  return this.token(src, true);
-};
-
-/**
- * Lexing
- */
-
-Lexer.prototype.token = function(src, top, bq) {
-  var src = src.replace(/^ +$/gm, '')
-    , next
-    , loose
-    , cap
-    , bull
-    , b
-    , item
-    , space
-    , i
-    , l;
-
-  while (src) {
-    // newline
-    if (cap = this.rules.newline.exec(src)) {
-      src = src.substring(cap[0].length);
-      if (cap[0].length > 1) {
-        this.tokens.push({
-          type: 'space'
-        });
-      }
-    }
-
-    // code
-    if (cap = this.rules.code.exec(src)) {
-      src = src.substring(cap[0].length);
-      cap = cap[0].replace(/^ {4}/gm, '');
-      this.tokens.push({
-        type: 'code',
-        text: !this.options.pedantic
-          ? cap.replace(/\n+$/, '')
-          : cap
-      });
-      continue;
-    }
-
-    // fences (gfm)
-    if (cap = this.rules.fences.exec(src)) {
-      src = src.substring(cap[0].length);
-      this.tokens.push({
-        type: 'code',
-        lang: cap[2],
-        text: cap[3] || ''
-      });
-      continue;
-    }
-
-    // heading
-    if (cap = this.rules.heading.exec(src)) {
-      src = src.substring(cap[0].length);
-      this.tokens.push({
-        type: 'heading',
-        depth: cap[1].length,
-        text: cap[2]
-      });
-      continue;
-    }
-
-    // table no leading pipe (gfm)
-    if (top && (cap = this.rules.nptable.exec(src))) {
-      src = src.substring(cap[0].length);
-
-      item = {
-        type: 'table',
-        header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
-        align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
-        cells: cap[3].replace(/\n$/, '').split('\n')
-      };
-
-      for (i = 0; i < item.align.length; i++) {
-        if (/^ *-+: *$/.test(item.align[i])) {
-          item.align[i] = 'right';
-        } else if (/^ *:-+: *$/.test(item.align[i])) {
-          item.align[i] = 'center';
-        } else if (/^ *:-+ *$/.test(item.align[i])) {
-          item.align[i] = 'left';
-        } else {
-          item.align[i] = null;
-        }
-      }
-
-      for (i = 0; i < item.cells.length; i++) {
-        item.cells[i] = item.cells[i].split(/ *\| */);
-      }
-
-      this.tokens.push(item);
-
-      continue;
-    }
-
-    // lheading
-    if (cap = this.rules.lheading.exec(src)) {
-      src = src.substring(cap[0].length);
-      this.tokens.push({
-        type: 'heading',
-        depth: cap[2] === '=' ? 1 : 2,
-        text: cap[1]
-      });
-      continue;
-    }
-
-    // hr
-    if (cap = this.rules.hr.exec(src)) {
-      src = src.substring(cap[0].length);
-      this.tokens.push({
-        type: 'hr'
-      });
-      continue;
-    }
-
-    // blockquote
-    if (cap = this.rules.blockquote.exec(src)) {
-      src = src.substring(cap[0].length);
-
-      this.tokens.push({
-        type: 'blockquote_start'
-      });
-
-      cap = cap[0].replace(/^ *> ?/gm, '');
-
-      // Pass `top` to keep the current
-      // "toplevel" state. This is exactly
-      // how markdown.pl works.
-      this.token(cap, top, true);
-
-      this.tokens.push({
-        type: 'blockquote_end'
-      });
-
-      continue;
-    }
-
-    // list
-    if (cap = this.rules.list.exec(src)) {
-      src = src.substring(cap[0].length);
-      bull = cap[2];
-
-      this.tokens.push({
-        type: 'list_start',
-        ordered: bull.length > 1
-      });
-
-      // Get each top-level item.
-      cap = cap[0].match(this.rules.item);
-
-      next = false;
-      l = cap.length;
-      i = 0;
-
-      for (; i < l; i++) {
-        item = cap[i];
-
-        // Remove the list item's bullet
-        // so it is seen as the next token.
-        space = item.length;
-        item = item.replace(/^ *([*+-]|\d+\.) +/, '');
-
-        // Outdent whatever the
-        // list item contains. Hacky.
-        if (~item.indexOf('\n ')) {
-          space -= item.length;
-          item = !this.options.pedantic
-            ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
-            : item.replace(/^ {1,4}/gm, '');
-        }
-
-        // Determine whether the next list item belongs here.
-        // Backpedal if it does not belong in this list.
-        if (this.options.smartLists && i !== l - 1) {
-          b = block.bullet.exec(cap[i + 1])[0];
-          if (bull !== b && !(bull.length > 1 && b.length > 1)) {
-            src = cap.slice(i + 1).join('\n') + src;
-            i = l - 1;
-          }
-        }
-
-        // Determine whether item is loose or not.
-        // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
-        // for discount behavior.
-        loose = next || /\n\n(?!\s*$)/.test(item);
-        if (i !== l - 1) {
-          next = item.charAt(item.length - 1) === '\n';
-          if (!loose) loose = next;
-        }
-
-        this.tokens.push({
-          type: loose
-            ? 'loose_item_start'
-            : 'list_item_start'
-        });
-
-        // Recurse.
-        this.token(item, false, bq);
-
-        this.tokens.push({
-          type: 'list_item_end'
-        });
-      }
-
-      this.tokens.push({
-        type: 'list_end'
-      });
-
-      continue;
-    }
-
-    // html
-    if (cap = this.rules.html.exec(src)) {
-      src = src.substring(cap[0].length);
-      this.tokens.push({
-        type: this.options.sanitize
-          ? 'paragraph'
-          : 'html',
-        pre: !this.options.sanitizer
-          && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
-        text: cap[0]
-      });
-      continue;
-    }
-
-    // def
-    if ((!bq && top) && (cap = this.rules.def.exec(src))) {
-      src = src.substring(cap[0].length);
-      this.tokens.links[cap[1].toLowerCase()] = {
-        href: cap[2],
-        title: cap[3]
-      };
-      continue;
-    }
-
-    // table (gfm)
-    if (top && (cap = this.rules.table.exec(src))) {
-      src = src.substring(cap[0].length);
-
-      item = {
-        type: 'table',
-        header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
-        align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
-        cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
-      };
-
-      for (i = 0; i < item.align.length; i++) {
-        if (/^ *-+: *$/.test(item.align[i])) {
-          item.align[i] = 'right';
-        } else if (/^ *:-+: *$/.test(item.align[i])) {
-          item.align[i] = 'center';
-        } else if (/^ *:-+ *$/.test(item.align[i])) {
-          item.align[i] = 'left';
-        } else {
-          item.align[i] = null;
-        }
-      }
-
-      for (i = 0; i < item.cells.length; i++) {
-        item.cells[i] = item.cells[i]
-          .replace(/^ *\| *| *\| *$/g, '')
-          .split(/ *\| */);
-      }
-
-      this.tokens.push(item);
-
-      continue;
-    }
-
-    // top-level paragraph
-    if (top && (cap = this.rules.paragraph.exec(src))) {
-      src = src.substring(cap[0].length);
-      this.tokens.push({
-        type: 'paragraph',
-        text: cap[1].charAt(cap[1].length - 1) === '\n'
-          ? cap[1].slice(0, -1)
-          : cap[1]
-      });
-      continue;
-    }
-
-    // text
-    if (cap = this.rules.text.exec(src)) {
-      // Top-level should never reach here.
-      src = src.substring(cap[0].length);
-      this.tokens.push({
-        type: 'text',
-        text: cap[0]
-      });
-      continue;
-    }
-
-    if (src) {
-      throw new
-        Error('Infinite loop on byte: ' + src.charCodeAt(0));
-    }
-  }
-
-  return this.tokens;
-};
-
-/**
- * Inline-Level Grammar
- */
-
-var inline = {
-  escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
-  autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
-  url: noop,
-  tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
-  link: /^!?\[(inside)\]\(href\)/,
-  reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
-  nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
-  strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
-  em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
-  code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
-  br: /^ {2,}\n(?!\s*$)/,
-  del: noop,
-  text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
-};
-
-inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
-inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
-
-inline.link = replace(inline.link)
-  ('inside', inline._inside)
-  ('href', inline._href)
-  ();
-
-inline.reflink = replace(inline.reflink)
-  ('inside', inline._inside)
-  ();
-
-/**
- * Normal Inline Grammar
- */
-
-inline.normal = merge({}, inline);
-
-/**
- * Pedantic Inline Grammar
- */
-
-inline.pedantic = merge({}, inline.normal, {
-  strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
-  em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
-});
-
-/**
- * GFM Inline Grammar
- */
-
-inline.gfm = merge({}, inline.normal, {
-  escape: replace(inline.escape)('])', '~|])')(),
-  url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
-  del: /^~~(?=\S)([\s\S]*?\S)~~/,
-  text: replace(inline.text)
-    (']|', '~]|')
-    ('|', '|https?://|')
-    ()
-});
-
-/**
- * GFM + Line Breaks Inline Grammar
- */
-
-inline.breaks = merge({}, inline.gfm, {
-  br: replace(inline.br)('{2,}', '*')(),
-  text: replace(inline.gfm.text)('{2,}', '*')()
-});
-
-/**
- * Inline Lexer & Compiler
- */
-
-function InlineLexer(links, options) {
-  this.options = options || marked.defaults;
-  this.links = links;
-  this.rules = inline.normal;
-  this.renderer = this.options.renderer || new Renderer;
-  this.renderer.options = this.options;
-
-  if (!this.links) {
-    throw new
-      Error('Tokens array requires a `links` property.');
-  }
-
-  if (this.options.gfm) {
-    if (this.options.breaks) {
-      this.rules = inline.breaks;
-    } else {
-      this.rules = inline.gfm;
-    }
-  } else if (this.options.pedantic) {
-    this.rules = inline.pedantic;
-  }
-}
-
-/**
- * Expose Inline Rules
- */
-
-InlineLexer.rules = inline;
-
-/**
- * Static Lexing/Compiling Method
- */
-
-InlineLexer.output = function(src, links, options) {
-  var inline = new InlineLexer(links, options);
-  return inline.output(src);
-};
-
-/**
- * Lexing/Compiling
- */
-
-InlineLexer.prototype.output = function(src) {
-  var out = ''
-    , link
-    , text
-    , href
-    , cap;
-
-  while (src) {
-    // escape
-    if (cap = this.rules.escape.exec(src)) {
-      src = src.substring(cap[0].length);
-      out += cap[1];
-      continue;
-    }
-
-    // autolink
-    if (cap = this.rules.autolink.exec(src)) {
-      src = src.substring(cap[0].length);
-      if (cap[2] === '@') {
-        text = cap[1].charAt(6) === ':'
-          ? this.mangle(cap[1].substring(7))
-          : this.mangle(cap[1]);
-        href = this.mangle('mailto:') + text;
-      } else {
-        text = escape(cap[1]);
-        href = text;
-      }
-      out += this.renderer.link(href, null, text);
-      continue;
-    }
-
-    // url (gfm)
-    if (!this.inLink && (cap = this.rules.url.exec(src))) {
-      src = src.substring(cap[0].length);
-      text = escape(cap[1]);
-      href = text;
-      out += this.renderer.link(href, null, text);
-      continue;
-    }
-
-    // tag
-    if (cap = this.rules.tag.exec(src)) {
-      if (!this.inLink && /^<a /i.test(cap[0])) {
-        this.inLink = true;
-      } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
-        this.inLink = false;
-      }
-      src = src.substring(cap[0].length);
-      out += this.options.sanitize
-        ? this.options.sanitizer
-          ? this.options.sanitizer(cap[0])
-          : escape(cap[0])
-        : cap[0]
-      continue;
-    }
-
-    // link
-    if (cap = this.rules.link.exec(src)) {
-      src = src.substring(cap[0].length);
-      this.inLink = true;
-      out += this.outputLink(cap, {
-        href: cap[2],
-        title: cap[3]
-      });
-      this.inLink = false;
-      continue;
-    }
-
-    // reflink, nolink
-    if ((cap = this.rules.reflink.exec(src))
-        || (cap = this.rules.nolink.exec(src))) {
-      src = src.substring(cap[0].length);
-      link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
-      link = this.links[link.toLowerCase()];
-      if (!link || !link.href) {
-        out += cap[0].charAt(0);
-        src = cap[0].substring(1) + src;
-        continue;
-      }
-      this.inLink = true;
-      out += this.outputLink(cap, link);
-      this.inLink = false;
-      continue;
-    }
-
-    // strong
-    if (cap = this.rules.strong.exec(src)) {
-      src = src.substring(cap[0].length);
-      out += this.renderer.strong(this.output(cap[2] || cap[1]));
-      continue;
-    }
-
-    // em
-    if (cap = this.rules.em.exec(src)) {
-      src = src.substring(cap[0].length);
-      out += this.renderer.em(this.output(cap[2] || cap[1]));
-      continue;
-    }
-
-    // code
-    if (cap = this.rules.code.exec(src)) {
-      src = src.substring(cap[0].length);
-      out += this.renderer.codespan(escape(cap[2], true));
-      continue;
-    }
-
-    // br
-    if (cap = this.rules.br.exec(src)) {
-      src = src.substring(cap[0].length);
-      out += this.renderer.br();
-      continue;
-    }
-
-    // del (gfm)
-    if (cap = this.rules.del.exec(src)) {
-      src = src.substring(cap[0].length);
-      out += this.renderer.del(this.output(cap[1]));
-      continue;
-    }
-
-    // text
-    if (cap = this.rules.text.exec(src)) {
-      src = src.substring(cap[0].length);
-      out += this.renderer.text(escape(this.smartypants(cap[0])));
-      continue;
-    }
-
-    if (src) {
-      throw new
-        Error('Infinite loop on byte: ' + src.charCodeAt(0));
-    }
-  }
-
-  return out;
-};
-
-/**
- * Compile Link
- */
-
-InlineLexer.prototype.outputLink = function(cap, link) {
-  var href = escape(link.href)
-    , title = link.title ? escape(link.title) : null;
-
-  return cap[0].charAt(0) !== '!'
-    ? this.renderer.link(href, title, this.output(cap[1]))
-    : this.renderer.image(href, title, escape(cap[1]));
-};
-
-/**
- * Smartypants Transformations
- */
-
-InlineLexer.prototype.smartypants = function(text) {
-  if (!this.options.smartypants) return text;
-  return text
-    // em-dashes
-    .replace(/---/g, '\u2014')
-    // en-dashes
-    .replace(/--/g, '\u2013')
-    // opening singles
-    .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
-    // closing singles & apostrophes
-    .replace(/'/g, '\u2019')
-    // opening doubles
-    .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
-    // closing doubles
-    .replace(/"/g, '\u201d')
-    // ellipses
-    .replace(/\.{3}/g, '\u2026');
-};
-
-/**
- * Mangle Links
- */
-
-InlineLexer.prototype.mangle = function(text) {
-  if (!this.options.mangle) return text;
-  var out = ''
-    , l = text.length
-    , i = 0
-    , ch;
-
-  for (; i < l; i++) {
-    ch = text.charCodeAt(i);
-    if (Math.random() > 0.5) {
-      ch = 'x' + ch.toString(16);
-    }
-    out += '&#' + ch + ';';
-  }
-
-  return out;
-};
-
-/**
- * Renderer
- */
-
-function Renderer(options) {
-  this.options = options || { };
-}
-
-Renderer.prototype.code = function(code, lang, escaped) {
-  if (this.options.highlight) {
-    var out = this.options.highlight(code, lang);
-    if (out != null && out !== code) {
-      escaped = true;
-      code = out;
-    }
-  }
-
-  if (!lang) {
-    return '<pre><code>'
-      + (escaped ? code : escape(code, true))
-      + '\n</code></pre>';
-  }
-
-  return '<pre><code class="'
-    + this.options.langPrefix
-    + escape(lang, true)
-    + '">'
-    + (escaped ? code : escape(code, true))
-    + '\n</code></pre>\n';
-};
-
-Renderer.prototype.blockquote = function(quote) {
-  return '<blockquote>\n' + quote + '</blockquote>\n';
-};
-
-Renderer.prototype.html = function(html) {
-  return html;
-};
-
-Renderer.prototype.heading = function(text, level, raw) {
-  return '<h'
-    + level
-    + ' id="'
-    + this.options.headerPrefix
-    + raw.toLowerCase().replace(/[^\w]+/g, '-')
-    + '">'
-    + text
-    + '</h'
-    + level
-    + '>\n';
-};
-
-Renderer.prototype.hr = function() {
-  return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
-};
-
-Renderer.prototype.list = function(body, ordered) {
-  var type = ordered ? 'ol' : 'ul';
-  return '<' + type + '>\n' + body + '</' + type + '>\n';
-};
-
-Renderer.prototype.listitem = function(text) {
-  return '<li>' + text + '</li>\n';
-};
-
-Renderer.prototype.paragraph = function(text) {
-  return '<p>' + text + '</p>\n';
-};
-
-Renderer.prototype.table = function(header, body) {
-  return '<table>\n'
-    + '<thead>\n'
-    + header
-    + '</thead>\n'
-    + '<tbody>\n'
-    + body
-    + '</tbody>\n'
-    + '</table>\n';
-};
-
-Renderer.prototype.tablerow = function(content) {
-  return '<tr>\n' + content + '</tr>\n';
-};
-
-Renderer.prototype.tablecell = function(content, flags) {
-  var type = flags.header ? 'th' : 'td';
-  var tag = flags.align
-    ? '<' + type + ' style="text-align:' + flags.align + '">'
-    : '<' + type + '>';
-  return tag + content + '</' + type + '>\n';
-};
-
-// span level renderer
-Renderer.prototype.strong = function(text) {
-  return '<strong>' + text + '</strong>';
-};
-
-Renderer.prototype.em = function(text) {
-  return '<em>' + text + '</em>';
-};
-
-Renderer.prototype.codespan = function(text) {
-  return '<code>' + text + '</code>';
-};
-
-Renderer.prototype.br = function() {
-  return this.options.xhtml ? '<br/>' : '<br>';
-};
-
-Renderer.prototype.del = function(text) {
-  return '<del>' + text + '</del>';
-};
-
-Renderer.prototype.link = function(href, title, text) {
-  if (this.options.sanitize) {
-    try {
-      var prot = decodeURIComponent(unescape(href))
-        .replace(/[^\w:]/g, '')
-        .toLowerCase();
-    } catch (e) {
-      return '';
-    }
-    if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
-      return '';
-    }
-  }
-  var out = '<a href="' + href + '"';
-  if (title) {
-    out += ' title="' + title + '"';
-  }
-  out += '>' + text + '</a>';
-  return out;
-};
-
-Renderer.prototype.image = function(href, title, text) {
-  var out = '<img src="' + href + '" alt="' + text + '"';
-  if (title) {
-    out += ' title="' + title + '"';
-  }
-  out += this.options.xhtml ? '/>' : '>';
-  return out;
-};
-
-Renderer.prototype.text = function(text) {
-  return text;
-};
-
-/**
- * Parsing & Compiling
- */
-
-function Parser(options) {
-  this.tokens = [];
-  this.token = null;
-  this.options = options || marked.defaults;
-  this.options.renderer = this.options.renderer || new Renderer;
-  this.renderer = this.options.renderer;
-  this.renderer.options = this.options;
-}
-
-/**
- * Static Parse Method
- */
-
-Parser.parse = function(src, options, renderer) {
-  var parser = new Parser(options, renderer);
-  return parser.parse(src);
-};
-
-/**
- * Parse Loop
- */
-
-Parser.prototype.parse = function(src) {
-  this.inline = new InlineLexer(src.links, this.options, this.renderer);
-  this.tokens = src.reverse();
-
-  var out = '';
-  while (this.next()) {
-    out += this.tok();
-  }
-
-  return out;
-};
-
-/**
- * Next Token
- */
-
-Parser.prototype.next = function() {
-  return this.token = this.tokens.pop();
-};
-
-/**
- * Preview Next Token
- */
-
-Parser.prototype.peek = function() {
-  return this.tokens[this.tokens.length - 1] || 0;
-};
-
-/**
- * Parse Text Tokens
- */
-
-Parser.prototype.parseText = function() {
-  var body = this.token.text;
-
-  while (this.peek().type === 'text') {
-    body += '\n' + this.next().text;
-  }
-
-  return this.inline.output(body);
-};
-
-/**
- * Parse Current Token
- */
-
-Parser.prototype.tok = function() {
-  switch (this.token.type) {
-    case 'space': {
-      return '';
-    }
-    case 'hr': {
-      return this.renderer.hr();
-    }
-    case 'heading': {
-      return this.renderer.heading(
-        this.inline.output(this.token.text),
-        this.token.depth,
-        this.token.text);
-    }
-    case 'code': {
-      return this.renderer.code(this.token.text,
-        this.token.lang,
-        this.token.escaped);
-    }
-    case 'table': {
-      var header = ''
-        , body = ''
-        , i
-        , row
-        , cell
-        , flags
-        , j;
-
-      // header
-      cell = '';
-      for (i = 0; i < this.token.header.length; i++) {
-        flags = { header: true, align: this.token.align[i] };
-        cell += this.renderer.tablecell(
-          this.inline.output(this.token.header[i]),
-          { header: true, align: this.token.align[i] }
-        );
-      }
-      header += this.renderer.tablerow(cell);
-
-      for (i = 0; i < this.token.cells.length; i++) {
-        row = this.token.cells[i];
-
-        cell = '';
-        for (j = 0; j < row.length; j++) {
-          cell += this.renderer.tablecell(
-            this.inline.output(row[j]),
-            { header: false, align: this.token.align[j] }
-          );
-        }
-
-        body += this.renderer.tablerow(cell);
-      }
-      return this.renderer.table(header, body);
-    }
-    case 'blockquote_start': {
-      var body = '';
-
-      while (this.next().type !== 'blockquote_end') {
-        body += this.tok();
-      }
-
-      return this.renderer.blockquote(body);
-    }
-    case 'list_start': {
-      var body = ''
-        , ordered = this.token.ordered;
-
-      while (this.next().type !== 'list_end') {
-        body += this.tok();
-      }
-
-      return this.renderer.list(body, ordered);
-    }
-    case 'list_item_start': {
-      var body = '';
-
-      while (this.next().type !== 'list_item_end') {
-        body += this.token.type === 'text'
-          ? this.parseText()
-          : this.tok();
-      }
-
-      return this.renderer.listitem(body);
-    }
-    case 'loose_item_start': {
-      var body = '';
-
-      while (this.next().type !== 'list_item_end') {
-        body += this.tok();
-      }
-
-      return this.renderer.listitem(body);
-    }
-    case 'html': {
-      var html = !this.token.pre && !this.options.pedantic
-        ? this.inline.output(this.token.text)
-        : this.token.text;
-      return this.renderer.html(html);
-    }
-    case 'paragraph': {
-      return this.renderer.paragraph(this.inline.output(this.token.text));
-    }
-    case 'text': {
-      return this.renderer.paragraph(this.parseText());
-    }
-  }
-};
-
-/**
- * Helpers
- */
-
-function escape(html, encode) {
-  return html
-    .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
-    .replace(/</g, '&lt;')
-    .replace(/>/g, '&gt;')
-    .replace(/"/g, '&quot;')
-    .replace(/'/g, '&#39;');
-}
-
-function unescape(html) {
-	// explicitly match decimal, hex, and named HTML entities
-  return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
-    n = n.toLowerCase();
-    if (n === 'colon') return ':';
-    if (n.charAt(0) === '#') {
-      return n.charAt(1) === 'x'
-        ? String.fromCharCode(parseInt(n.substring(2), 16))
-        : String.fromCharCode(+n.substring(1));
-    }
-    return '';
-  });
-}
-
-function replace(regex, opt) {
-  regex = regex.source;
-  opt = opt || '';
-  return function self(name, val) {
-    if (!name) return new RegExp(regex, opt);
-    val = val.source || val;
-    val = val.replace(/(^|[^\[])\^/g, '$1');
-    regex = regex.replace(name, val);
-    return self;
-  };
-}
-
-function noop() {}
-noop.exec = noop;
-
-function merge(obj) {
-  var i = 1
-    , target
-    , key;
-
-  for (; i < arguments.length; i++) {
-    target = arguments[i];
-    for (key in target) {
-      if (Object.prototype.hasOwnProperty.call(target, key)) {
-        obj[key] = target[key];
-      }
-    }
-  }
-
-  return obj;
-}
-
-
-/**
- * Marked
- */
-
-function marked(src, opt, callback) {
-  if (callback || typeof opt === 'function') {
-    if (!callback) {
-      callback = opt;
-      opt = null;
-    }
-
-    opt = merge({}, marked.defaults, opt || {});
-
-    var highlight = opt.highlight
-      , tokens
-      , pending
-      , i = 0;
-
-    try {
-      tokens = Lexer.lex(src, opt)
-    } catch (e) {
-      return callback(e);
-    }
-
-    pending = tokens.length;
-
-    var done = function(err) {
-      if (err) {
-        opt.highlight = highlight;
-        return callback(err);
-      }
-
-      var out;
-
-      try {
-        out = Parser.parse(tokens, opt);
-      } catch (e) {
-        err = e;
-      }
-
-      opt.highlight = highlight;
-
-      return err
-        ? callback(err)
-        : callback(null, out);
-    };
-
-    if (!highlight || highlight.length < 3) {
-      return done();
-    }
-
-    delete opt.highlight;
-
-    if (!pending) return done();
-
-    for (; i < tokens.length; i++) {
-      (function(token) {
-        if (token.type !== 'code') {
-          return --pending || done();
-        }
-        return highlight(token.text, token.lang, function(err, code) {
-          if (err) return done(err);
-          if (code == null || code === token.text) {
-            return --pending || done();
-          }
-          token.text = code;
-          token.escaped = true;
-          --pending || done();
-        });
-      })(tokens[i]);
-    }
-
-    return;
-  }
-  try {
-    if (opt) opt = merge({}, marked.defaults, opt);
-    return Parser.parse(Lexer.lex(src, opt), opt);
-  } catch (e) {
-    e.message += '\nPlease report this to https://github.com/chjj/marked.';
-    if ((opt || marked.defaults).silent) {
-      return '<p>An error occured:</p><pre>'
-        + escape(e.message + '', true)
-        + '</pre>';
-    }
-    throw e;
-  }
-}
-
-/**
- * Options
- */
-
-marked.options =
-marked.setOptions = function(opt) {
-  merge(marked.defaults, opt);
-  return marked;
-};
-
-marked.defaults = {
-  gfm: true,
-  tables: true,
-  breaks: false,
-  pedantic: false,
-  sanitize: false,
-  sanitizer: null,
-  mangle: true,
-  smartLists: false,
-  silent: false,
-  highlight: null,
-  langPrefix: 'lang-',
-  smartypants: false,
-  headerPrefix: '',
-  renderer: new Renderer,
-  xhtml: false
-};
-
-/**
- * Expose
- */
-
-marked.Parser = Parser;
-marked.parser = Parser.parse;
-
-marked.Renderer = Renderer;
-
-marked.Lexer = Lexer;
-marked.lexer = Lexer.lex;
-
-marked.InlineLexer = InlineLexer;
-marked.inlineLexer = InlineLexer.output;
-
-marked.parse = marked;
-
-if (typeof module !== 'undefined' && typeof exports === 'object') {
-  module.exports = marked;
-} else if (typeof define === 'function' && define.amd) {
-  define(function() { return marked; });
-} else {
-  this.marked = marked;
-}
-
-}).call(function() {
-  return this || (typeof window !== 'undefined' ? window : global);
-}());

+ 0 - 175
packages/ckeditor5-markdown-gfm/src/lib/marked/renderer.js

@@ -1,175 +0,0 @@
-/**
- * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
- */
-
-/**
- * Original marked.js library renderer with fixes:
- * - No formatting for output HTML string &mdash; all newlines between tags are removed to create clean output.
- * - Changed long string concatenations to ES5 template strings.
- * - Changed code style.
- *
- * @see {@link https://github.com/chjj/marked#renderer} Methods description.
- * @param options
- * @constructor
- */
-function Renderer( options ) {
-	this.options = options || {};
-}
-
-Renderer.prototype.code = function( code, lang, escaped ) {
-	if ( this.options.highlight ) {
-		const out = this.options.highlight( code, lang );
-
-		if ( out !== null && out !== code ) {
-			escaped = true;
-			code = out;
-		}
-	}
-
-	if ( !lang ) {
-		return `<pre><code>${ escaped ? code : escape( code, true ) }</code></pre>`;
-	}
-
-	const cssClass = this.options.langPrefix + escape( lang, true );
-
-	return `<pre><code class="${ cssClass }">${ escaped ? code : escape( code, true ) }</code></pre>`;
-};
-
-Renderer.prototype.blockquote = function( quote ) {
-	return `<blockquote>${ quote }</blockquote>`;
-};
-
-Renderer.prototype.html = function( html ) {
-	return html;
-};
-
-Renderer.prototype.heading = function( text, level, raw ) {
-	return `<h${ level }>${ text }</h${ level }>`;
-};
-
-Renderer.prototype.hr = function() {
-	return this.options.xhtml ? '<hr/>' : '<hr>';
-};
-
-Renderer.prototype.list = function( body, ordered ) {
-	const type = ordered ? 'ol' : 'ul';
-
-	return `<${ type }>${ body }</${ type }>`;
-};
-
-Renderer.prototype.listitem = function( text ) {
-	return `<li>${ text }</li>`;
-};
-
-Renderer.prototype.paragraph = function( text ) {
-	return `<p>${ text }</p>`;
-};
-
-Renderer.prototype.table = function( header, body ) {
-	return `<table><thead>${ header }</thead><tbody>${ body }</tbody></table>`;
-};
-
-Renderer.prototype.tablerow = function( content ) {
-	return '<tr>' + content + '</tr>';
-};
-
-Renderer.prototype.tablecell = function( content, flags ) {
-	const type = flags.header ? 'th' : 'td';
-	const tag = flags.align ? `<${ type } align="${ flags.align }">` : `<${ type }>`;
-
-	return tag + content + `</${ type }>`;
-};
-
-// span level renderer
-Renderer.prototype.strong = function( text ) {
-	return `<strong>${ text }</strong>`;
-};
-
-Renderer.prototype.em = function( text ) {
-	return `<em>${ text }</em>`;
-};
-
-Renderer.prototype.codespan = function( text ) {
-	return `<code>${ text.trim() }</code>`;
-};
-
-Renderer.prototype.br = function() {
-	return this.options.xhtml ? '<br/>' : '<br>';
-};
-
-Renderer.prototype.del = function( text ) {
-	return `<del>${ text }</del>`;
-};
-
-Renderer.prototype.link = function( href, title, text ) {
-	if ( this.options.sanitize ) {
-		let prot;
-
-		try {
-			prot = decodeURIComponent( unescape( href ) )
-				.replace( /[^\w:]/g, '' )
-				.toLowerCase();
-		} catch ( e ) {
-			return '';
-		}
-
-		if ( prot.indexOf( 'javascript:' ) === 0 || prot.indexOf( 'vbscript:' ) === 0 ) { // jshint ignore:line
-			return '';
-		}
-	}
-
-	let out = '<a href="' + href + '"';
-
-	if ( title ) {
-		out += ' title="' + title + '"';
-	}
-	out += '>' + text + '</a>';
-
-	return out;
-};
-
-Renderer.prototype.image = function( href, title, text ) {
-	let out = '<img src="' + href + '" alt="' + text + '"';
-
-	if ( title ) {
-		out += ' title="' + title + '"';
-	}
-	out += this.options.xhtml ? '/>' : '>';
-
-	return out;
-};
-
-Renderer.prototype.text = function( text ) {
-	return text;
-};
-
-export default Renderer;
-
-function escape( html, encode ) {
-	return html
-		.replace( !encode ? /&(?!#?\w+;)/g : /&/g, '&amp;' )
-		.replace( /</g, '&lt;' )
-		.replace( />/g, '&gt;' )
-		.replace( /"/g, '&quot;' )
-		.replace( /'/g, '&#39;' );
-}
-
-function unescape( html ) {
-	// explicitly match decimal, hex, and named HTML entities
-	return html.replace( /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function( _, n ) {
-		n = n.toLowerCase();
-
-		if ( n === 'colon' ) {
-			return ':';
-		}
-
-		if ( n.charAt( 0 ) === '#' ) {
-			return n.charAt( 1 ) === 'x' ?
-				String.fromCharCode( parseInt( n.substring( 2 ), 16 ) ) :
-				String.fromCharCode( +n.substring( 1 ) ); // jscs:ignore
-		}
-
-		return '';
-	} );
-}

+ 0 - 68
packages/ckeditor5-markdown-gfm/src/lib/to-markdown/converters.js

@@ -1,68 +0,0 @@
-/**
- * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
- */
-
-// Exports an array with custom converters used by to-markdown library.
-export default [
-	// Converting code blocks with class name matching output from marked library.
-	{
-		filter: ( node ) =>  {
-			const regexp = /lang-(.+)/;
-
-			return node.nodeName === 'PRE' &&
-				node.firstChild &&
-				node.firstChild.nodeName === 'CODE' &&
-				regexp.test( node.firstChild.className );
-		},
-		replacement: ( content, node ) => {
-			const regexp = /lang-(.+)/;
-			const lang = regexp.exec( node.firstChild.className )[ 1 ];
-
-			return '\n\n``` ' + lang + '\n' + node.firstChild.textContent + '\n```\n\n';
-		}
-	},
-	// Converting empty links.
-	{
-		filter: ( node ) => {
-			return node.nodeName === 'A' && !node.getAttribute( 'href' );
-		},
-
-		replacement: ( content, node ) => {
-			const title = node.title ? `"${node.title}"` : '';
-
-			return `[${ content }](${ title })`;
-		}
-	},
-	// Headers - fixing newline at the beginning.
-	{
-		filter: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ],
-		replacement: ( content, node ) => {
-			const hLevel = node.nodeName.charAt( 1 );
-			let hPrefix = '';
-
-			for ( let i = 0; i < hLevel; i++ ) {
-				hPrefix += '#';
-			}
-
-			return hPrefix + ' ' + content + '\n';
-		}
-	},
-	// Inline code - fixing backticks inside code blocks.
-	{
-		filter: ( node ) => {
-			const hasSiblings = node.previousSibling || node.nextSibling;
-			const isCodeBlock = node.parentNode.nodeName === 'PRE' && !hasSiblings;
-
-			return node.nodeName === 'CODE' && !isCodeBlock;
-		},
-		replacement: ( content ) => {
-			// If content starts or ends with backtick - use double backtick.
-			if ( content.indexOf( '`' ) > -1 ) {
-				return '`` ' + content + ' ``';
-			}
-
-			return '`' + content + '`';
-		}
-	}
-];

+ 0 - 785
packages/ckeditor5-markdown-gfm/src/lib/to-markdown/to-markdown.js

@@ -1,785 +0,0 @@
-(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.toMarkdown = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
-	/*
-	 * to-markdown - an HTML to Markdown converter
-	 *
-	 * Copyright 2011+, Dom Christie
-	 * Licenced under the MIT licence
-	 *
-	 */
-
-	'use strict'
-
-	var toMarkdown
-	var converters
-	var mdConverters = require('./lib/md-converters')
-	var gfmConverters = require('./lib/gfm-converters')
-	var HtmlParser = require('./lib/html-parser')
-	var collapse = require('collapse-whitespace')
-
-	/*
-	 * Utilities
-	 */
-
-	var blocks = ['address', 'article', 'aside', 'audio', 'blockquote', 'body',
-		'canvas', 'center', 'dd', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption',
-		'figure', 'footer', 'form', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
-		'header', 'hgroup', 'hr', 'html', 'isindex', 'li', 'main', 'menu', 'nav',
-		'noframes', 'noscript', 'ol', 'output', 'p', 'pre', 'section', 'table',
-		'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'ul'
-	]
-
-	function isBlock (node) {
-		return blocks.indexOf(node.nodeName.toLowerCase()) !== -1
-	}
-
-	var voids = [
-		'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input',
-		'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'
-	]
-
-	function isVoid (node) {
-		return voids.indexOf(node.nodeName.toLowerCase()) !== -1
-	}
-
-	function htmlToDom (string) {
-		var tree = new HtmlParser().parseFromString(string, 'text/html')
-		collapse(tree.documentElement, isBlock)
-		return tree
-	}
-
-	/*
-	 * Flattens DOM tree into single array
-	 */
-
-	function bfsOrder (node) {
-		var inqueue = [node]
-		var outqueue = []
-		var elem
-		var children
-		var i
-
-		while (inqueue.length > 0) {
-			elem = inqueue.shift()
-			outqueue.push(elem)
-			children = elem.childNodes
-			for (i = 0; i < children.length; i++) {
-				if (children[i].nodeType === 1) inqueue.push(children[i])
-			}
-		}
-		outqueue.shift()
-		return outqueue
-	}
-
-	/*
-	 * Contructs a Markdown string of replacement text for a given node
-	 */
-
-	function getContent (node) {
-		var text = ''
-		for (var i = 0; i < node.childNodes.length; i++) {
-			if (node.childNodes[i].nodeType === 1) {
-				text += node.childNodes[i]._replacement
-			} else if (node.childNodes[i].nodeType === 3) {
-				text += node.childNodes[i].data
-			} else continue
-		}
-		return text
-	}
-
-	/*
-	 * Returns the HTML string of an element with its contents converted
-	 */
-
-	function outer (node, content) {
-		return node.cloneNode(false).outerHTML.replace('><', '>' + content + '<')
-	}
-
-	function canConvert (node, filter) {
-		if (typeof filter === 'string') {
-			return filter === node.nodeName.toLowerCase()
-		}
-		if (Array.isArray(filter)) {
-			return filter.indexOf(node.nodeName.toLowerCase()) !== -1
-		} else if (typeof filter === 'function') {
-			return filter.call(toMarkdown, node)
-		} else {
-			throw new TypeError('`filter` needs to be a string, array, or function')
-		}
-	}
-
-	function isFlankedByWhitespace (side, node) {
-		var sibling
-		var regExp
-		var isFlanked
-
-		if (side === 'left') {
-			sibling = node.previousSibling
-			regExp = / $/
-		} else {
-			sibling = node.nextSibling
-			regExp = /^ /
-		}
-
-		if (sibling) {
-			if (sibling.nodeType === 3) {
-				isFlanked = regExp.test(sibling.nodeValue)
-			} else if (sibling.nodeType === 1 && !isBlock(sibling)) {
-				isFlanked = regExp.test(sibling.textContent)
-			}
-		}
-		return isFlanked
-	}
-
-	function flankingWhitespace (node) {
-		var leading = ''
-		var trailing = ''
-
-		if (!isBlock(node)) {
-			var hasLeading = /^[ \r\n\t]/.test(node.innerHTML)
-			var hasTrailing = /[ \r\n\t]$/.test(node.innerHTML)
-
-			if (hasLeading && !isFlankedByWhitespace('left', node)) {
-				leading = ' '
-			}
-			if (hasTrailing && !isFlankedByWhitespace('right', node)) {
-				trailing = ' '
-			}
-		}
-
-		return { leading: leading, trailing: trailing }
-	}
-
-	/*
-	 * Finds a Markdown converter, gets the replacement, and sets it on
-	 * `_replacement`
-	 */
-
-	function process (node) {
-		var replacement
-		var content = getContent(node)
-
-		// Remove blank nodes
-		if (!isVoid(node) && !/A|TH|TD/.test(node.nodeName) && /^\s*$/i.test(content)) {
-			node._replacement = ''
-			return
-		}
-
-		for (var i = 0; i < converters.length; i++) {
-			var converter = converters[i]
-
-			if (canConvert(node, converter.filter)) {
-				if (typeof converter.replacement !== 'function') {
-					throw new TypeError(
-						'`replacement` needs to be a function that returns a string'
-					)
-				}
-
-				var whitespace = flankingWhitespace(node)
-
-				if (whitespace.leading || whitespace.trailing) {
-					content = content.trim()
-				}
-				replacement = whitespace.leading +
-					converter.replacement.call(toMarkdown, content, node) +
-					whitespace.trailing
-				break
-			}
-		}
-
-		node._replacement = replacement
-	}
-
-	toMarkdown = function (input, options) {
-		options = options || {}
-
-		if (typeof input !== 'string') {
-			throw new TypeError(input + ' is not a string')
-		}
-
-		// Escape potential ol triggers
-		input = input.replace(/(\d+)\. /g, '$1\\. ')
-
-		var clone = htmlToDom(input).body
-		var nodes = bfsOrder(clone)
-		var output
-
-		converters = mdConverters.slice(0)
-		if (options.gfm) {
-			converters = gfmConverters.concat(converters)
-		}
-
-		if (options.converters) {
-			converters = options.converters.concat(converters)
-		}
-
-		// Process through nodes in reverse (so deepest child elements are first).
-		for (var i = nodes.length - 1; i >= 0; i--) {
-			process(nodes[i])
-		}
-		output = getContent(clone)
-
-		return output.replace(/^[\t\r\n]+|[\t\r\n\s]+$/g, '')
-			.replace(/\n\s+\n/g, '\n\n')
-			.replace(/\n{3,}/g, '\n\n')
-	}
-
-	toMarkdown.isBlock = isBlock
-	toMarkdown.isVoid = isVoid
-	toMarkdown.outer = outer
-
-	module.exports = toMarkdown
-
-},{"./lib/gfm-converters":2,"./lib/html-parser":3,"./lib/md-converters":4,"collapse-whitespace":7}],2:[function(require,module,exports){
-	'use strict'
-
-	function cell (content, node) {
-		var index = Array.prototype.indexOf.call(node.parentNode.childNodes, node)
-		var prefix = ' '
-		if (index === 0) prefix = '| '
-		return prefix + content + ' |'
-	}
-
-	var highlightRegEx = /highlight highlight-(\S+)/
-
-	module.exports = [
-		{
-			filter: 'br',
-			replacement: function () {
-				return '\n'
-			}
-		},
-		{
-			filter: ['del', 's', 'strike'],
-			replacement: function (content) {
-				return '~~' + content + '~~'
-			}
-		},
-
-		{
-			filter: function (node) {
-				return node.type === 'checkbox' && node.parentNode.nodeName === 'LI'
-			},
-			replacement: function (content, node) {
-				return (node.checked ? '[x]' : '[ ]') + ' '
-			}
-		},
-
-		{
-			filter: ['th', 'td'],
-			replacement: function (content, node) {
-				return cell(content, node)
-			}
-		},
-
-		{
-			filter: 'tr',
-			replacement: function (content, node) {
-				var borderCells = ''
-				var alignMap = { left: ':--', right: '--:', center: ':-:' }
-
-				if (node.parentNode.nodeName === 'THEAD') {
-					for (var i = 0; i < node.childNodes.length; i++) {
-						var align = node.childNodes[i].attributes.align
-						var border = '---'
-
-						if (align) border = alignMap[align.value] || border
-
-						borderCells += cell(border, node.childNodes[i])
-					}
-				}
-				return '\n' + content + (borderCells ? '\n' + borderCells : '')
-			}
-		},
-
-		{
-			filter: 'table',
-			replacement: function (content) {
-				return '\n\n' + content + '\n\n'
-			}
-		},
-
-		{
-			filter: ['thead', 'tbody', 'tfoot'],
-			replacement: function (content) {
-				return content
-			}
-		},
-
-		// Fenced code blocks
-		{
-			filter: function (node) {
-				return node.nodeName === 'PRE' &&
-					node.firstChild &&
-					node.firstChild.nodeName === 'CODE'
-			},
-			replacement: function (content, node) {
-				return '\n\n```\n' + node.firstChild.textContent + '\n```\n\n'
-			}
-		},
-
-		// Syntax-highlighted code blocks
-		{
-			filter: function (node) {
-				return node.nodeName === 'PRE' &&
-					node.parentNode.nodeName === 'DIV' &&
-					highlightRegEx.test(node.parentNode.className)
-			},
-			replacement: function (content, node) {
-				var language = node.parentNode.className.match(highlightRegEx)[1]
-				return '\n\n```' + language + '\n' + node.textContent + '\n```\n\n'
-			}
-		},
-
-		{
-			filter: function (node) {
-				return node.nodeName === 'DIV' &&
-					highlightRegEx.test(node.className)
-			},
-			replacement: function (content) {
-				return '\n\n' + content + '\n\n'
-			}
-		}
-	]
-
-},{}],3:[function(require,module,exports){
-	/*
-	 * Set up window for Node.js
-	 */
-
-	var _window = (typeof window !== 'undefined' ? window : this)
-
-	/*
-	 * Parsing HTML strings
-	 */
-
-	function canParseHtmlNatively () {
-		var Parser = _window.DOMParser
-		var canParse = false
-
-		// Adapted from https://gist.github.com/1129031
-		// Firefox/Opera/IE throw errors on unsupported types
-		try {
-			// WebKit returns null on unsupported types
-			if (new Parser().parseFromString('', 'text/html')) {
-				canParse = true
-			}
-		} catch (e) {}
-
-		return canParse
-	}
-
-	function createHtmlParser () {
-		var Parser = function () {}
-
-		// For Node.js environments
-		if (typeof document === 'undefined') {
-			var jsdom = require('jsdom')
-			Parser.prototype.parseFromString = function (string) {
-				return jsdom.jsdom(string, {
-					plugins: {
-						FetchExternalResources: [],
-						ProcessExternalResources: false
-					}
-				})
-			}
-		} else {
-			if (!shouldUseActiveX()) {
-				Parser.prototype.parseFromString = function (string) {
-					var doc = document.implementation.createHTMLDocument('')
-					doc.open()
-					doc.write(string)
-					doc.close()
-					return doc
-				}
-			} else {
-				Parser.prototype.parseFromString = function (string) {
-					var doc = new window.ActiveXObject('htmlfile')
-					doc.designMode = 'on' // disable on-page scripts
-					doc.open()
-					doc.write(string)
-					doc.close()
-					return doc
-				}
-			}
-		}
-		return Parser
-	}
-
-	function shouldUseActiveX () {
-		var useActiveX = false
-
-		try {
-			document.implementation.createHTMLDocument('').open()
-		} catch (e) {
-			if (window.ActiveXObject) useActiveX = true
-		}
-
-		return useActiveX
-	}
-
-	module.exports = canParseHtmlNatively() ? _window.DOMParser : createHtmlParser()
-
-},{"jsdom":6}],4:[function(require,module,exports){
-	'use strict'
-
-	module.exports = [
-		{
-			filter: 'p',
-			replacement: function (content) {
-				return '\n\n' + content + '\n\n'
-			}
-		},
-
-		{
-			filter: 'br',
-			replacement: function () {
-				return '  \n'
-			}
-		},
-
-		{
-			filter: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
-			replacement: function (content, node) {
-				var hLevel = node.nodeName.charAt(1)
-				var hPrefix = ''
-				for (var i = 0; i < hLevel; i++) {
-					hPrefix += '#'
-				}
-				return '\n\n' + hPrefix + ' ' + content + '\n\n'
-			}
-		},
-
-		{
-			filter: 'hr',
-			replacement: function () {
-				return '\n\n* * *\n\n'
-			}
-		},
-
-		{
-			filter: ['em', 'i'],
-			replacement: function (content) {
-				return '_' + content + '_'
-			}
-		},
-
-		{
-			filter: ['strong', 'b'],
-			replacement: function (content) {
-				return '**' + content + '**'
-			}
-		},
-
-		// Inline code
-		{
-			filter: function (node) {
-				var hasSiblings = node.previousSibling || node.nextSibling
-				var isCodeBlock = node.parentNode.nodeName === 'PRE' && !hasSiblings
-
-				return node.nodeName === 'CODE' && !isCodeBlock
-			},
-			replacement: function (content) {
-				return '`' + content + '`'
-			}
-		},
-
-		{
-			filter: function (node) {
-				return node.nodeName === 'A' && node.getAttribute('href')
-			},
-			replacement: function (content, node) {
-				var titlePart = node.title ? ' "' + node.title + '"' : ''
-				return '[' + content + '](' + node.getAttribute('href') + titlePart + ')'
-			}
-		},
-
-		{
-			filter: 'img',
-			replacement: function (content, node) {
-				var alt = node.alt || ''
-				var src = node.getAttribute('src') || ''
-				var title = node.title || ''
-				var titlePart = title ? ' "' + title + '"' : ''
-				return src ? '![' + alt + ']' + '(' + src + titlePart + ')' : ''
-			}
-		},
-
-		// Code blocks
-		{
-			filter: function (node) {
-				return node.nodeName === 'PRE' && node.firstChild.nodeName === 'CODE'
-			},
-			replacement: function (content, node) {
-				return '\n\n    ' + node.firstChild.textContent.replace(/\n/g, '\n    ') + '\n\n'
-			}
-		},
-
-		{
-			filter: 'blockquote',
-			replacement: function (content) {
-				content = content.trim()
-				content = content.replace(/\n{3,}/g, '\n\n')
-				content = content.replace(/^/gm, '> ')
-				return '\n\n' + content + '\n\n'
-			}
-		},
-
-		{
-			filter: 'li',
-			replacement: function (content, node) {
-				content = content.replace(/^\s+/, '').replace(/\n/gm, '\n    ')
-				var prefix = '*   '
-				var parent = node.parentNode
-				var index = Array.prototype.indexOf.call(parent.children, node) + 1
-
-				prefix = /ol/i.test(parent.nodeName) ? index + '.  ' : '*   '
-				return prefix + content
-			}
-		},
-
-		{
-			filter: ['ul', 'ol'],
-			replacement: function (content, node) {
-				var strings = []
-				for (var i = 0; i < node.childNodes.length; i++) {
-					strings.push(node.childNodes[i]._replacement)
-				}
-
-				if (/li/i.test(node.parentNode.nodeName)) {
-					return '\n' + strings.join('\n')
-				}
-				return '\n\n' + strings.join('\n') + '\n\n'
-			}
-		},
-
-		{
-			filter: function (node) {
-				return this.isBlock(node)
-			},
-			replacement: function (content, node) {
-				return '\n\n' + this.outer(node, content) + '\n\n'
-			}
-		},
-
-		// Anything else!
-		{
-			filter: function () {
-				return true
-			},
-			replacement: function (content, node) {
-				return this.outer(node, content)
-			}
-		}
-	]
-
-},{}],5:[function(require,module,exports){
-	/**
-	 * This file automatically generated from `build.js`.
-	 * Do not manually edit.
-	 */
-
-	module.exports = [
-		"address",
-		"article",
-		"aside",
-		"audio",
-		"blockquote",
-		"canvas",
-		"dd",
-		"div",
-		"dl",
-		"fieldset",
-		"figcaption",
-		"figure",
-		"footer",
-		"form",
-		"h1",
-		"h2",
-		"h3",
-		"h4",
-		"h5",
-		"h6",
-		"header",
-		"hgroup",
-		"hr",
-		"main",
-		"nav",
-		"noscript",
-		"ol",
-		"output",
-		"p",
-		"pre",
-		"section",
-		"table",
-		"tfoot",
-		"ul",
-		"video"
-	];
-
-},{}],6:[function(require,module,exports){
-
-},{}],7:[function(require,module,exports){
-	'use strict';
-
-	var voidElements = require('void-elements');
-	Object.keys(voidElements).forEach(function (name) {
-		voidElements[name.toUpperCase()] = 1;
-	});
-
-	var blockElements = {};
-	require('block-elements').forEach(function (name) {
-		blockElements[name.toUpperCase()] = 1;
-	});
-
-	/**
-	 * isBlockElem(node) determines if the given node is a block element.
-	 *
-	 * @param {Node} node
-	 * @returns {Boolean}
-	 */
-	function isBlockElem(node) {
-		return !!(node && blockElements[node.nodeName]);
-	}
-
-	/**
-	 * isVoid(node) determines if the given node is a void element.
-	 *
-	 * @param {Node} node
-	 * @returns {Boolean}
-	 */
-	function isVoid(node) {
-		return !!(node && voidElements[node.nodeName]);
-	}
-
-	/**
-	 * whitespace(elem [, isBlock]) removes extraneous whitespace from an
-	 * the given element. The function isBlock may optionally be passed in
-	 * to determine whether or not an element is a block element; if none
-	 * is provided, defaults to using the list of block elements provided
-	 * by the `block-elements` module.
-	 *
-	 * @param {Node} elem
-	 * @param {Function} blockTest
-	 */
-	function collapseWhitespace(elem, isBlock) {
-		if (!elem.firstChild || elem.nodeName === 'PRE') return;
-
-		if (typeof isBlock !== 'function') {
-			isBlock = isBlockElem;
-		}
-
-		var prevText = null;
-		var prevVoid = false;
-
-		var prev = null;
-		var node = next(prev, elem);
-
-		while (node !== elem) {
-			if (node.nodeType === 3) {
-				// Node.TEXT_NODE
-				var text = node.data.replace(/[ \r\n\t]+/g, ' ');
-
-				if ((!prevText || / $/.test(prevText.data)) && !prevVoid && text[0] === ' ') {
-					text = text.substr(1);
-				}
-
-				// `text` might be empty at this point.
-				if (!text) {
-					node = remove(node);
-					continue;
-				}
-
-				node.data = text;
-				prevText = node;
-			} else if (node.nodeType === 1) {
-				// Node.ELEMENT_NODE
-				if (isBlock(node) || node.nodeName === 'BR') {
-					if (prevText) {
-						prevText.data = prevText.data.replace(/ $/, '');
-					}
-
-					prevText = null;
-					prevVoid = false;
-				} else if (isVoid(node)) {
-					// Avoid trimming space around non-block, non-BR void elements.
-					prevText = null;
-					prevVoid = true;
-				}
-			} else {
-				node = remove(node);
-				continue;
-			}
-
-			var nextNode = next(prev, node);
-			prev = node;
-			node = nextNode;
-		}
-
-		if (prevText) {
-			prevText.data = prevText.data.replace(/ $/, '');
-			if (!prevText.data) {
-				remove(prevText);
-			}
-		}
-	}
-
-	/**
-	 * remove(node) removes the given node from the DOM and returns the
-	 * next node in the sequence.
-	 *
-	 * @param {Node} node
-	 * @returns {Node} node
-	 */
-	function remove(node) {
-		var next = node.nextSibling || node.parentNode;
-
-		node.parentNode.removeChild(node);
-
-		return next;
-	}
-
-	/**
-	 * next(prev, current) returns the next node in the sequence, given the
-	 * current and previous nodes.
-	 *
-	 * @param {Node} prev
-	 * @param {Node} current
-	 * @returns {Node}
-	 */
-	function next(prev, current) {
-		if (prev && prev.parentNode === current || current.nodeName === 'PRE') {
-			return current.nextSibling || current.parentNode;
-		}
-
-		return current.firstChild || current.nextSibling || current.parentNode;
-	}
-
-	module.exports = collapseWhitespace;
-
-},{"block-elements":5,"void-elements":8}],8:[function(require,module,exports){
-	/**
-	 * This file automatically generated from `pre-publish.js`.
-	 * Do not manually edit.
-	 */
-
-	module.exports = {
-		"area": true,
-		"base": true,
-		"br": true,
-		"col": true,
-		"embed": true,
-		"hr": true,
-		"img": true,
-		"input": true,
-		"keygen": true,
-		"link": true,
-		"menuitem": true,
-		"meta": true,
-		"param": true,
-		"source": true,
-		"track": true,
-		"wbr": true
-	};
-
-},{}]},{},[1])(1)
-});

+ 36 - 0
packages/ckeditor5-markdown-gfm/src/markdown.js

@@ -0,0 +1,36 @@
+/**
+ * @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 markdown-gfm/markdown
+ */
+
+import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
+import GFMDataProcessor from './gfmdataprocessor';
+
+/**
+ * The GitHub Flavored Markdown (GFM) plugin.
+ *
+ * For a detailed overview, check the {@glink features/markdown Markdown feature documentation}.
+ *
+ * @extends module:core/plugin~Plugin
+ */
+export default class Markdown extends Plugin {
+	/**
+	 * @inheritDoc
+	 */
+	constructor( editor ) {
+		super( editor );
+
+		editor.data.processor = new GFMDataProcessor( editor.data.viewDocument );
+	}
+
+	/**
+	 * @inheritDoc
+	 */
+	static get pluginName() {
+		return 'Markdown';
+	}
+}

+ 37 - 0
packages/ckeditor5-markdown-gfm/src/markdown2html/markdown2html.js

@@ -0,0 +1,37 @@
+/**
+ * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/**
+ * @module markdown-gfm/markdown2html
+ */
+
+import marked from 'marked';
+
+// Overrides.
+marked.use( {
+	tokenizer: {
+		// Disable the autolink rule in the lexer.
+		autolink: () => null,
+		url: () => null
+	}
+} );
+
+/**
+ * Parses markdown string to an HTML.
+ *
+ * @param {String} markdown
+ * @returns {String}
+ */
+export default function markdown2html( markdown ) {
+	return marked.parse( markdown, {
+		gfm: true,
+		breaks: true,
+		tables: true,
+		xhtml: true,
+		headerIds: false
+	} );
+}
+
+export { marked };

+ 26 - 3
packages/ckeditor5-markdown-gfm/tests/_utils/utils.js

@@ -14,18 +14,41 @@ import { StylesProcessor } from '@ckeditor/ckeditor5-engine/src/view/stylesmap';
  * @param {String} markdown Markdown to be processed to view.
  * @param {String} viewString Expected view structure.
  * @param {String} [normalizedMarkdown] When converting back to the markdown it might be different than provided input
+ * @param {Object} [options] Additional options.
+ * @param {Function} [options.setup] A function that receives the data processor instance before its execution.
  * markdown string (which will be used if this parameter is not provided).
  */
-export function testDataProcessor( markdown, viewString, normalizedMarkdown ) {
+export function testDataProcessor( markdown, viewString, normalizedMarkdown, options ) {
 	const viewDocument = new ViewDocument( new StylesProcessor() );
+
 	const dataProcessor = new MarkdownDataProcessor( viewDocument );
+
+	if ( options && options.setup ) {
+		options.setup( dataProcessor );
+	}
 	const viewFragment = dataProcessor.toView( markdown );
 
+	const html = cleanHtml( stringify( viewFragment ) );
+
 	// Check if view has correct data.
-	expect( stringify( viewFragment ) ).to.equal( viewString );
+	expect( html ).to.equal( viewString );
 
 	// Check if converting back gives the same result.
 	const normalized = typeof normalizedMarkdown !== 'undefined' ? normalizedMarkdown : markdown;
 
-	expect( dataProcessor.toData( viewFragment ) ).to.equal( normalized );
+	expect( cleanMarkdown( dataProcessor.toData( viewFragment ) ) ).to.equal( normalized );
+}
+
+function cleanHtml( html ) {
+	// Space between table elements.
+	html = html.replace( /(th|td|tr)>\s+<(\/?(?:th|td|tr))/g, '$1><$2' );
+	return html;
+}
+
+function cleanMarkdown( markdown ) {
+	// Trim spaces at the end of the lines.
+	markdown = markdown.replace( / +$/gm, '' );
+	// Trim linebreak at the very beginning.
+	markdown = markdown.replace( /^\s+/g, '' );
+	return markdown;
 }

+ 31 - 13
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/blockquotes.js

@@ -23,9 +23,9 @@ describe( 'GFMDataProcessor', () => {
 		it( 'should process nested blockquotes', () => {
 			testDataProcessor(
 				'> foo\n' +
-				'> \n' +
+				'>\n' +
 				'> > bar\n' +
-				'> \n' +
+				'>\n' +
 				'> foo',
 
 				// GitHub is rendering as:
@@ -51,7 +51,7 @@ describe( 'GFMDataProcessor', () => {
 		it( 'should process list within a blockquote', () => {
 			testDataProcessor(
 				'> A list within a blockquote:\n' +
-				'> \n' +
+				'>\n' +
 				'> *   asterisk 1\n' +
 				'> *   asterisk 2\n' +
 				'> *   asterisk 3',
@@ -80,13 +80,13 @@ describe( 'GFMDataProcessor', () => {
 		it( 'should process blockquotes with code inside with ```', () => {
 			testDataProcessor(
 				'> Example 1:\n' +
-				'> \n' +
+				'>\n' +
 				'> ```\n' +
 				'> code 1\n' +
 				'> ```\n' +
-				'> \n' +
+				'>\n' +
 				'> Example 2:\n' +
-				'> \n' +
+				'>\n' +
 				'> ```\n' +
 				'> code 2\n' +
 				'> ```',
@@ -115,8 +115,23 @@ describe( 'GFMDataProcessor', () => {
 						'<code>' +
 							'code 2' +
 						'</code>' +
-					'</pre>' +
-				'</blockquote>'
+					// Space after `</pre>` might be due to bug in engine. See: https://github.com/ckeditor/ckeditor5/issues/7863.
+					'</pre> ' +
+				'</blockquote>',
+
+				'> Example 1:\n' +
+				'>\n' +
+				'> ```\n' +
+				'> code 1\n' +
+				'> ```\n' +
+				'>\n' +
+				'> Example 2:\n' +
+				'>\n' +
+				'> ```\n' +
+				'> code 2\n' +
+				'> ```' +
+				// The below is an artefact of space after `</pre>`. See comment above & https://github.com/ckeditor/ckeditor5/issues/7863.
+				'\n>\n>'
 			);
 		} );
 
@@ -154,21 +169,24 @@ describe( 'GFMDataProcessor', () => {
 						'<code>' +
 							'code 2' +
 						'</code>' +
-					'</pre>' +
+					// Space after `</pre>` might be due to bug in engine. See: https://github.com/ckeditor/ckeditor5/issues/7863.
+					'</pre> ' +
 				'</blockquote>',
 
 				// When converting back to data, DataProcessor will normalize tabs to ```.
 				'> Example 1:\n' +
-				'> \n' +
+				'>\n' +
 				'> ```\n' +
 				'> code 1\n' +
 				'> ```\n' +
-				'> \n' +
+				'>\n' +
 				'> Example 2:\n' +
-				'> \n' +
+				'>\n' +
 				'> ```\n' +
 				'> code 2\n' +
-				'> ```'
+				'> ```' +
+				// The below is an artefact of space after `</pre>`. See comment above & https://github.com/ckeditor/ckeditor5/issues/7863.
+				'\n>\n>'
 			);
 		} );
 	} );

+ 56 - 20
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/code.js

@@ -27,11 +27,11 @@ describe( 'GFMDataProcessor', () => {
 			testDataProcessor(
 				'regular text and` inline code`',
 
-				'<p>regular text and<code>inline code</code></p>',
+				'<p>regular text and<code> inline code</code></p>',
 
 				// When converting back it will be normalized and spaces
 				// at the beginning of inline code will be removed.
-				'regular text and`inline code`'
+				'regular text and `inline code`'
 			);
 		} );
 
@@ -45,7 +45,7 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should properly process backticks inside code spans #2', () => {
 			testDataProcessor(
-				'`` some `backticks` inside ``',
+				'``some `backticks` inside``',
 
 				'<p><code>some `backticks` inside</code></p>'
 			);
@@ -142,17 +142,17 @@ describe( 'GFMDataProcessor', () => {
 				'<pre><code>the lines in this block  \n' +
 				'all contain trailing spaces  </code></pre>',
 
-				// When converting back tabs are normalized to ```.
+				// When converting back tabs are normalized to ```, while the test function remove trailing spaces.
 				'```\n' +
-				'the lines in this block  \n' +
-				'all contain trailing spaces  \n' +
+				'the lines in this block\n' +
+				'all contain trailing spaces\n' +
 				'```'
 			);
 		} );
 
 		it( 'should process code block with language name', () => {
 			testDataProcessor(
-				'``` js\n' +
+				'```js\n' +
 				'var a = \'hello\';\n' +
 				'console.log(a + \' world\');\n' +
 				'```',
@@ -160,7 +160,7 @@ describe( 'GFMDataProcessor', () => {
 				// GitHub is rendering as special html with syntax highlighting.
 				// We will need to handle this separately by some feature.
 
-				'<pre><code class="lang-js">var a = \'hello\';\n' +
+				'<pre><code class="language-js">var a = \'hello\';\n' +
 				'console.log(a + \' world\');</code></pre>'
 			);
 		} );
@@ -174,11 +174,11 @@ describe( 'GFMDataProcessor', () => {
 				// GitHub is rendering as special html with syntax highlighting.
 				// We will need to handle this separately by some feature.
 
-				'<pre><code class="lang-bash">#!/bin/bash</code></pre>',
+				'<pre><code class="language-bash">#!/bin/bash</code></pre>',
 
 				// When converting back ~~~ are normalized to ```.
 
-				'``` bash\n' +
+				'```bash\n' +
 				'#!/bin/bash\n' +
 				'```'
 			);
@@ -186,7 +186,7 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process code block with language name and using ``````` as delimiter', () => {
 			testDataProcessor(
-				'``````` js\n' +
+				'```````js\n' +
 				'var a = \'hello\';\n' +
 				'console.log(a + \' world\');\n' +
 				'```````',
@@ -194,12 +194,12 @@ describe( 'GFMDataProcessor', () => {
 				// GitHub is rendering as special html with syntax highlighting.
 				// We will need to handle this separately by some feature.
 
-				'<pre><code class="lang-js">var a = \'hello\';\n' +
+				'<pre><code class="language-js">var a = \'hello\';\n' +
 				'console.log(a + \' world\');</code></pre>',
 
 				// When converting back ``````` are normalized to ```.
 
-				'``` js\n' +
+				'```js\n' +
 				'var a = \'hello\';\n' +
 				'console.log(a + \' world\');\n' +
 				'```'
@@ -216,12 +216,12 @@ describe( 'GFMDataProcessor', () => {
 				// GitHub is rendering as special html with syntax highlighting.
 				// We will need to handle this separately by some feature.
 
-				'<pre><code class="lang-js">var a = \'hello\';\n' +
+				'<pre><code class="language-js">var a = \'hello\';\n' +
 				'console.log(a + \' world\');</code></pre>',
 
 				// When converting back ~~~~~~~~~~ are normalized to ```.
 
-				'``` js\n' +
+				'```js\n' +
 				'var a = \'hello\';\n' +
 				'console.log(a + \' world\');\n' +
 				'```'
@@ -230,13 +230,13 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process empty code block', () => {
 			testDataProcessor(
-				'``` js\n' +
+				'```js\n' +
 				'```',
 
 				// GitHub is rendering as special html with syntax highlighting.
 				// We will need to handle this separately by some feature.
 
-				'<pre><code class="lang-js"></code></pre>',
+				'<pre><code class="language-js"></code></pre>',
 
 				// When converting back, empty code blocks will be removed.
 				// This might be an issue when switching from source to editor
@@ -247,14 +247,14 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process code block with empty line', () => {
 			testDataProcessor(
-				'``` js\n' +
+				'```js\n' +
 				'\n' +
 				'```',
 
 				// GitHub is rendering as special html with syntax highlighting.
 				// We will need to handle this separately by some feature.
 
-				'<pre><code class="lang-js"></code></pre>',
+				'<pre><code class="language-js"></code></pre>',
 
 				// When converting back, empty code blocks will be removed.
 				// This might be an issue when switching from source to editor
@@ -273,7 +273,43 @@ describe( 'GFMDataProcessor', () => {
 				'<p><code>code `` code ```</code></p>',
 
 				// When converting back ````` will be normalized to ``.
-				'`` code `` code ``` ``'
+				'`code `` code ``` `'
+			);
+		} );
+
+		it( 'should handle triple ticks inside code', () => {
+			testDataProcessor(
+				'````\n' +
+				'```\n' +
+				'Code\n' +
+				'```\n' +
+				'````',
+
+				'<pre><code>' +
+				'```\n' +
+				'Code\n' +
+				'```' +
+				'</code></pre>'
+			);
+		} );
+
+		it( 'should handle triple and quatruple ticks inside code', () => {
+			testDataProcessor(
+				'`````\n' +
+				'````\n' +
+				'```\n' +
+				'Code\n' +
+				'```\n' +
+				'````\n' +
+				'`````',
+
+				'<pre><code>' +
+				'````\n' +
+				'```\n' +
+				'Code\n' +
+				'```\n' +
+				'````' +
+				'</code></pre>'
 			);
 		} );
 	} );

+ 42 - 8
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/escaping.js

@@ -5,6 +5,7 @@
 
 import MarkdownDataProcessor from '../../src/gfmdataprocessor';
 import { stringify } from '@ckeditor/ckeditor5-engine/src/dev-utils/view';
+import { testDataProcessor } from '../../tests/_utils/utils';
 import ViewDocument from '@ckeditor/ckeditor5-engine/src/view/document';
 import { StylesProcessor } from '@ckeditor/ckeditor5-engine/src/view/stylesmap';
 
@@ -19,22 +20,22 @@ const testCases = {
 	'right paren': { test: '\\)', result: ')' },
 	'greater than': { test: '\\>', result: '>' },
 	'hash': { test: '\\#', result: '#' },
-	'peroid': { test: '\\.', result: '.' },
+	'period': { test: '\\.', result: '.' },
 	'exclamation mark': { test: '\\!', result: '!' },
 	'plus': { test: '\\+', result: '+' },
 	'minus': { test: '\\-', result: '-' }
 };
 
 describe( 'GFMDataProcessor', () => {
-	let dataProcessor;
-
-	beforeEach( () => {
-		const viewDocument = new ViewDocument( new StylesProcessor() );
-		dataProcessor = new MarkdownDataProcessor( viewDocument );
-	} );
-
 	describe( 'escaping', () => {
 		describe( 'toView', () => {
+			let dataProcessor;
+
+			beforeEach( () => {
+				const viewDocument = new ViewDocument( new StylesProcessor() );
+				dataProcessor = new MarkdownDataProcessor( viewDocument );
+			} );
+
 			for ( const key in testCases ) {
 				const test = testCases[ key ].test;
 				const result = testCases[ key ].result;
@@ -70,5 +71,38 @@ describe( 'GFMDataProcessor', () => {
 				expect( stringify( documentFragment ) ).to.equal( '<pre><code>\\`</code></pre>' );
 			} );
 		} );
+
+		describe( 'HTML', () => {
+			// To note that the test util inlines entities in text nodes, hence the expected HTML in these tests
+			// contain the raw characters but we "know" that those are text nodes and therefore should be converted
+			// back to entities when outputting markdown.
+
+			it( 'should escape <', () => {
+				testDataProcessor( '\\<', '<p><</p>' );
+			} );
+
+			it( 'should escape HTML as text', () => {
+				testDataProcessor( '\\<h1>Test\\</h1>', '<p><h1>Test</h1></p>' );
+			} );
+
+			it( 'should not escape \\< inside inline code', () => {
+				testDataProcessor( '`\\<`', '<p><code>\\<</code></p>' );
+			} );
+
+			it( 'should not touch escape-like HTML inside code blocks', () => {
+				testDataProcessor(
+					'```\n' +
+					'\\<h1>Test\\</h1>\n' +
+					'```',
+					'<pre><code>' +
+					'\\<h1>Test\\</h1>' +
+					'</code></pre>' );
+			} );
+
+			// Necessary test as we're overriding Turndown's escape(). Just to be sure.
+			it( 'should still escape markdown characters', () => {
+				testDataProcessor( '\\* \\_', '<p>* _</p>' );
+			} );
+		} );
 	} );
 } );

+ 12 - 2
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/headers.js

@@ -95,7 +95,11 @@ describe( 'GFMDataProcessor', () => {
 				'# header\n' +
 				'# header',
 
-				'<h1>header</h1><h1>header</h1>'
+				'<h1>header</h1><h1>header</h1>',
+
+				'# header\n' +
+				'\n' +
+				'# header'
 			);
 		} );
 
@@ -105,7 +109,13 @@ describe( 'GFMDataProcessor', () => {
 				'## header\n' +
 				'### header',
 
-				'<h1>header</h1><h2>header</h2><h3>header</h3>'
+				'<h1>header</h1><h2>header</h2><h3>header</h3>',
+
+				'# header\n' +
+				'\n' +
+				'## header\n' +
+				'\n' +
+				'### header'
 			);
 		} );
 

+ 26 - 26
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/horizontal-rules.js

@@ -6,24 +6,24 @@
 import { testDataProcessor } from '../_utils/utils';
 
 describe( 'GFMDataProcessor', () => {
-	// Horizontal rules are are always rendered by GitHub as <hr> and normalized when converting
-	// back to * * *.
+	// Horizontal rules are always rendered by GitHub as <hr> and normalized when converting
+	// back to ---.
 	describe( 'horizontal rules', () => {
 		describe( 'dashes', () => {
 			it( '#1', () => {
-				testDataProcessor( '---', '<hr></hr>', '* * *' );
+				testDataProcessor( '---', '<hr></hr>', '---' );
 			} );
 
 			it( '#2', () => {
-				testDataProcessor( ' ---', '<hr></hr>', '* * *' );
+				testDataProcessor( ' ---', '<hr></hr>', '---' );
 			} );
 
 			it( '#3', () => {
-				testDataProcessor( '  ---', '<hr></hr>', '* * *' );
+				testDataProcessor( '  ---', '<hr></hr>', '---' );
 			} );
 
 			it( '#4', () => {
-				testDataProcessor( '   ---', '<hr></hr>', '* * *' );
+				testDataProcessor( '   ---', '<hr></hr>', '---' );
 			} );
 
 			it( '#5 - code', () => {
@@ -43,19 +43,19 @@ describe( 'GFMDataProcessor', () => {
 
 		describe( 'dashes with spaces', () => {
 			it( '#1', () => {
-				testDataProcessor( '- - -', '<hr></hr>', '* * *' );
+				testDataProcessor( '- - -', '<hr></hr>', '---' );
 			} );
 
 			it( '#2', () => {
-				testDataProcessor( ' - - -', '<hr></hr>', '* * *' );
+				testDataProcessor( ' - - -', '<hr></hr>', '---' );
 			} );
 
 			it( '#3', () => {
-				testDataProcessor( '  - - -', '<hr></hr>', '* * *' );
+				testDataProcessor( '  - - -', '<hr></hr>', '---' );
 			} );
 
 			it( '#4', () => {
-				testDataProcessor( '   - - -', '<hr></hr>', '* * *' );
+				testDataProcessor( '   - - -', '<hr></hr>', '---' );
 			} );
 
 			it( '#5 - code', () => {
@@ -75,19 +75,19 @@ describe( 'GFMDataProcessor', () => {
 
 		describe( 'asterisks', () => {
 			it( '#1', () => {
-				testDataProcessor( '***', '<hr></hr>', '* * *' );
+				testDataProcessor( '***', '<hr></hr>', '---' );
 			} );
 
 			it( '#2', () => {
-				testDataProcessor( ' ***', '<hr></hr>', '* * *' );
+				testDataProcessor( ' ***', '<hr></hr>', '---' );
 			} );
 
 			it( '#3', () => {
-				testDataProcessor( '  ***', '<hr></hr>', '* * *' );
+				testDataProcessor( '  ***', '<hr></hr>', '---' );
 			} );
 
 			it( '#4', () => {
-				testDataProcessor( '   ***', '<hr></hr>', '* * *' );
+				testDataProcessor( '   ***', '<hr></hr>', '---' );
 			} );
 
 			it( '#5 - code', () => {
@@ -107,19 +107,19 @@ describe( 'GFMDataProcessor', () => {
 
 		describe( 'asterisks with spaces', () => {
 			it( '#1', () => {
-				testDataProcessor( '* * *', '<hr></hr>', '* * *' );
+				testDataProcessor( '* * *', '<hr></hr>', '---' );
 			} );
 
 			it( '#2', () => {
-				testDataProcessor( ' * * *', '<hr></hr>', '* * *' );
+				testDataProcessor( ' * * *', '<hr></hr>', '---' );
 			} );
 
 			it( '#3', () => {
-				testDataProcessor( '  * * *', '<hr></hr>', '* * *' );
+				testDataProcessor( '  * * *', '<hr></hr>', '---' );
 			} );
 
 			it( '#4', () => {
-				testDataProcessor( '   * * *', '<hr></hr>', '* * *' );
+				testDataProcessor( '   * * *', '<hr></hr>', '---' );
 			} );
 
 			it( '#5 - code', () => {
@@ -139,19 +139,19 @@ describe( 'GFMDataProcessor', () => {
 
 		describe( 'underscores', () => {
 			it( '#1', () => {
-				testDataProcessor( '___', '<hr></hr>', '* * *' );
+				testDataProcessor( '___', '<hr></hr>', '---' );
 			} );
 
 			it( '#2', () => {
-				testDataProcessor( ' ___', '<hr></hr>', '* * *' );
+				testDataProcessor( ' ___', '<hr></hr>', '---' );
 			} );
 
 			it( '#3', () => {
-				testDataProcessor( '  ___', '<hr></hr>', '* * *' );
+				testDataProcessor( '  ___', '<hr></hr>', '---' );
 			} );
 
 			it( '#4', () => {
-				testDataProcessor( '   ___', '<hr></hr>', '* * *' );
+				testDataProcessor( '   ___', '<hr></hr>', '---' );
 			} );
 
 			it( '#5 - code', () => {
@@ -171,19 +171,19 @@ describe( 'GFMDataProcessor', () => {
 
 		describe( 'underscores with spaces', () => {
 			it( '#1', () => {
-				testDataProcessor( '_ _ _', '<hr></hr>', '* * *' );
+				testDataProcessor( '_ _ _', '<hr></hr>', '---' );
 			} );
 
 			it( '#2', () => {
-				testDataProcessor( ' _ _ _', '<hr></hr>', '* * *' );
+				testDataProcessor( ' _ _ _', '<hr></hr>', '---' );
 			} );
 
 			it( '#3', () => {
-				testDataProcessor( '  _ _ _', '<hr></hr>', '* * *' );
+				testDataProcessor( '  _ _ _', '<hr></hr>', '---' );
 			} );
 
 			it( '#4', () => {
-				testDataProcessor( '   _ _ _', '<hr></hr>', '* * *' );
+				testDataProcessor( '   _ _ _', '<hr></hr>', '---' );
 			} );
 
 			it( '#5 - code', () => {

+ 26 - 0
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/html.js

@@ -0,0 +1,26 @@
+/**
+ * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
+ */
+
+import { testDataProcessor } from '../_utils/utils';
+
+describe( 'GFMDataProcessor', () => {
+	describe( 'html', () => {
+		it( 'should keep html', () => {
+			testDataProcessor(
+				'test with <keep>html</keep> and <notkeep>not html</notkeep>',
+
+				'<p>test with <keep>html</keep> and <notkeep>not html</notkeep></p>',
+
+				'test with <keep>html</keep> and not html',
+
+				{
+					setup: dataProcessor => {
+						dataProcessor.keepHtml( 'keep' );
+					}
+				}
+			);
+		} );
+	} );
+} );

+ 3 - 3
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/images.js

@@ -35,7 +35,7 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process referenced images', () => {
 			testDataProcessor(
-				'![alt text][logo]\n' +
+				'![alt text][logo]\n\n' +
 				'[logo]: http://example.com/image.png "title text"',
 
 				'<p><img alt="alt text" src="http://example.com/image.png" title="title text"></img></p>',
@@ -47,7 +47,7 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process referenced images without title', () => {
 			testDataProcessor(
-				'![alt text][logo]\n' +
+				'![alt text][logo]\n\n' +
 				'[logo]: http://example.com/image.png',
 
 				'<p><img alt="alt text" src="http://example.com/image.png"></img></p>',
@@ -59,7 +59,7 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process referenced images without alt text', () => {
 			testDataProcessor(
-				'![][logo]\n' +
+				'![][logo]\n\n' +
 				'[logo]: http://example.com/image.png "title text"',
 
 				'<p><img alt="" src="http://example.com/image.png" title="title text"></img></p>',

+ 47 - 125
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/links.js

@@ -7,57 +7,34 @@ import { testDataProcessor } from '../_utils/utils';
 
 describe( 'GFMDataProcessor', () => {
 	describe( 'links', () => {
-		it( 'should autolink', () => {
-			testDataProcessor(
-				'Link: <http://example.com/>.',
-				'<p>Link: <a href="http://example.com/">http://example.com/</a>.</p>',
-
-				// When converting back it will be represented as standard markdown link.
-				'Link: [http://example.com/](http://example.com/).'
-			);
-		} );
-
-		it( 'should autolink #2', () => {
+		it( 'should not autolink', () => {
 			testDataProcessor(
 				'Link: http://example.com/.',
-				'<p>Link: <a href="http://example.com/">http://example.com/</a>.</p>',
-
-				// When converting back it will be represented as standard markdown link.
-				'Link: [http://example.com/](http://example.com/).'
+				'<p>Link: http://example.com/.</p>'
 			);
 		} );
 
-		it( 'should autolink with params', () => {
+		it( 'should not autolink with params', () => {
 			testDataProcessor(
-				'Link: <http://example.com/?foo=1&bar=2>.',
-				'<p>Link: <a href="http://example.com/?foo=1&bar=2">http://example.com/?foo=1&bar=2</a>.</p>',
-
-				// When converting back it will be represented as standard markdown link.
-				'Link: [http://example.com/?foo=1&bar=2](http://example.com/?foo=1&bar=2).'
+				'Link: http://example.com/?foo=1&bar=2.',
+				'<p>Link: http://example.com/?foo=1&bar=2.</p>'
 			);
 		} );
 
-		it( 'should autolink inside list', () => {
+		it( 'should not autolink inside list', () => {
 			testDataProcessor(
-				'* <http://example.com/>',
-
-				'<ul><li><a href="http://example.com/">http://example.com/</a></li></ul>',
-
-				// When converting back it will be represented as standard markdown link.
-				'*   [http://example.com/](http://example.com/)'
+				'*   http://example.com/',
+				'<ul><li>http://example.com/</li></ul>'
 			);
 		} );
 
-		it( 'should autolink inside blockquote', () => {
+		it( 'should not autolink inside blockquote', () => {
 			testDataProcessor(
-				'> Blockquoted: <http://example.com/>',
+				'> Blockquoted: http://example.com/',
 
 				'<blockquote>' +
-				'<p>Blockquoted: <a href="http://example.com/">http://example.com/</a></p>' +
-				'</blockquote>',
-
-				// When converting back it will be represented as standard markdown link.
-				'> Blockquoted: [http://example.com/](http://example.com/)'
+				'<p>Blockquoted: http://example.com/</p>' +
+				'</blockquote>'
 			);
 		} );
 
@@ -138,37 +115,17 @@ describe( 'GFMDataProcessor', () => {
 			);
 		} );
 
-		it( 'should process inline links with spaces in URL', () => {
-			testDataProcessor(
-				'[URL and title]( /url/has space )',
-				'<p><a href="/url/has space">URL and title</a></p>',
-
-				// When converting back unneeded spaces will be removed.
-				'[URL and title](/url/has space)'
-			);
-		} );
-
-		it( 'should process inline links with titles and spaces in URL', () => {
-			testDataProcessor(
-				'[URL and title]( /url/has space/ "url has space and title")',
-				'<p><a href="/url/has space/" title="url has space and title">URL and title</a></p>',
-
-				// When converting back unneeded spaces will be removed.
-				'[URL and title](/url/has space/ "url has space and title")'
-			);
-		} );
-
-		it( 'should process empty link', () => {
-			testDataProcessor(
-				'[Empty]()',
-
-				'<p><a href="">Empty</a></p>'
-			);
-		} );
+		// it( 'should process empty link', () => {
+		// 	testDataProcessor(
+		// 		'[Empty]()',
+		//
+		// 		'<p><a href="">Empty</a></p>'
+		// 	);
+		// } );
 
 		it( 'should process reference links', () => {
 			testDataProcessor(
-				'Foo [bar] [1].\n' +
+				'Foo [bar][1].\n\n' +
 				'[1]: /url/  "Title"',
 
 				'<p>Foo <a href="/url/" title="Title">bar</a>.</p>',
@@ -181,19 +138,7 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process reference links - without space', () => {
 			testDataProcessor(
-				'Foo [bar][1].\n' +
-				'[1]: /url/  "Title"',
-
-				'<p>Foo <a href="/url/" title="Title">bar</a>.</p>',
-
-				'Foo [bar](/url/ "Title").'
-			);
-		} );
-
-		it( 'should process reference links - with newline', () => {
-			testDataProcessor(
-				'Foo [bar]\n' +
-				'[1].\n' +
+				'Foo [bar][1].\n\n' +
 				'[1]: /url/  "Title"',
 
 				'<p>Foo <a href="/url/" title="Title">bar</a>.</p>',
@@ -204,18 +149,18 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process reference links - with embedded brackets', () => {
 			testDataProcessor(
-				'With [embedded [brackets]] [b].\n' +
+				'With [embedded [brackets]][b].\n\n' +
 				'[b]: /url/',
 
 				'<p>With <a href="/url/">embedded [brackets]</a>.</p>',
 
-				'With [embedded [brackets]](/url/).'
+				'With [embedded \\[brackets\\]](/url/).'
 			);
 		} );
 
 		it( 'should process reference links - with reference indented once', () => {
 			testDataProcessor(
-				'Indented [once][].\n' +
+				'Indented [once][].\n\n' +
 				' [once]: /url',
 
 				'<p>Indented <a href="/url">once</a>.</p>',
@@ -226,7 +171,7 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process reference links - with reference indented twice', () => {
 			testDataProcessor(
-				'Indented [twice][].\n' +
+				'Indented [twice][].\n\n' +
 				'  [twice]: /url',
 
 				'<p>Indented <a href="/url">twice</a>.</p>',
@@ -237,7 +182,7 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process reference links - with reference indented three times', () => {
 			testDataProcessor(
-				'Indented [trice][].\n' +
+				'Indented [trice][].\n\n' +
 				'   [trice]: /url',
 
 				'<p>Indented <a href="/url">trice</a>.</p>',
@@ -246,28 +191,9 @@ describe( 'GFMDataProcessor', () => {
 			);
 		} );
 
-		it( 'should NOT process reference links - with reference indented four times', () => {
-			testDataProcessor(
-				'Indented [four][].\n' +
-				'    [four]: /url',
-
-				// GitHub renders it as:
-				// <p>Indented [four][].<br>
-				// [four]: /url</p>
-				// Marked converts it to the code block.
-				'<p>Indented [four][].</p><pre><code>[four]: /url</code></pre>',
-
-				'Indented [four][].\n' +
-				'\n' +
-				'```\n' +
-				'[four]: /url\n' +
-				'```'
-			);
-		} );
-
 		it( 'should process reference links when title and reference are same #1', () => {
 			testDataProcessor(
-				'[this] [this]\n' +
+				'[this][this]\n\n' +
 				'[this]: foo',
 
 				'<p><a href="foo">this</a></p>',
@@ -278,7 +204,7 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process reference links when title and reference are same #2', () => {
 			testDataProcessor(
-				'[this][this]\n' +
+				'[this][this]\n\n' +
 				'[this]: foo',
 
 				'<p><a href="foo">this</a></p>',
@@ -289,7 +215,7 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process reference links when only title is provided and is same as reference #1', () => {
 			testDataProcessor(
-				'[this] []\n' +
+				'[this][]\n\n' +
 				'[this]: foo',
 
 				'<p><a href="foo">this</a></p>',
@@ -300,7 +226,7 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process reference links when only title is provided and is same as reference #2', () => {
 			testDataProcessor(
-				'[this][]\n' +
+				'[this][]\n\n' +
 				'[this]: foo',
 
 				'<p><a href="foo">this</a></p>',
@@ -311,7 +237,7 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process reference links when only title is provided and is same as reference #3', () => {
 			testDataProcessor(
-				'[this]\n' +
+				'[this]\n\n' +
 				'[this]: foo',
 
 				'<p><a href="foo">this</a></p>',
@@ -321,18 +247,12 @@ describe( 'GFMDataProcessor', () => {
 		} );
 
 		it( 'should not process reference links when reference is not found #1', () => {
-			testDataProcessor(
-				'[this] []',
-
-				'<p>[this] []</p>'
-			);
-		} );
-
-		it( 'should not process reference links when reference is not found #2', () => {
 			testDataProcessor(
 				'[this][]',
 
-				'<p>[this][]</p>'
+				'<p>[this][]</p>',
+
+				'\\[this\\]\\[\\]'
 			);
 		} );
 
@@ -340,35 +260,37 @@ describe( 'GFMDataProcessor', () => {
 			testDataProcessor(
 				'[this]',
 
-				'<p>[this]</p>'
+				'<p>[this]</p>',
+
+				'\\[this\\]'
 			);
 		} );
 
 		it( 'should process reference links nested in brackets #1', () => {
 			testDataProcessor(
-				'[a reference inside [this][]]\n' +
+				'[a reference inside [this][]]\n\n' +
 				'[this]: foo',
 
 				'<p>[a reference inside <a href="foo">this</a>]</p>',
 
-				'[a reference inside [this](foo)]'
+				'\\[a reference inside [this](foo)\\]'
 			);
 		} );
 
 		it( 'should process reference links nested in brackets #2', () => {
 			testDataProcessor(
-				'[a reference inside [this]]\n' +
+				'[a reference inside [this]]\n\n' +
 				'[this]: foo',
 
 				'<p>[a reference inside <a href="foo">this</a>]</p>',
 
-				'[a reference inside [this](foo)]'
+				'\\[a reference inside [this](foo)\\]'
 			);
 		} );
 
 		it( 'should not process reference links when title is same as reference but reference is different', () => {
 			testDataProcessor(
-				'[this](/something/else/)\n' +
+				'[this](/something/else/)\n\n' +
 				'[this]: foo',
 
 				'<p><a href="/something/else/">this</a></p>',
@@ -379,19 +301,19 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should not process reference links suppressed by backslashes', () => {
 			testDataProcessor(
-				'Suppress \\[this] and [this\\].\n' +
+				'Suppress \\[this] and [this\\].\n\n' +
 				'[this]: foo',
 
 				'<p>Suppress [this] and [this].</p>',
 
-				'Suppress [this] and [this].'
+				'Suppress \\[this\\] and \\[this\\].'
 			);
 		} );
 
 		it( 'should process reference links when used across multiple lines #1', () => {
 			testDataProcessor(
 				'This is [multiline\n' +
-				'reference]\n' +
+				'reference]\n\n' +
 				'[multiline reference]: foo',
 
 				'<p>This is <a href="foo">multiline<br></br>reference</a></p>',
@@ -404,7 +326,7 @@ describe( 'GFMDataProcessor', () => {
 		it( 'should process reference links when used across multiple lines #2', () => {
 			testDataProcessor(
 				'This is [multiline \n' +
-				'reference]\n' +
+				'reference]\n\n' +
 				'[multiline reference]: foo',
 
 				'<p>This is <a href="foo">multiline<br></br>reference</a></p>',
@@ -416,7 +338,7 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process reference links case-insensitive', () => {
 			testDataProcessor(
-				'[hi]\n' +
+				'[hi]\n\n' +
 				'[HI]: /url',
 
 				'<p><a href="/url">hi</a></p>',

+ 42 - 0
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/lists.js

@@ -4,6 +4,10 @@
  */
 
 import { testDataProcessor } from '../_utils/utils';
+import MarkdownDataProcessor from '../../src/gfmdataprocessor';
+import HtmlDataProcessor from '@ckeditor/ckeditor5-engine/src/dataprocessor/htmldataprocessor';
+import ViewDocument from '@ckeditor/ckeditor5-engine/src/view/document';
+import { StylesProcessor } from '@ckeditor/ckeditor5-engine/src/view/stylesmap';
 
 describe( 'GFMDataProcessor', () => {
 	describe( 'lists', () => {
@@ -340,4 +344,42 @@ describe( 'GFMDataProcessor', () => {
 			);
 		} );
 	} );
+
+	describe( 'todo lists', () => {
+		it( 'should process todo lists', () => {
+			testDataProcessor(
+				'*   [ ] Item 1\n' +
+				'*   [x] Item 2',
+
+				'<ul>' +
+					'<li><input disabled="" type="checkbox"></input>Item 1</li>' +
+					'<li><input checked="" disabled="" type="checkbox"></input>Item 2</li>' +
+				'</ul>' );
+		} );
+
+		it( 'should process the HTML produced by the todo list feature', () => {
+			const viewDocument = new ViewDocument( new StylesProcessor() );
+
+			const htmlDataProcessor = new HtmlDataProcessor( viewDocument );
+			const mdDataProcessor = new MarkdownDataProcessor( viewDocument );
+
+			const viewFragment = htmlDataProcessor.toView(
+				'<ul class="todo-list">' +
+					'<li><label class="todo-list__label">' +
+						'<input type="checkbox" disabled="disabled">' +
+						'<span class="todo-list__label__description">Item 1</span>' +
+					'</label></li>' +
+					'<li><label class="todo-list__label">' +
+						'<input type="checkbox" disabled="disabled" checked="checked">' +
+						'<span class="todo-list__label__description">Item 2</span>' +
+					'</label></li>' +
+				'</ul>'
+			);
+
+			expect( mdDataProcessor.toData( viewFragment ) ).to.equal(
+				'*   [ ] Item 1\n' +
+				'*   [x] Item 2'
+			);
+		} );
+	} );
 } );

+ 6 - 3
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/manual/gfmdataprocessor.js

@@ -5,17 +5,20 @@
 
 /* globals document */
 
-import MarkdownDataProcessor from '../../../src/gfmdataprocessor';
+import Document from '@ckeditor/ckeditor5-engine/src/view/document';
+import { StylesProcessor } from '@ckeditor/ckeditor5-engine/src/view/stylesmap';
 import { stringify, parse } from '@ckeditor/ckeditor5-engine/src/dev-utils/view';
 
+import MarkdownDataProcessor from '../../../src/gfmdataprocessor';
+
 const markdownTextArea = document.getElementById( 'markdown' );
 const viewTextArea = document.getElementById( 'view' );
-const dataProcessor = new MarkdownDataProcessor();
+const dataProcessor = new MarkdownDataProcessor( new Document( new StylesProcessor() ) );
 
 document.getElementById( 'button_to_view' ).addEventListener( 'click', convertToView );
 document.getElementById( 'button_to_md' ).addEventListener( 'click', convertToMarkdown );
 
-markdownTextArea.value = '### Header\n\nFoo bar baz biz.';
+markdownTextArea.value = '### Header 3\n\nTodo:\n\n* [ ] Test me';
 convertToView();
 
 function convertToView() {

+ 3 - 42
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/paragraphs.js

@@ -40,25 +40,6 @@ describe( 'GFMDataProcessor', () => {
 				// <h1>header</h1>
 				'<p>single line</p><h1>header</h1>',
 
-				// To-markdown always put 2 empty lines after paragraph.
-				'single line\n\n' +
-				'# header'
-			);
-		} );
-
-		it( 'with header after #2', () => {
-			testDataProcessor(
-				'single line\n' +
-				'header\n' +
-				'===',
-
-				// GitHub is rendering as:
-				// <p>single line</p>
-				//
-				// <h1>header</h1>
-				'<p>single line</p><h1>header</h1>',
-
-				// To-markdown always put 2 empty lines after paragraph and normalize header to #.
 				'single line\n' +
 				'\n' +
 				'# header'
@@ -78,17 +59,16 @@ describe( 'GFMDataProcessor', () => {
 				// </blockquote>
 				'<p>single line</p><blockquote><p>quote</p></blockquote>',
 
-				// To-markdown always put 2 empty lines after paragraph.
-				'single line\n' +
+				'single line' +
 				'\n' +
-				'> quote'
+				'\n> quote'
 			);
 		} );
 
 		it( 'with list after', () => {
 			testDataProcessor(
 				'single line\n' +
-				'* item',
+				'*   item',
 
 				// GitHub is rendering as:
 				// <p>single line</p>
@@ -98,29 +78,10 @@ describe( 'GFMDataProcessor', () => {
 				// </ul>
 				'<p>single line</p><ul><li>item</li></ul>',
 
-				// To-markdown always put 2 empty lines after paragraph.
 				'single line\n' +
 				'\n' +
 				'*   item'
 			);
 		} );
-
-		it( 'with div element after', () => {
-			testDataProcessor(
-				'single line\n' +
-				'<div>div element</div>',
-
-				// GitHub is rendering as:
-				// <p>single line</p>
-				//
-				// <div>div element</div>
-				'<p>single line</p><div>div element</div>',
-
-				// To-markdown always put 2 empty lines after paragraph.
-				'single line\n' +
-				'\n' +
-				'<div>div element</div>'
-			);
-		} );
 	} );
 } );

+ 2 - 2
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/strikethrough.js

@@ -9,7 +9,7 @@ describe( 'GFMDataProcessor', () => {
 	describe( 'Strikethrough', () => {
 		it( 'should process strikethrough text', () => {
 			testDataProcessor(
-				'~~deleted~~',
+				'~deleted~',
 
 				'<p><del>deleted</del></p>'
 			);
@@ -17,7 +17,7 @@ describe( 'GFMDataProcessor', () => {
 
 		it( 'should process strikethrough inside text', () => {
 			testDataProcessor(
-				'This is ~~deleted content~~.',
+				'This is ~deleted content~.',
 
 				'<p>This is <del>deleted content</del>.</p>'
 			);

+ 12 - 0
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/strong-emphasis.js

@@ -78,6 +78,18 @@ describe( 'GFMDataProcessor', () => {
 			testDataProcessor(
 				'This should_not_be_emp.',
 
+				'<p>This should_not_be_emp.</p>',
+
+				// Turndow escape markdown markup characters used inside text.
+				'This should\\_not\\_be\\_emp.'
+			);
+		} );
+
+		it( 'should not render escape marks', () => {
+			testDataProcessor(
+				// Following the previous test.
+				'This should\\_not\\_be\\_emp.',
+
 				'<p>This should_not_be_emp.</p>'
 			);
 		} );

+ 2 - 2
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/tables.js

@@ -119,7 +119,7 @@ describe( 'GFMDataProcessor', () => {
 			testDataProcessor(
 				'Header 1|Header 2|Header 3|Header 4\n' +
 				':-------|:------:|-------:|--------\n' +
-				'*Cell 1*  |**Cell 2**  |~~Cell 3~~  |Cell 4',
+				'*Cell 1*  |**Cell 2**  |~Cell 3~  |Cell 4',
 
 				'<table>' +
 					'<thead>' +
@@ -151,7 +151,7 @@ describe( 'GFMDataProcessor', () => {
 				// After converting back it will be normalized.
 				'| Header 1 | Header 2 | Header 3 | Header 4 |\n' +
 				'| :-- | :-: | --: | --- |\n' +
-				'| _Cell 1_ | **Cell 2** | ~~Cell 3~~ | Cell 4 |'
+				'| _Cell 1_ | **Cell 2** | ~Cell 3~ | Cell 4 |'
 			);
 		} );
 	} );

+ 50 - 0
packages/ckeditor5-markdown-gfm/tests/gfmdataprocessor/text.js

@@ -0,0 +1,50 @@
+/**
+ * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
+ */
+
+import { testDataProcessor } from '../_utils/utils';
+
+describe( 'GFMDataProcessor', () => {
+	describe( 'text', () => {
+		describe( 'urls', () => {
+			it( 'should not escape urls', () => {
+				testDataProcessor(
+					'escape\\_this https://test.com/do_[not]-escape escape\\_this',
+					'<p>escape_this https://test.com/do_[not]-escape escape_this</p>'
+				);
+			} );
+
+			it( 'should not escape urls (data escaped between urls)', () => {
+				testDataProcessor(
+					'escape\\_this https://test.com/do_[not]-escape escape\\_this https://test.com/do_[not]-escape',
+					'<p>escape_this https://test.com/do_[not]-escape escape_this https://test.com/do_[not]-escape</p>'
+				);
+			} );
+
+			it( 'should not escape urls (at start)', () => {
+				testDataProcessor(
+					'https://test.com/do_[not]-escape escape\\_this',
+					'<p>https://test.com/do_[not]-escape escape_this</p>'
+				);
+			} );
+
+			it( 'should not escape urls (at end)', () => {
+				testDataProcessor(
+					'escape\\_this https://test.com/do_[not]-escape',
+					'<p>escape_this https://test.com/do_[not]-escape</p>'
+				);
+			} );
+
+			[
+				'https://test.com/do_[not]-escape',
+				'http://test.com/do_[not]-escape',
+				'www.test.com/do_[not]-escape'
+			].forEach( url => {
+				it( `should not escape urls (${ url })`, () => {
+					testDataProcessor( url, `<p>${ url }</p>` );
+				} );
+			} );
+		} );
+	} );
+} );

+ 31 - 0
packages/ckeditor5-markdown-gfm/tests/manual/markdown.html

@@ -0,0 +1,31 @@
+<style>
+	pre.markdown-output {
+		background: hsl(70, 7%, 16%);
+		color: hsl(0, 0%, 100%);
+		display: block;
+		font-size: 1em;
+		font-family: Monaco, Menlo, Consolas, "Roboto Mono", "Courier New", "Ubuntu Mono", monospace;
+		padding: 1.333em;
+	}
+</style>
+
+<div id="editor">This is [CKEditor 5](https://ckeditor.com).
+![Sample image](./sample.jpg)
+
+```javascript
+function fancyAlert(arg) {
+  if(arg) {
+    $.facebox({div:'#foo'})
+  }
+}
+```
+
+First Header | Second Header
+------------ | -------------
+Content from cell 1 | Content from cell 2
+Content in the first column | Content in the second column
+</div>
+
+<p>Output:</p>
+
+<pre class="markdown-output"><code id="markdown-output"></code></pre>

+ 71 - 0
packages/ckeditor5-markdown-gfm/tests/manual/markdown.js

@@ -0,0 +1,71 @@
+/**
+ * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
+ */
+
+/* globals console, window, document, setTimeout */
+
+import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';
+
+import ArticlePluginSet from '@ckeditor/ckeditor5-core/tests/_utils/articlepluginset';
+import Strikethrough from '@ckeditor/ckeditor5-basic-styles/src/strikethrough';
+import TodoList from '@ckeditor/ckeditor5-list/src/todolist';
+import TableProperties from '@ckeditor/ckeditor5-table/src/tableproperties';
+import TableCellProperties from '@ckeditor/ckeditor5-table/src/tablecellproperties';
+import CodeBlock from '@ckeditor/ckeditor5-code-block/src/codeblock';
+import Code from '@ckeditor/ckeditor5-basic-styles/src/code';
+import Markdown from '../../src/markdown';
+
+ClassicEditor
+	.create( document.querySelector( '#editor' ), {
+		plugins: [ Markdown, ArticlePluginSet, Code, CodeBlock, Strikethrough, TodoList, TableProperties, TableCellProperties ],
+		toolbar: [
+			'heading',
+			'|',
+			'bold',
+			'italic',
+			'strikethrough',
+			'underline',
+			'link',
+			'|',
+			'code',
+			'codeBlock',
+			'|',
+			'todoList',
+			'bulletedList',
+			'numberedList',
+			'|',
+			'outdent',
+			'indent',
+			'|',
+			'blockQuote',
+			'insertTable',
+			'|',
+			'undo',
+			'redo'
+		],
+		image: {
+			toolbar: [ 'imageStyle:full', 'imageStyle:side', '|', 'imageTextAlternative' ]
+		},
+		table: {
+			contentToolbar: [ 'tableColumn', 'tableRow', 'mergeTableCells', 'tableProperties', 'tableCellProperties' ],
+			tableToolbar: [ 'bold', 'italic' ]
+		}
+	} )
+	.then( editor => {
+		window.editor = editor;
+
+		const outputElement = document.querySelector( '#markdown-output' );
+
+		editor.model.document.on( 'change', () => {
+			outputElement.innerText = editor.getData();
+		} );
+
+		// Set the initial data with delay so hightlight.js doesn't catch them.
+		setTimeout( () => {
+			outputElement.innerText = editor.getData();
+		}, 500 );
+	} )
+	.catch( err => {
+		console.error( err.stack );
+	} );

+ 9 - 0
packages/ckeditor5-markdown-gfm/tests/manual/markdown.md

@@ -0,0 +1,9 @@
+#### GitHub Flavored Markdown Editor
+
+- Play around with [GitHub Flavored Markdown](https://guides.github.com/features/mastering-markdown/).
+- See the markdown generated in the "output" box.
+- You can use `editor.setData( markdownString )` to set markdown content:
+
+```js
+editor.setData( 'This\n\n*is*\n\n**MARKDOWN!**' );
+```

BIN
packages/ckeditor5-markdown-gfm/tests/manual/sample.jpg


+ 26 - 0
packages/ckeditor5-markdown-gfm/tests/markdown.js

@@ -0,0 +1,26 @@
+/**
+ * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
+ */
+
+import Markdown from '../src/markdown';
+import GFMDataProcessor from '../src/gfmdataprocessor';
+import ClassicTestEditor from '@ckeditor/ckeditor5-core/tests/_utils/classictesteditor';
+
+describe( 'Markdown', () => {
+	it( 'has proper name', () => {
+		expect( Markdown.pluginName ).to.equal( 'Markdown' );
+	} );
+
+	it( 'should set editor.data.processor', () => {
+		return ClassicTestEditor
+			.create( '', {
+				plugins: [ Markdown ]
+			} )
+			.then( editor => {
+				expect( editor.data.processor ).to.be.an.instanceof( GFMDataProcessor );
+
+				editor.destroy(); // Tests cleanup.
+			} );
+	} );
+} );

+ 3 - 3
packages/ckeditor5-media-embed/docs/features/media-embed.md

@@ -10,7 +10,7 @@ The {@link module:media-embed/mediaembed~MediaEmbed} feature brings support for
 
 ## Demo
 
-You can use the "Insert media" button in the toolbar to embed media like the following examples. You can also paste the media URL directly into the editor content and it will be [automatically embedded](#automatic-media-embed-on-paste).
+You can use the "Insert media" button in the toolbar to embed media like in the following examples. You can also paste the media URL directly into the editor content and it will be [automatically embedded](#automatic-media-embed-on-paste).
 
 * <input class="example-input" type="text" value="https://www.youtube.com/watch?v=H08tGjXNHO4">
 * <input class="example-input" type="text" value="https://open.spotify.com/album/2IXlgvecaDqOeF3viUZnPI?si=ogVw7KlcQAGZKK4Jz9QzvA">
@@ -74,7 +74,7 @@ Thanks to the ability to hardcode this URL to HTML transformation, the media emb
 
 ### Non-previewable media
 
-Unfortunately, to show previews of media such as tweets, Instagram photos or Facebook posts, the editor would need to retrieve the content of those from an external service. Some of these media providers expose [oEmbed endpoints](https://oembed.com/) but not all and those endpoint responses often require further processing to be embeddable. Most importantly, though, the media embed feature is often not able to request those services due to [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy).
+Unfortunately, to show previews of media such as tweets, Instagram photos or Facebook posts, the editor would need to retrieve the content of these from an external service. Some of these media providers expose [oEmbed endpoints](https://oembed.com/) but not all and those endpoint responses often require further processing to be embeddable. Most importantly, though, the media embed feature is often not able to request those services due to [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy).
 
 The above limitations can be overcome with the help of proxy services like Iframely or Embedly. However, the media embed feature [does not support asynchronous preview providers](https://github.com/ckeditor/ckeditor5-media-embed/issues/16) yet. Therefore, to still allow embedding tweets or Instagram photos, we chose to:
 
@@ -145,7 +145,7 @@ Names of providers **without previews**:
 * `'facebook'`.
 
 <info-box notice>
-	The default media provider configuration does not support all possible media URLs, only the most common are included. Services like Iframely or Embedly support thousands of media providers and it is up to you to define which you want to allow.
+	The default media provider configuration does not support all possible media URLs &mdash; only the most common are included. Services like Iframely or Embedly support thousands of media providers and it is up to you to define which you want to allow.
 </info-box>
 
 #### Extending media providers

+ 1 - 1
packages/ckeditor5-media-embed/src/mediaregistry.js

@@ -59,7 +59,7 @@ export default class MediaRegistry {
 			} );
 
 		/**
-		 * The locale {@link module:utils/locale~Locale} instance.
+		 * The {@link module:utils/locale~Locale} instance.
 		 *
 		 * @member {module:utils/locale~Locale}
 		 */

+ 3 - 3
packages/ckeditor5-media-embed/src/utils.js

@@ -52,13 +52,13 @@ export function isMediaWidget( viewElement ) {
 }
 
 /**
- * Creates a view element representing the media. Either "semantic" one for the data pipeline:
+ * Creates a view element representing the media. Either a "semantic" one for the data pipeline:
  *
  *		<figure class="media">
  *			<oembed url="foo"></oembed>
  *		</figure>
  *
- * or "non-semantic" (for the editing view pipeline):
+ * or a "non-semantic" (for the editing view pipeline):
  *
  *		<figure class="media">
  *			<div data-oembed-url="foo">[ non-semantic media preview for "foo" ]</div>
@@ -104,7 +104,7 @@ export function getSelectedMediaModelWidget( selection ) {
  *
  * @param {module:engine/model/model~Model} model
  * @param {String} url An URL of an embeddable media.
- * @param {module:engine/model/position~Position} [insertPosition] Position to insert media. If not specified,
+ * @param {module:engine/model/position~Position} [insertPosition] Position to insert the media. If not specified,
  * the default behavior of {@link module:engine/model/model~Model#insertContent `model.insertContent()`} will
  * be applied.
  */

+ 3 - 4
packages/ckeditor5-media-embed/tests/mediaembedtoolbar.js

@@ -63,10 +63,9 @@ describe( 'MediaEmbedToolbar', () => {
 
 			setData( model, '[<media url=""></media>]' );
 
-			sinon.assert.calledWithMatch( spy, {
-				view: toolbar,
-				balloonClassName: 'ck-toolbar-container'
-			} );
+			sinon.assert.calledWithMatch( spy, sinon.match( ( { balloonClassName, view } ) => {
+				return view === toolbar && balloonClassName === 'ck-toolbar-container';
+			} ) );
 		} );
 
 		it( 'should set aria-label attribute', () => {

+ 3 - 2
packages/ckeditor5-mention/docs/features/mentions.md

@@ -23,8 +23,9 @@ You can type the "@" character to invoke the mention autocomplete UI. The demo b
 
 In addition to enabling mentions, you may want to check the following productivity features:
 
-* {@link features/text-transformation Automatic text transformation} &ndash; It allows to automatically turn snippets such as `(tm)` into `™` and `"foo"` into `“foo”`.
-* {@link features/autoformat Autoformatting} &ndash; It allows to quickly apply formatting to the content you are writing.
+* {@link features/text-transformation Automatic text transformation} &ndash; Allows to automatically turn snippets such as `(tm)` into `™` and `"foo"` into `“foo”`.
+* {@link features/link#autolink-feature Autolink} &ndash; Turns the links and email addresses typed or pasted into the editor into active URLs.
+* {@link features/autoformat Autoformatting} &ndash; Allows to quickly apply formatting to the content you are writing.
 
 ## Configuration
 

+ 1 - 2
packages/ckeditor5-mention/src/mentionui.js

@@ -34,7 +34,6 @@ const handledKeyCodes = [
 	keyCodes.arrowdown,
 	keyCodes.enter,
 	keyCodes.tab,
-	keyCodes.space,
 	keyCodes.esc
 ];
 
@@ -121,7 +120,7 @@ export default class MentionUI extends Plugin {
 					this._mentionsView.selectPrevious();
 				}
 
-				if ( data.keyCode == keyCodes.enter || data.keyCode == keyCodes.tab || data.keyCode == keyCodes.space ) {
+				if ( data.keyCode == keyCodes.enter || data.keyCode == keyCodes.tab ) {
 					this._mentionsView.executeSelected();
 				}
 

+ 23 - 5
packages/ckeditor5-mention/tests/mentionui.js

@@ -1572,8 +1572,30 @@ describe( 'MentionUI', () => {
 				testExecuteKey( 'enter', keyCodes.enter, feedItems );
 
 				testExecuteKey( 'tab', keyCodes.tab, feedItems );
+			} );
+
+			describe( 'on other keys', () => {
+				it( 'should do nothing on space', async () => {
+					setData( model, '<paragraph>foo []</paragraph>' );
+
+					model.change( writer => {
+						writer.insertText( '@', doc.selection.getFirstPosition() );
+					} );
+
+					const command = editor.commands.get( 'mention' );
+					const spy = testUtils.sinon.spy( command, 'execute' );
+
+					await waitForDebounce();
+					expectChildViewsIsOnState( [ true, false, false, false, false ] );
 
-				testExecuteKey( 'space', keyCodes.space, feedItems );
+					fireKeyDownEvent( {
+						keyCodes: keyCodes.space,
+						preventDefault: sinon.spy(),
+						stopPropagation: sinon.spy()
+					} );
+
+					sinon.assert.notCalled( spy );
+				} );
 			} );
 		} );
 
@@ -1724,8 +1746,6 @@ describe( 'MentionUI', () => {
 					testExecuteKey( 'enter', keyCodes.enter, issues );
 
 					testExecuteKey( 'tab', keyCodes.tab, issues );
-
-					testExecuteKey( 'space', keyCodes.space, issues );
 				} );
 			} );
 		} );
@@ -1849,8 +1869,6 @@ describe( 'MentionUI', () => {
 					testExecuteKey( 'enter', keyCodes.enter, issues );
 
 					testExecuteKey( 'tab', keyCodes.tab, issues );
-
-					testExecuteKey( 'space', keyCodes.space, issues );
 				} );
 
 				describe( 'mouse', () => {

+ 19 - 4
packages/ckeditor5-table/src/tablewalker.js

@@ -516,8 +516,23 @@ class TableSlot {
 		return model.createPositionAt( this._table.getChild( this.row ), this._cellIndex );
 	}
 
-	// @if CK_DEBUG // get isSpanned() { throw new CKEditorError( 'tablewalker-improper-api-usage', this ); }
-	// @if CK_DEBUG // get colspan() { throw new CKEditorError( 'tablewalker-improper-api-usage', this ); }
-	// @if CK_DEBUG // get rowspan() { throw new CKEditorError( 'tablewalker-improper-api-usage', this ); }
-	// @if CK_DEBUG // get cellIndex() { throw new CKEditorError( 'tablewalker-improper-api-usage', this ); }
+	// @if CK_DEBUG // get isSpanned() { throwMissingGetterError( 'isSpanned' ); }
+	// @if CK_DEBUG // get colspan() { throwMissingGetterError( 'colspan' ); }
+	// @if CK_DEBUG // get rowspan() { throwMissingGetterError( 'rowspan' ); }
+	// @if CK_DEBUG // get cellIndex() { throwMissingGetterError( 'cellIndex' ); }
 }
+
+/**
+ * This `TableSlot`'s getter (property) was removed in CKEditor 5 v20.0.0.
+ *
+ * Check out the new `TableWalker`'s API in the documentation.
+ *
+ * @error tableslot-getter-removed
+ * @param {String} getterName
+ */
+
+// @if CK_DEBUG // function throwMissingGetterError( getterName ) {
+// @if CK_DEBUG //		throw new CKEditorError( 'tableslot-getter-removed: This TableSlot getter does not exist any more.', this, {
+// @if CK_DEBUG //			getterName
+// @if CK_DEBUG //		} );
+// @if CK_DEBUG // }

+ 13 - 28
packages/ckeditor5-table/src/utils/ui/contextualballoon.js

@@ -87,11 +87,7 @@ export function getBalloonCellPositionData( editor ) {
 
 	if ( selection.rangeCount > 1 ) {
 		return {
-			target: () => createBoundingRect( selection.getRanges(), modelRange => {
-				const modelTableCell = getTableCellAtPosition( modelRange.start );
-				const viewTableCell = mapper.toViewElement( modelTableCell );
-				return new Rect( domConverter.viewToDom( viewTableCell ) );
-			} ),
+			target: () => createBoundingRect( selection.getRanges(), editor ),
 			positions: BALLOON_POSITIONS
 		};
 	}
@@ -115,30 +111,19 @@ function getTableCellAtPosition( position ) {
 	return isTableCellSelected ? position.nodeAfter : position.findAncestor( 'tableCell' );
 }
 
-// Returns bounding rect for list of rects.
+// Returns bounding rectangle for given model ranges.
 //
-// @param {Array.<module:utils/dom/rect~Rect>|Array.<*>} list List of `Rect`s or any list to map by `mapFn`.
-// @param {Function} mapFn Mapping function for list elements.
+// @param {Iterable.<module:engine/model/range~Range>} ranges Model ranges that the bounding rect should be returned for.
+// @param {module:core/editor/editor~Editor} editor The editor instance.
 // @returns {module:utils/dom/rect~Rect}
-function createBoundingRect( list, mapFn ) {
-	const rectData = {
-		left: Number.POSITIVE_INFINITY,
-		top: Number.POSITIVE_INFINITY,
-		right: Number.NEGATIVE_INFINITY,
-		bottom: Number.NEGATIVE_INFINITY
-	};
-
-	for ( const item of list ) {
-		const rect = mapFn( item );
-
-		rectData.left = Math.min( rectData.left, rect.left );
-		rectData.top = Math.min( rectData.top, rect.top );
-		rectData.right = Math.max( rectData.right, rect.right );
-		rectData.bottom = Math.max( rectData.bottom, rect.bottom );
-	}
-
-	rectData.width = rectData.right - rectData.left;
-	rectData.height = rectData.bottom - rectData.top;
+function createBoundingRect( ranges, editor ) {
+	const mapper = editor.editing.mapper;
+	const domConverter = editor.editing.view.domConverter;
+	const rects = Array.from( ranges ).map( range => {
+		const modelTableCell = getTableCellAtPosition( range.start );
+		const viewTableCell = mapper.toViewElement( modelTableCell );
+		return new Rect( domConverter.viewToDom( viewTableCell ) );
+	} );
 
-	return new Rect( rectData );
+	return Rect.getBoundingRect( rects );
 }

+ 6 - 8
packages/ckeditor5-table/tests/tabletoolbar.js

@@ -89,10 +89,9 @@ describe( 'TableToolbar', () => {
 
 				setData( model, '<table><tableRow><tableCell>[]</tableCell></tableRow></table>' );
 
-				sinon.assert.calledWithMatch( spy, {
-					view: toolbar,
-					balloonClassName: 'ck-toolbar-container'
-				} );
+				sinon.assert.calledWithMatch( spy, sinon.match( ( { balloonClassName, view } ) => {
+					return view === toolbar && balloonClassName === 'ck-toolbar-container';
+				} ) );
 			} );
 
 			it( 'should set aria-label attribute', () => {
@@ -301,10 +300,9 @@ describe( 'TableToolbar', () => {
 
 				setData( model, '[<table><tableRow><tableCell></tableCell></tableRow></table>]' );
 
-				sinon.assert.calledWithMatch( spy, {
-					view: toolbar,
-					balloonClassName: 'ck-toolbar-container'
-				} );
+				sinon.assert.calledWithMatch( spy, sinon.match( ( { balloonClassName, view } ) => {
+					return view === toolbar && balloonClassName === 'ck-toolbar-container';
+				} ) );
 			} );
 		} );
 

+ 4 - 4
packages/ckeditor5-table/tests/tablewalker.js

@@ -629,9 +629,9 @@ describe( 'TableWalker', () => {
 
 		const { value } = walker.next();
 
-		expect( () => value.isSpanned ).to.throw( CKEditorError, 'tablewalker-improper-api-usage' );
-		expect( () => value.colspan ).to.throw( CKEditorError, 'tablewalker-improper-api-usage' );
-		expect( () => value.rowspan ).to.throw( CKEditorError, 'tablewalker-improper-api-usage' );
-		expect( () => value.cellIndex ).to.throw( CKEditorError, 'tablewalker-improper-api-usage' );
+		expect( () => value.isSpanned ).to.throw( CKEditorError, 'tableslot-getter-removed' );
+		expect( () => value.colspan ).to.throw( CKEditorError, 'tableslot-getter-removed' );
+		expect( () => value.rowspan ).to.throw( CKEditorError, 'tableslot-getter-removed' );
+		expect( () => value.cellIndex ).to.throw( CKEditorError, 'tableslot-getter-removed' );
 	} );
 } );

+ 3 - 2
packages/ckeditor5-typing/docs/features/text-transformation.md

@@ -54,8 +54,9 @@ Type snippets such as `(c)`, `3/4`, `!=`, `---`, `"foo"` into the rich-text edit
 
 In addition to enabling automatic text transformations, you may want to check the following productivity features:
 
-* {@link features/autoformat Autoformatting} &ndash; It allows to quickly apply formatting to the content you are writing.
-* {@link features/mentions Mentions} &ndash; It brings support for smart autocompletion.
+* {@link features/autoformat Autoformatting} &ndash; Allows to quickly apply formatting to the content you are writing.
+* {@link features/link#autolink-feature Autolink} &ndash; Turns the links and email addresses typed or pasted into the editor into active URLs.
+* {@link features/mentions Mentions} &ndash; Brings support for smart autocompletion.
 
 ## Configuring transformations
 

+ 5 - 4
packages/ckeditor5-utils/src/collection.js

@@ -201,11 +201,12 @@ export default class Collection {
 			index = this._items.length;
 		} else if ( index > this._items.length || index < 0 ) {
 			/**
-			 * The index number has invalid value.
+			 * The `index` passed to {@link module:utils/collection~Collection#addMany `Collection#addMany()`}
+			 * is invalid. It must be a number between 0 and the the collection's length.
 			 *
 			 * @error collection-add-item-bad-index
 			 */
-			throw new CKEditorError( 'collection-add-item-invalid-index', this );
+			throw new CKEditorError( 'collection-add-item-invalid-index: The index passed to Collection#addMany() is invalid.', this );
 		}
 
 		for ( let offset = 0; offset < items.length; offset++ ) {
@@ -645,7 +646,7 @@ export default class Collection {
 				 *
 				 * @error collection-add-invalid-id
 				 */
-				throw new CKEditorError( 'collection-add-invalid-id', this );
+				throw new CKEditorError( 'collection-add-invalid-id: This item\'s id should be a string.', this );
 			}
 
 			if ( this.get( itemId ) ) {
@@ -654,7 +655,7 @@ export default class Collection {
 				 *
 				 * @error collection-add-item-already-exists
 				 */
-				throw new CKEditorError( 'collection-add-item-already-exists', this );
+				throw new CKEditorError( 'collection-add-item-already-exists: This item already exists in the collection.', this );
 			}
 		} else {
 			item[ idProperty ] = itemId = uid();

+ 17 - 5
packages/ckeditor5-utils/src/dom/emittermixin.js

@@ -49,6 +49,8 @@ const DomEmitterMixin = extend( {}, EmitterMixin, {
 	 * order they were added.
 	 * @param {Boolean} [options.useCapture=false] Indicates that events of this type will be dispatched to the registered
 	 * listener before being dispatched to any EventTarget beneath it in the DOM tree.
+	 * @param {Boolean} [options.usePassive=false] Indicates that the function specified by listener will never call preventDefault()
+	 * and prevents blocking browser's main thread by this event handler.
 	 */
 	listenTo( emitter, ...rest ) {
 		// Check if emitter is an instance of DOM Node. If so, replace the argument with
@@ -179,6 +181,8 @@ extend( ProxyEmitter.prototype, EmitterMixin, {
 	 * @param {Object} [options={}] Additional options.
 	 * @param {Boolean} [options.useCapture=false] Indicates that events of this type will be dispatched to the registered
 	 * listener before being dispatched to any EventTarget beneath it in the DOM tree.
+	 * @param {Boolean} [options.usePassive=false] Indicates that the function specified by listener will never call preventDefault()
+	 * and prevents blocking browser's main thread by this event handler.
 	 */
 	attach( event, callback, options = {} ) {
 		// If the DOM Listener for given event already exist it is pointless
@@ -187,10 +191,15 @@ extend( ProxyEmitter.prototype, EmitterMixin, {
 			return;
 		}
 
-		const domListener = this._createDomListener( event, !!options.useCapture );
+		const listenerOptions = {
+			capture: !!options.useCapture,
+			passive: !!options.usePassive
+		};
+
+		const domListener = this._createDomListener( event, listenerOptions );
 
 		// Attach the native DOM listener to DOM Node.
-		this._domNode.addEventListener( event, domListener, !!options.useCapture );
+		this._domNode.addEventListener( event, domListener, listenerOptions );
 
 		if ( !this._domListeners ) {
 			this._domListeners = {};
@@ -227,10 +236,13 @@ extend( ProxyEmitter.prototype, EmitterMixin, {
 	 * @private
 	 * @method module:utils/dom/emittermixin~ProxyEmitter#_createDomListener
 	 * @param {String} event The name of the event.
-	 * @param {Boolean} useCapture Indicates whether the listener was created for capturing event.
+	 * @param {Object} [options] Additional options.
+	 * @param {Boolean} [options.capture=false] Indicates whether the listener was created for capturing event.
+	 * @param {Boolean} [options.passive=false] Indicates that the function specified by listener will never call preventDefault()
+	 * and prevents blocking browser's main thread by this event handler.
 	 * @returns {Function} The DOM listener callback.
 	 */
-	_createDomListener( event, useCapture ) {
+	_createDomListener( event, options ) {
 		const domListener = domEvt => {
 			this.fire( event, domEvt );
 		};
@@ -239,7 +251,7 @@ extend( ProxyEmitter.prototype, EmitterMixin, {
 		// detach it from the DOM Node, when it is no longer necessary.
 		// See: {@link detach}.
 		domListener.removeListener = () => {
-			this._domNode.removeEventListener( event, domListener, useCapture );
+			this._domNode.removeEventListener( event, domListener, options );
 			delete this._domListeners[ event ];
 		};
 

+ 36 - 1
packages/ckeditor5-utils/src/dom/rect.js

@@ -78,7 +78,8 @@ export default class Rect {
 			// @if CK_DEBUG // }
 
 			if ( isSourceRange ) {
-				copyRectProperties( this, Rect.getDomRangeRects( source )[ 0 ] );
+				const rangeRects = Rect.getDomRangeRects( source );
+				copyRectProperties( this, Rect.getBoundingRect( rangeRects ) );
 			} else {
 				copyRectProperties( this, source.getBoundingClientRect() );
 			}
@@ -381,6 +382,40 @@ export default class Rect {
 
 		return rects;
 	}
+
+	/**
+	 * Returns a bounding rectangle that contains all the given `rects`.
+	 *
+	 * @param {Iterable.<module:utils/dom/rect~Rect>} rects A list of rectangles that should be contained in the result rectangle.
+	 * @returns {module:utils/dom/rect~Rect|null} Bounding rectangle or `null` if no `rects` were given.
+	 */
+	static getBoundingRect( rects ) {
+		const boundingRectData = {
+			left: Number.POSITIVE_INFINITY,
+			top: Number.POSITIVE_INFINITY,
+			right: Number.NEGATIVE_INFINITY,
+			bottom: Number.NEGATIVE_INFINITY
+		};
+		let rectangleCount = 0;
+
+		for ( const rect of rects ) {
+			rectangleCount++;
+
+			boundingRectData.left = Math.min( boundingRectData.left, rect.left );
+			boundingRectData.top = Math.min( boundingRectData.top, rect.top );
+			boundingRectData.right = Math.max( boundingRectData.right, rect.right );
+			boundingRectData.bottom = Math.max( boundingRectData.bottom, rect.bottom );
+		}
+
+		if ( rectangleCount == 0 ) {
+			return null;
+		}
+
+		boundingRectData.width = boundingRectData.right - boundingRectData.left;
+		boundingRectData.height = boundingRectData.bottom - boundingRectData.top;
+
+		return new Rect( boundingRectData );
+	}
 }
 
 // Acquires all the rect properties from the passed source.

+ 6 - 1
packages/ckeditor5-utils/src/focustracker.js

@@ -77,7 +77,12 @@ export default class FocusTracker {
 	 */
 	add( element ) {
 		if ( this._elements.has( element ) ) {
-			throw new CKEditorError( 'focusTracker-add-element-already-exist', this );
+			/**
+			 * This element is already tracked by {@link module:utils/focustracker~FocusTracker}.
+			 *
+			 * @error focusTracker-add-element-already-exist
+			 */
+			throw new CKEditorError( 'focusTracker-add-element-already-exist: This element is already tracked by FocusTracker.', this );
 		}
 
 		this.listenTo( element, 'focus', () => this._focus( element ), { useCapture: true } );

+ 26 - 0
packages/ckeditor5-utils/tests/dom/emittermixin.js

@@ -113,6 +113,32 @@ describe( 'DomEmitterMixin', () => {
 				sinon.assert.calledOnce( spy );
 			} );
 		} );
+
+		describe( 'event passive handling', () => {
+			it( 'should not use passive mode by default', () => {
+				const spy = sinon.spy( node, 'addEventListener' );
+
+				domEmitter.listenTo( node, 'test', () => {} );
+
+				expect( spy.calledWith( 'test', sinon.match.func, sinon.match( { capture: false, passive: false } ) ) ).to.be.true;
+			} );
+
+			it( 'should optionally use passive mode', () => {
+				const spy = sinon.spy( node, 'addEventListener' );
+
+				domEmitter.listenTo( node, 'test', () => {}, { usePassive: true } );
+
+				expect( spy.calledWith( 'test', sinon.match.func, sinon.match( { capture: false, passive: true } ) ) ).to.be.true;
+			} );
+
+			it( 'should not get activated for event capturing (if not desired)', () => {
+				const spy = sinon.spy( node, 'addEventListener' );
+
+				domEmitter.listenTo( node, 'test', () => {}, { useCapture: true } );
+
+				expect( spy.calledWith( 'test', sinon.match.func, sinon.match( { capture: true, passive: false } ) ) ).to.be.true;
+			} );
+		} );
 	} );
 
 	describe( 'stopListening', () => {

+ 86 - 0
packages/ckeditor5-utils/tests/dom/rect.js

@@ -52,6 +52,45 @@ describe( 'Rect', () => {
 			assertRect( new Rect( range ), geometry );
 		} );
 
+		it( 'should accept Range (non–collapsed, sequenced horizontally)', () => {
+			const firstGeometry = geometry;
+			const secondGeometry = Object.assign( {}, geometry, {
+				right: 50,
+				left: 40,
+				width: 10
+			} );
+
+			const range = document.createRange();
+			range.selectNode( document.body );
+			sinon.stub( range, 'getClientRects' ).returns( [ firstGeometry, secondGeometry ] );
+
+			const expectedGeometry = Object.assign( {}, geometry, {
+				width: 30,
+				right: 50
+			} );
+
+			assertRect( new Rect( range ), expectedGeometry );
+		} );
+
+		it( 'should accept Range (non–collapsed, sequenced vertically)', () => {
+			const firstGeometry = geometry;
+			const secondGeometry = Object.assign( {}, geometry, {
+				top: 30,
+				bottom: 40
+			} );
+
+			const range = document.createRange();
+			range.selectNode( document.body );
+			sinon.stub( range, 'getClientRects' ).returns( [ firstGeometry, secondGeometry ] );
+
+			const expectedGeometry = Object.assign( {}, geometry, {
+				height: 30,
+				bottom: 40
+			} );
+
+			assertRect( new Rect( range ), expectedGeometry );
+		} );
+
 		// https://github.com/ckeditor/ckeditor5-utils/issues/153
 		it( 'should accept Range (collapsed)', () => {
 			const range = document.createRange();
@@ -1053,6 +1092,53 @@ describe( 'Rect', () => {
 			assertRect( rects[ 0 ], expectedGeometry );
 		} );
 	} );
+
+	describe( 'getBoundingRect()', () => {
+		it( 'should not return a rect instance when no rectangles were given', () => {
+			expect( Rect.getBoundingRect( [] ) ).to.be.null;
+		} );
+
+		it( 'should calculate proper rectangle when multiple rectangles were given', () => {
+			const rects = [
+				new Rect( geometry ),
+				new Rect( {
+					top: 10,
+					right: 100,
+					bottom: 20,
+					left: 80,
+					width: 20,
+					height: 10
+				} ),
+				new Rect( {
+					top: 50,
+					right: 50,
+					bottom: 60,
+					left: 30,
+					width: 20,
+					height: 10
+				} )
+			];
+
+			assertRect( Rect.getBoundingRect( rects ), {
+				top: 10,
+				right: 100,
+				bottom: 60,
+				left: 20,
+				width: 80,
+				height: 50
+			} );
+		} );
+
+		it( 'should calculate proper rectangle when a single rectangles was given', () => {
+			const rectangles = new Set( [ new Rect( geometry ) ] );
+			assertRect( Rect.getBoundingRect( rectangles ), geometry );
+		} );
+
+		it( 'should return proper type', () => {
+			const rectangles = new Set( [ new Rect( geometry ) ] );
+			expect( Rect.getBoundingRect( rectangles ) ).to.be.instanceOf( Rect );
+		} );
+	} );
 } );
 
 function assertRect( rect, expected ) {

+ 1 - 3
scripts/docs/snippetadapter.js

@@ -202,7 +202,7 @@ module.exports = function snippetAdapter( snippets, options, umbertoHelpers ) {
 				}
 
 				const cssImportsHTML = getHTMLImports( cssFiles, importPath => {
-					return `    <link rel="stylesheet" href="${ importPath }" type="text/css">`;
+					return `    <link rel="stylesheet" href="${ importPath }" type="text/css" data-cke="true">`;
 				} );
 
 				const jsImportsHTML = getHTMLImports( jsFiles, importPath => {
@@ -350,8 +350,6 @@ function getWebpackConfig( snippets, config ) {
 	const webpackConfig = {
 		mode: config.production ? 'production' : 'development',
 
-		devtool: 'source-map',
-
 		entry: {},
 
 		output: {