├── .editorconfig
├── .eslintignore
├── .eslintrc.js
├── .github
├── FUNDING.yml
├── actions
│ └── vsce-package
│ │ ├── Dockerfile
│ │ ├── action.yml
│ │ └── entrypoint.sh
└── workflows
│ └── main.yml
├── .gitignore
├── .vscode
├── extensions.json
├── launch.json
├── settings.json
└── tasks.json
├── .vscodeignore
├── CHANGELOG.md
├── LICENSE.md
├── README.md
├── package-lock.json
├── package.json
├── publish.ps1
├── publish.py
├── resources
├── icon-blend.png
├── icon.blend
├── icon.gvdesign
└── icon.png
├── src
├── MarkdownTable.ts
├── MarkdownTableRegex.ts
├── MarkdownTableUtils.ts
├── decoration
│ └── MarkdownTableDecorationProvider.ts
├── extension.ts
├── formatter
│ ├── MarkdownTableFormatter.types.ts
│ ├── MarkdownTableFormatterProvider.ts
│ ├── MarkdownTableFormatterSettingsImpl.ts
│ └── MarkdownTableFormatterUtils.ts
├── sorter
│ ├── MTSortIndicator.ts
│ ├── MTSortInfo.ts
│ ├── MarkdownTableSortCodeLensProvider.ts
│ ├── MarkdownTableSortCommandArguments.ts
│ ├── MarkdownTableSortDirection.ts
│ ├── MarkdownTableSortOptions.ts
│ └── MarkdownTableSortUtils.ts
└── test
│ ├── files
│ ├── onetable.md
│ ├── tables.md
│ ├── tables.ts
│ ├── tables2.md
│ └── tables3.md
│ ├── runTest.ts
│ └── suite
│ ├── extension.test.ts
│ └── index.ts
└── tsconfig.json
/.editorconfig:
--------------------------------------------------------------------------------
1 | [*.ts]
2 | indent_size = 4
3 | indent_style = tab
4 |
5 | [*.js]
6 | indent_size = 4
7 | indent_style = tab
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | dist
3 | out
4 | .eslintrc.js
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | "env": {
3 | "browser": true,
4 | "es2020": true
5 | },
6 | "extends": [
7 | "eslint:recommended",
8 | "plugin:@typescript-eslint/recommended"
9 | ],
10 | "parser": "@typescript-eslint/parser",
11 | "parserOptions": {
12 | "ecmaVersion": 11,
13 | "sourceType": "module"
14 | },
15 | "plugins": [
16 | "@typescript-eslint"
17 | ],
18 | "rules": {
19 | }
20 | };
21 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: fcrespo82
2 | ko_fi: fcrespo82
3 | custom: 'https://www.paypal.com/donate?hosted_button_id=73E3UAJNR2VM4'
4 |
--------------------------------------------------------------------------------
/.github/actions/vsce-package/Dockerfile:
--------------------------------------------------------------------------------
1 | # Container image that runs your code
2 | FROM node:slim
3 |
4 | RUN npm i -g vsce typescript
5 |
6 | # Copies your code file from your action repository to the filesystem path `/` of the container
7 | COPY entrypoint.sh /entrypoint.sh
8 | # Sets run flag to entrypoint.sh
9 | RUN chmod 700 /entrypoint.sh
10 |
11 | # Code file to execute when the docker container starts up (`entrypoint.sh`)
12 | ENTRYPOINT ["/entrypoint.sh"]
--------------------------------------------------------------------------------
/.github/actions/vsce-package/action.yml:
--------------------------------------------------------------------------------
1 | # action.yml
2 | name: 'Visual Studio code vsce package action'
3 | description: 'Runs vsce package on the repository'
4 |
5 | outputs:
6 | package_name: # id of output
7 | description: 'Filename of the package'
8 | runs:
9 | using: 'docker'
10 | image: 'Dockerfile'
--------------------------------------------------------------------------------
/.github/actions/vsce-package/entrypoint.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh -l
2 |
3 | # Install dependencies from your project
4 | npm ci
5 |
6 | # Packages the Visual Studio Code extension
7 | vsce package
8 |
9 | # Exports the name to the next step
10 | name=`ls *.vsix`
11 | echo "package_name=$name" >> $GITHUB_OUTPUT
--------------------------------------------------------------------------------
/.github/workflows/main.yml:
--------------------------------------------------------------------------------
1 | # This is a basic workflow to help you get started with Actions
2 |
3 | name: Package extension and create release on tag
4 |
5 | # Controls when the action will run. Triggers the workflow on push or pull request
6 | # events but only for the master branch
7 | on:
8 | push:
9 | # Sequence of patterns matched against refs/tags
10 | tags:
11 | - 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
12 |
13 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel
14 | jobs:
15 | # This workflow contains a single job called "build"
16 | build:
17 | # The type of runner that the job will run on
18 | runs-on: ubuntu-latest
19 | # Steps represent a sequence of tasks that will be executed as part of the job
20 | steps:
21 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
22 | - name: Checkout code
23 | uses: actions/checkout@v2
24 |
25 | # Read the changelog for the tag (https://keepachangelog.com compatible)
26 | - name: Changelog Reader
27 | id: changelog
28 | uses: mindsers/changelog-reader-action@v1.3.1
29 |
30 | - name: Create a Release
31 | id: create_release
32 | uses: actions/create-release@v1
33 | env:
34 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token
35 | with:
36 | tag_name: ${{ github.ref }}
37 | # The name of the release. For example, `Release v1.0.1`
38 | release_name: Release ${{ github.ref }}
39 | # Path to file with information about the tag.
40 | body: ${{ steps.changelog.outputs.log_entry }}
41 | - name: Package the extension
42 | id: package
43 | uses: ./.github/actions/vsce-package
44 | with:
45 | args: package
46 | - name: Upload a Release Asset
47 | uses: actions/upload-release-asset@v1.0.2
48 | env:
49 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token
50 | with:
51 | upload_url: ${{ steps.create_release.outputs.upload_url }}
52 | asset_path: ${{ steps.package.outputs.package_name }}
53 | asset_name: ${{ steps.package.outputs.package_name }}
54 | asset_content_type: application/zip
55 | - name: Publish to Open VSX Registry
56 | uses: HaaLeo/publish-vscode-extension@v0
57 | with:
58 | packagePath: ''
59 | extensionFile: ${{ steps.package.outputs.package_name }}
60 | pat: ${{ secrets.OPEN_VSX_TOKEN }}
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.toptal.com/developers/gitignore/api/vscode,macos,node,python
3 | # Edit at https://www.toptal.com/developers/gitignore?templates=vscode,macos,node,python
4 |
5 | ### macOS ###
6 | # General
7 | .DS_Store
8 | .AppleDouble
9 | .LSOverride
10 |
11 | # Icon must end with two \r
12 | Icon
13 |
14 |
15 | # Thumbnails
16 | ._*
17 |
18 | # Files that might appear in the root of a volume
19 | .DocumentRevisions-V100
20 | .fseventsd
21 | .Spotlight-V100
22 | .TemporaryItems
23 | .Trashes
24 | .VolumeIcon.icns
25 | .com.apple.timemachine.donotpresent
26 |
27 | # Directories potentially created on remote AFP share
28 | .AppleDB
29 | .AppleDesktop
30 | Network Trash Folder
31 | Temporary Items
32 | .apdisk
33 |
34 | ### Node ###
35 | # Logs
36 | logs
37 | *.log
38 | npm-debug.log*
39 | yarn-debug.log*
40 | yarn-error.log*
41 | lerna-debug.log*
42 | .pnpm-debug.log*
43 |
44 | # Diagnostic reports (https://nodejs.org/api/report.html)
45 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
46 |
47 | # Runtime data
48 | pids
49 | *.pid
50 | *.seed
51 | *.pid.lock
52 |
53 | # Directory for instrumented libs generated by jscoverage/JSCover
54 | lib-cov
55 |
56 | # Coverage directory used by tools like istanbul
57 | coverage
58 | *.lcov
59 |
60 | # nyc test coverage
61 | .nyc_output
62 |
63 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
64 | .grunt
65 |
66 | # Bower dependency directory (https://bower.io/)
67 | bower_components
68 |
69 | # node-waf configuration
70 | .lock-wscript
71 |
72 | # Compiled binary addons (https://nodejs.org/api/addons.html)
73 | build/Release
74 |
75 | # Dependency directories
76 | node_modules/
77 | jspm_packages/
78 |
79 | # Snowpack dependency directory (https://snowpack.dev/)
80 | web_modules/
81 |
82 | # TypeScript cache
83 | *.tsbuildinfo
84 |
85 | # Optional npm cache directory
86 | .npm
87 |
88 | # Optional eslint cache
89 | .eslintcache
90 |
91 | # Microbundle cache
92 | .rpt2_cache/
93 | .rts2_cache_cjs/
94 | .rts2_cache_es/
95 | .rts2_cache_umd/
96 |
97 | # Optional REPL history
98 | .node_repl_history
99 |
100 | # Output of 'npm pack'
101 | *.tgz
102 |
103 | # Yarn Integrity file
104 | .yarn-integrity
105 |
106 | # dotenv environment variables file
107 | .env
108 | .env.test
109 | .env.production
110 |
111 | # parcel-bundler cache (https://parceljs.org/)
112 | .cache
113 | .parcel-cache
114 |
115 | # Next.js build output
116 | .next
117 | out
118 |
119 | # Nuxt.js build / generate output
120 | .nuxt
121 | dist
122 |
123 | # Gatsby files
124 | .cache/
125 | # Comment in the public line in if your project uses Gatsby and not Next.js
126 | # https://nextjs.org/blog/next-9-1#public-directory-support
127 | # public
128 |
129 | # vuepress build output
130 | .vuepress/dist
131 |
132 | # Serverless directories
133 | .serverless/
134 |
135 | # FuseBox cache
136 | .fusebox/
137 |
138 | # DynamoDB Local files
139 | .dynamodb/
140 |
141 | # TernJS port file
142 | .tern-port
143 |
144 | # Stores VSCode versions used for testing VSCode extensions
145 | .vscode-test
146 |
147 | # yarn v2
148 | .yarn/cache
149 | .yarn/unplugged
150 | .yarn/build-state.yml
151 | .yarn/install-state.gz
152 | .pnp.*
153 |
154 | ### Python ###
155 | # Byte-compiled / optimized / DLL files
156 | __pycache__/
157 | *.py[cod]
158 | *$py.class
159 |
160 | # C extensions
161 | *.so
162 |
163 | # Distribution / packaging
164 | .Python
165 | build/
166 | develop-eggs/
167 | dist/
168 | downloads/
169 | eggs/
170 | .eggs/
171 | lib/
172 | lib64/
173 | parts/
174 | sdist/
175 | var/
176 | wheels/
177 | share/python-wheels/
178 | *.egg-info/
179 | .installed.cfg
180 | *.egg
181 | MANIFEST
182 |
183 | # PyInstaller
184 | # Usually these files are written by a python script from a template
185 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
186 | *.manifest
187 | *.spec
188 |
189 | # Installer logs
190 | pip-log.txt
191 | pip-delete-this-directory.txt
192 |
193 | # Unit test / coverage reports
194 | htmlcov/
195 | .tox/
196 | .nox/
197 | .coverage
198 | .coverage.*
199 | nosetests.xml
200 | coverage.xml
201 | *.cover
202 | *.py,cover
203 | .hypothesis/
204 | .pytest_cache/
205 | cover/
206 |
207 | # Translations
208 | *.mo
209 | *.pot
210 |
211 | # Django stuff:
212 | local_settings.py
213 | db.sqlite3
214 | db.sqlite3-journal
215 |
216 | # Flask stuff:
217 | instance/
218 | .webassets-cache
219 |
220 | # Scrapy stuff:
221 | .scrapy
222 |
223 | # Sphinx documentation
224 | docs/_build/
225 |
226 | # PyBuilder
227 | .pybuilder/
228 | target/
229 |
230 | # Jupyter Notebook
231 | .ipynb_checkpoints
232 |
233 | # IPython
234 | profile_default/
235 | ipython_config.py
236 |
237 | # pyenv
238 | # For a library or package, you might want to ignore these files since the code is
239 | # intended to run in multiple environments; otherwise, check them in:
240 | # .python-version
241 |
242 | # pipenv
243 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
244 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
245 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
246 | # install all needed dependencies.
247 | #Pipfile.lock
248 |
249 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
250 | __pypackages__/
251 |
252 | # Celery stuff
253 | celerybeat-schedule
254 | celerybeat.pid
255 |
256 | # SageMath parsed files
257 | *.sage.py
258 |
259 | # Environments
260 | .venv
261 | env/
262 | venv/
263 | ENV/
264 | env.bak/
265 | venv.bak/
266 |
267 | # Spyder project settings
268 | .spyderproject
269 | .spyproject
270 |
271 | # Rope project settings
272 | .ropeproject
273 |
274 | # mkdocs documentation
275 | /site
276 |
277 | # mypy
278 | .mypy_cache/
279 | .dmypy.json
280 | dmypy.json
281 |
282 | # Pyre type checker
283 | .pyre/
284 |
285 | # pytype static type analyzer
286 | .pytype/
287 |
288 | # Cython debug symbols
289 | cython_debug/
290 |
291 | #!! ERROR: vscode is undefined. Use list command to see defined gitignore types !!#
292 |
293 | # End of https://www.toptal.com/developers/gitignore/api/vscode,macos,node,python
294 |
295 | out
296 | *.vsix
--------------------------------------------------------------------------------
/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
3 | // Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
4 |
5 | // List of extensions which should be recommended for users of this workspace.
6 | "recommendations": [
7 | "eamodio.tsl-problem-matcher"
8 | ],
9 | // List of extensions recommended by VS Code that should not be recommended for users of this workspace.
10 | "unwantedRecommendations": [
11 |
12 | ]
13 | }
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | // A launch configuration that compiles the extension and then opens it inside a new window
2 | {
3 | "version": "0.2.0",
4 | "configurations": [
5 | {
6 | "name": "Launch Extension",
7 | "type": "extensionHost",
8 | "request": "launch",
9 | "runtimeExecutable": "${execPath}",
10 | "args": [
11 | "--disable-extensions",
12 | "--extensionDevelopmentPath=${workspaceFolder}",
13 | "${workspaceFolder}/src/test/files/onetable.md",
14 | "${workspaceFolder}/src/test/files/tables.md",
15 | "${workspaceFolder}/src/test/files/tables2.md",
16 | "${workspaceFolder}/src/test/files/tables3.md"
17 | ],
18 | "outFiles": [
19 | "${workspaceFolder}/out/**/*.js"
20 | ],
21 | "preLaunchTask": "npm: esbuild",
22 | "smartStep": true
23 | },
24 | {
25 | "name": "Extension Tests",
26 | "type": "extensionHost",
27 | "request": "launch",
28 | "runtimeExecutable": "${execPath}",
29 | "args": [
30 | "--disable-extensions",
31 | "--extensionDevelopmentPath=${workspaceFolder}",
32 | "--extensionTestsPath=${workspaceFolder}/out/test/suite/index"
33 | ],
34 | "outFiles": [
35 | "${workspaceFolder}/out/test/**/*.js"
36 | ],
37 | "internalConsoleOptions": "openOnSessionStart",
38 | "preLaunchTask": "npm: test-compile"
39 | }
40 | ]
41 | }
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "cSpell.words": [
3 | "wcwidth"
4 | ],
5 | }
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "type": "npm",
6 | "script": "watch",
7 | "group": "build",
8 | "problemMatcher": "$esbuild-watch",
9 | "isBackground": true,
10 | "label": "npm: watch",
11 | },
12 | {
13 | "type": "npm",
14 | "script": "build",
15 | "group": "build",
16 | "problemMatcher": "$esbuild",
17 | "label": "npm: build",
18 | }
19 | ]
20 | }
--------------------------------------------------------------------------------
/.vscodeignore:
--------------------------------------------------------------------------------
1 | .vscode/**
2 | .vscode-test/**
3 | out/test/**
4 | out/**/*.map
5 | src/**
6 | .gitignore
7 | tsconfig.json
8 | vsc-extension-quickstart.md
9 | tslint.json
10 | node_modules
11 | src/
12 | resources/**
13 | !resources/icon.png
14 | .github
15 | publish
16 | .eslintignore
17 | **/*.vsix
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file.
4 |
5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6 |
7 | ## Unreleased
8 |
9 | ## [3.0.0] - 2023-08-11
10 |
11 | ### Added
12 |
13 | - You can now choose which CodeLenses to show
14 | - Command to Re-Sort the same table (shows on CodeLens)
15 | - You can now move columns from context menu
16 | - Support for case insensitive sorting
17 | - You can now sort tables from context menu or command pallete
18 | - Support tables with tabs in format line
19 | - New options for Limit Last Column Length (former Limit Last Column Width)
20 | ### Changed
21 |
22 | - Improve internal comparission algorithm
23 | - Improve activation events
24 | - Overall improvements to code
25 |
26 | ### Fixed
27 |
28 | - Test logic (internal)
29 |
30 | ## [2.2.4] - 2021-10-24
31 |
32 | ### Fixed
33 |
34 | - Fixed a regex error where the extension wrongly detect a row with numbers as a format row
35 |
36 | ## [2.2.3] - 2021-08-31
37 |
38 | ### Fixed
39 |
40 | - Fixed extension not working on CRLF line endings
41 |
42 | ## [2.2.2] - 2021-08-25
43 |
44 | ### Fixed
45 |
46 | - Removed preview tag from the extension
47 |
48 | ## [2.2.1] - 2021-08-25
49 |
50 | ### Fixed
51 |
52 | - High CPU load on big files Issue (Issue [#35](https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/35))
53 |
54 | ## [2.2.0] - 2021-07-04
55 |
56 | ### Added
57 |
58 | - Option to focus on an error when the extension shows a notification of a problem.
59 |
60 | ### Changed
61 |
62 | - Simplified parser to better support the markdown syntax used by **Visual Studio Code**, this means that pipes (`|`) inside cells _SHOULD_ be escaped with a backslash (`\`) otherwise they will be interpreted as column dividers. (Issue [#42](https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/42))
63 |
64 | ### Fixed
65 |
66 | - Formatting of tables that are in lists or indented.
67 |
68 | ## [2.1.8] - 2021-05-13
69 |
70 | ### Fixed
71 |
72 | - Pipes missing after formatting (Issue [#40](https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/40))
73 |
74 | ## [2.1.7] - 2021-04-29
75 |
76 | ### Changed
77 |
78 | - Better code structure
79 |
80 | ### Fixed
81 |
82 | - Dependency vulnerabilities
83 | - Extension not activating (changed from webpack to esbuild)
84 |
85 | ## [2.1.6] - 2021-04-27 [YANKED]
86 |
87 | ## [2.1.5] - 2021-04-26 [YANKED]
88 |
89 | ## [2.1.4] - 2021-03-05
90 |
91 | ### Fixed
92 |
93 | - Correct ordering when a column only has numbers
94 |
95 | ## [2.1.3] - 2020-08-14
96 |
97 | ### Removed
98 |
99 | - Removed telemetry.
100 |
101 | ## [2.1.2] - 2020-08-13
102 |
103 | ### Fixed
104 |
105 | - The extension was unable to format a table with one column. (Issue [#31](https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/31))
106 |
107 | ## [2.1.1] - 2020-08-02
108 |
109 | ### Fixed
110 |
111 | - Command **Enable for current language** not found. [#30](https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/30)
112 | - Command **Sort table by header** should not be visible in the command palette. [#30](https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/30)
113 |
114 | ## [2.1.0] - 2020-07-16
115 |
116 | ### Added
117 |
118 | - Limit last column width: Don't let the last column expand more than the wordWrapColumn. (Issue [#20](https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/20))
119 | - Telemetry: send usage statistics. This will help in future development of this extension, but you can turn it of in settings and no personal data is ever sent.
120 | - Format tables even if lines have less columns than header. (Issue [#24](https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/24))
121 |
122 | ### Fixed
123 |
124 | - Case where backtick were not interpreted correctly if near a pipe sign '|'. (Issue [#26](https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/26))
125 | - Some cases the extension got stuck when in files not related to markdown. (Issue [#27](https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/27))
126 |
127 | ## [2.0.5] - 2020-07-09
128 |
129 | ### Changed
130 |
131 | - Changed keybindings for "Move column left/right" to `ctrl+m left` and `ctrl+m right` the old ones conflicted with the built-in fix. (Issue [#25](https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/25))
132 |
133 | ### Fixed
134 |
135 | - Fix a case where multiple backtick were not escaped correctly. (Issue [#26](https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/26))
136 |
137 | ## [2.0.4] - 2020-04-10
138 |
139 | ### Changed
140 |
141 | - Better error message when the header and body have different column numbers (Issue [#24](https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/24))
142 |
143 | ## [2.0.3] - 2020-01-24
144 |
145 | ### Fixed
146 |
147 | - Fix a bug where the extension would fail to format a table with columns header and lines with 1 character. (Issue [#19](https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/19))
148 |
149 | ## [2.0.2] - 2019-11-27
150 |
151 | ### Changed
152 |
153 | - A lot of internal fixes and improvements
154 |
155 | ## [2.0.1] - 2019-11-27
156 |
157 | ### Fixed
158 |
159 | - Various bugs
160 |
161 | ## [2.0.0] - 2019-11-22
162 |
163 | ### Added
164 |
165 | - Global column sizes - options: Disabled, Same column size, Same table size (default: Disabled)
166 | - Sort table by CodeLens
167 | - Reorder columns (Alt+Shift+Left or Right arrow)
168 |
169 | ### Changed
170 |
171 | - A lot of internal fixes and improvements
172 |
173 | ### Removed
174 |
175 | - Limit Last Column Padding - If you use this feature please let me know and I'll find a way to add it back. For now, if you rely on this, keep on the older version.
176 |
177 | ## [1.4.3] - 2019-05-13
178 |
179 | ## [1.4.1] - 2019-01-30
180 |
181 | ### Fixed
182 |
183 | - Ignore pipe symbols between pairs of backtick #4
184 | - Repeat character inserted at end of table on format #6
185 |
186 | ## [1.4.0] - 2018-11-07
187 |
188 | ### Added
189 |
190 | - Configuration to remove the colons from format line if the justification is the same as default (default: false)
191 |
192 | ### Fixed
193 |
194 | - Format tables that have no colons or dashes on the format line (e.g. |||)
195 | - Configuration for `defaultTableJustification` type was wrong
196 |
197 | ## [1.3.3] - 2018-10-09
198 |
199 | ## [1.3.2] - 2018-07-19
200 |
201 | ### Fixed
202 |
203 | - Don't treat \`\|\` (backtick pipes) as a table cell
204 |
205 | ## [1.3.1] - 2018-07-19
206 |
207 | ### Added
208 |
209 | - Option to disable the formatter
210 |
211 | ## [1.3.0] - 2018-05-03
212 |
213 | The extensions was rewritten to take advantage of the Formatter provider VSCode offers.
214 |
215 | ### Changed
216 |
217 | - Format on save
218 | - Now it uses the config provided by VSCode
219 | - Auto Select Entire Document
220 | - Now registers a formatter provider for entire document and for selection
221 |
222 | ### Fixed
223 |
224 | - Sometimes, when formatting, a line was wrongly inserted.
225 |
226 | ## [1.2.1] - 2018-05-02
227 |
228 | ## [1.2.0] - 2018-02-26
229 |
230 | ### Added
231 |
232 | - Format on save
233 |
234 | ## [1.1.0] - 2018-02-26
235 |
236 | ## [1.0.1] - 2018-02-26
237 |
238 | ### Fixed
239 |
240 | - Removed code for 'format on save', feature not ready.
241 |
242 | ## [1.0.0] - 2018-02-23
243 |
244 | - First version
245 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Markdown table formatter
2 |
3 | 
4 | 
5 | 
6 |
7 | A (not so) simple markdown plugin to format tables and other table related features.
8 |
9 | [Changelog](https://github.com/fcrespo82/vscode-markdown-table-formatter/blob/master/CHANGELOG.md)
10 |
11 | ## Features
12 | - Format markdown tables
13 | - Sort tables
14 | - Organize columns moving it left/right
15 |
16 | ## Usage
17 |
18 | Uses VSCode `Format Document` and `Format Selection`
19 |
20 | ### Settings
21 |
22 | - **enable**: Enable or disable the formatter;
23 | - **enableSort**: Enable or disable table sorter;
24 | - **spacePadding**: How many spaces between left and right of each column content;
25 | - **keepFirstAndLastPipes**: Keep first and last pipes "|" in table formatting. Tables are easier to format when pipes are kept;
26 | - **defaultTableJustification**: Defines the default justification for tables that have only "-" on the formatting line;
27 | - **removeColonsIfSameAsDefault**: Remove colons from the format line if the justification is the same as default;
28 | - **globalColumnSizes**: Format tables locally, with same column sizes or same table size;
29 | - **delimiterRowPadding**: Calculates the column sizes based on all tables on the document;
30 | - **limitLastColumnLength**: Control how the last column size is calculated;
31 | - **sortCaseInsensitive**: Sort table columns without considering text case;
32 | - **allowEmptyLines**: Format tables even if lines have less columns than header;
33 | - **markdownGrammarScopes**: File language grammar that will be considered Markdown by this package;
34 | - **whichCodeLensesToShow**: Control what is shown on CodeLens;
35 |
36 | ## Tips
37 |
38 | ### Enable Markdown Table Formatter for the current file type
39 |
40 | To enable Markdown Table Formatter for your current file type: put your cursor in the file, open the Command Palette ^ (CONTROL)+⇧ (SHIFT)+P (⌘ (CMD)+⇧ (SHIFT)+P for mac), and run the `Markdown Table Formatter: Enable for current language` command. This will add language grammar from current editor to the list of languages in the settings for the Markdown Table Formatter package. You can edit this setting manually later if you want to.
41 |
42 | ## Thanks
43 |
44 | Thanks all users for the awesome community that was built here. I never imagined that this extension would be used by more than  users with  downloads.
45 |
46 | Thanks for the support, bug reports and PRs!
47 |
48 | ## Donating
49 |
50 | If you like this extension, please consider [donating](https://www.paypal.com/donate?hosted_button_id=73E3UAJNR2VM4) and/or take a moment to [write a review](https://marketplace.visualstudio.com/items?itemName=fcrespo82.markdown-table-formatter&ssr=false#review-details) and share on [Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmarketplace.visualstudio.com%2Fitems%3FitemName%3Dfcrespo82.markdown-table-formatter%23overview) or [Twitter](https://twitter.com/intent/tweet?text=Just%20discovered%20this%20extension%20on%20the%20%23VSMarketplace&url=https%3A%2F%2Fmarketplace.visualstudio.com%2Fitems%3FitemName%3Dfcrespo82.markdown-table-formatter%23overview)
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "markdown-table-formatter",
3 | "displayName": "Markdown Table Formatter",
4 | "description": "A (not so) simple markdown plugin to format tables and other table related features.",
5 | "homepage": "https://github.com/fcrespo82/vscode-markdown-table-formatter",
6 | "repository": {
7 | "type": "git",
8 | "url": "https://github.com/fcrespo82/vscode-markdown-table-formatter"
9 | },
10 | "bugs": {
11 | "url": "https://github.com/fcrespo82/vscode-markdown-table-formatter/issues"
12 | },
13 | "license": "MIT",
14 | "version": "3.0.0",
15 | "publisher": "fcrespo82",
16 | "icon": "resources/icon.png",
17 | "keywords": [
18 | "markdown",
19 | "table",
20 | "formatter"
21 | ],
22 | "engines": {
23 | "vscode": "^1.72.0"
24 | },
25 | "categories": [
26 | "Formatters"
27 | ],
28 | "activationEvents": [
29 | "onLanguage:markdown",
30 | "onLanguage:rmd",
31 | "onCommand:markdown-table-formatter.enableForCurrentScope",
32 | "onCommand:markdown-table-formatter.toggleDebug",
33 | "onCommand:markdown-table-formatter.moveColumnRight",
34 | "onCommand:markdown-table-formatter.moveColumnLeft",
35 | "workspaceContains:**/*.md",
36 | "workspaceContains:README.md"
37 | ],
38 | "main": "./out/extension.js",
39 | "contributes": {
40 | "commands": [
41 | {
42 | "command": "markdown-table-formatter.enableForCurrentScope",
43 | "category": "Markdown Table Formatter",
44 | "title": "Enable for current language"
45 | },
46 | {
47 | "command": "markdown-table-formatter.toggleDebug",
48 | "category": "Markdown Table Formatter",
49 | "title": "Toggle debug decorations"
50 | },
51 | {
52 | "command": "markdown-table-formatter.moveColumnRight",
53 | "category": "Markdown Table Formatter",
54 | "title": "Move column right"
55 | },
56 | {
57 | "command": "markdown-table-formatter.moveColumnLeft",
58 | "category": "Markdown Table Formatter",
59 | "title": "Move column left"
60 | },
61 | {
62 | "command": "markdown-table-formatter.sortTable",
63 | "category": "Markdown Table Formatter",
64 | "title": "Sort table based on cursor position"
65 | }
66 | ],
67 | "menus": {
68 | "editor/context": [
69 | {
70 | "command": "markdown-table-formatter.moveColumnLeft",
71 | "group": "markdown-table-formatter",
72 | "when": "config.markdown-table-formatter.enableSort === true"
73 | },
74 | {
75 | "command": "markdown-table-formatter.moveColumnRight",
76 | "group": "markdown-table-formatter",
77 | "when": "config.markdown-table-formatter.enableSort === true"
78 | },
79 | {
80 | "command": "markdown-table-formatter.sortTable",
81 | "group": "markdown-table-formatter",
82 | "when": "config.markdown-table-formatter.enableSort === true"
83 | }
84 | ]
85 | },
86 | "keybindings": [
87 | {
88 | "command": "markdown-table-formatter.enableForCurrentScope",
89 | "key": "alt+shift+e",
90 | "when": "editorTextFocus"
91 | },
92 | {
93 | "command": "markdown-table-formatter.moveColumnRight",
94 | "key": "ctrl+m right",
95 | "when": "editorTextFocus"
96 | },
97 | {
98 | "command": "markdown-table-formatter.moveColumnLeft",
99 | "key": "ctrl+m left",
100 | "when": "editorTextFocus"
101 | }
102 | ],
103 | "configuration": {
104 | "type": "object",
105 | "title": "Markdown Table Formatter",
106 | "properties": {
107 | "markdown-table-formatter.enable": {
108 | "order": 0,
109 | "description": "Enable or disable Markdown Table Formatter",
110 | "type": "boolean",
111 | "default": true
112 | },
113 | "markdown-table-formatter.enableSort": {
114 | "order": 1,
115 | "description": "Enable or disable Markdown Table Formatter Code Lenses for sorting tables",
116 | "type": "boolean",
117 | "default": true
118 | },
119 | "markdown-table-formatter.sortCaseInsensitive": {
120 | "description": "Sort table columns without considering text case",
121 | "type": "boolean",
122 | "default": true
123 | },
124 | "markdown-table-formatter.spacePadding": {
125 | "description": "How many spaces between left and right of each column content",
126 | "type": "integer",
127 | "default": 1
128 | },
129 | "markdown-table-formatter.keepFirstAndLastPipes": {
130 | "description": "Keep first and last pipes \"|\" in table formatting.",
131 | "type": "boolean",
132 | "default": true
133 | },
134 | "markdown-table-formatter.defaultTableJustification": {
135 | "description": "Defines the default justification for tables that have only a \"-\" or no colon on the formatting line",
136 | "type": "string",
137 | "enum": [
138 | "Left",
139 | "Center",
140 | "Right"
141 | ],
142 | "default": "Left"
143 | },
144 | "markdown-table-formatter.removeColonsIfSameAsDefault": {
145 | "description": "Remove colons from the format line if the justification is the same as default",
146 | "type": "boolean",
147 | "default": false
148 | },
149 | "markdown-table-formatter.markdownGrammarScopes": {
150 | "description": "File language grammar that will be considered Markdown by this package (comma-separated). \nRun \"Markdown Table Formatter: Enable For Current Scope\" command to add current editor grammar to this setting.",
151 | "type": "array",
152 | "items": {
153 | "type": "string"
154 | },
155 | "default": [
156 | "markdown"
157 | ]
158 | },
159 | "markdown-table-formatter.globalColumnSizes": {
160 | "description": "Calculates the column sizes based on all tables on the document.",
161 | "type": "string",
162 | "enum": [
163 | "Disabled",
164 | "Same Column Size",
165 | "Same Table Size"
166 | ],
167 | "default": "Disabled"
168 | },
169 | "markdown-table-formatter.delimiterRowPadding": {
170 | "description": "Changes how the delimiter row is presented.",
171 | "type": "string",
172 | "enum": [
173 | "None",
174 | "Follow Space Padding",
175 | "Single Space Always",
176 | "Alignment Marker"
177 | ],
178 | "default": "None"
179 | },
180 | "markdown-table-formatter.limitLastColumnLength": {
181 | "description": "Control how the last column size is calculated.",
182 | "type": "string",
183 | "enum": [
184 | "None",
185 | "Follow editor's wordWrapColumn",
186 | "Follow header row length"
187 | ],
188 | "enumDescriptions": [
189 | "Do not limit last column",
190 | "Do not extend last column to more than your editor's wordWrapColumn setting",
191 | "Do not extend last column to more than the table's header row"
192 | ],
193 | "default": "None"
194 | },
195 | "markdown-table-formatter.allowEmptyLines": {
196 | "description": "Format tables even if lines have less columns than header.",
197 | "type": "boolean",
198 | "default": true
199 | },
200 | "markdown-table-formatter.whichCodeLensesToShow": {
201 | "description": "Control what is shown on CodeLens.",
202 | "type": "array",
203 | "items": {
204 | "type": "string",
205 | "enum": [
206 | "Format",
207 | "Sort",
208 | "Re-Sort"
209 | ]
210 | },
211 | "default": [
212 | "Format",
213 | "Sort",
214 | "Re-Sort"
215 | ]
216 | }
217 | }
218 | }
219 | },
220 | "scripts": {
221 | "vscode:prepublish": "npm run -S esbuild-base -- --minify",
222 | "esbuild-base": "esbuild ./src/extension.ts --bundle --outfile=out/extension.js --external:vscode --format=cjs --platform=node",
223 | "esbuild": "npm run -S esbuild-base -- --sourcemap",
224 | "watch": "npm run -S esbuild-base -- --sourcemap --watch",
225 | "test-compile": "tsc -p ./",
226 | "lint": "eslint .",
227 | "test": "node ./out/test/runTest.js"
228 | },
229 | "dependencies": {
230 | "md5": "^2.3.0",
231 | "wcwidth": "^1.0.1",
232 | "xregexp": "^5.1.1"
233 | },
234 | "devDependencies": {
235 | "@types/glob": "^8.0.0",
236 | "@types/md5": "^2.3.2",
237 | "@types/mocha": "^10.0.0",
238 | "@types/node": "^16.11.64",
239 | "@types/vscode": "^1.72.0",
240 | "@types/wcwidth": "^1.0.0",
241 | "@typescript-eslint/eslint-plugin": "^5.39.0",
242 | "@typescript-eslint/parser": "^5.39.0",
243 | "@vscode/test-electron": "^2.1.5",
244 | "@vscode/vsce": "^2.20.1",
245 | "esbuild": "^0.15.18",
246 | "eslint": "^8.25.0",
247 | "mocha": "^10.0.0",
248 | "ts-loader": "^9.4.1",
249 | "typescript": "^4.8.4"
250 | }
251 | }
252 |
--------------------------------------------------------------------------------
/publish.ps1:
--------------------------------------------------------------------------------
1 | ./.venv/Scripts/python.exe .\publish.py $args[0]
--------------------------------------------------------------------------------
/publish.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """
3 | usage:
4 | ./publish [options]
5 |
6 | options:
7 | --run
8 | """
9 | import os
10 | import json
11 | import argparse
12 | import keepachangelog
13 | package = json.load(open("package.json"))
14 |
15 | options = {"M": "major", "I": "minor",
16 | "P": "patch", "G": "git push", "C": "cancel"}
17 |
18 | parser = argparse.ArgumentParser()
19 | parser.add_argument("--run", action="store_true")
20 |
21 | args = parser.parse_args()
22 |
23 | def parse_version(version):
24 | return version.split(".")
25 |
26 | data = keepachangelog.to_dict("CHANGELOG.md").keys()
27 |
28 | versions_list = list(data)
29 | versions_list.sort()
30 |
31 | latest_changelog_version = versions_list[-1]
32 |
33 | if not args.run:
34 | print("Running in DRY RUN mode")
35 |
36 | print("Current", package["name"], "package version:", package["version"], "\n")
37 | while (True):
38 | option = input(
39 | "Publish [m]ajor, m[i]nor, [p]atch, just push to [g]it, [C]ancel? ").upper()
40 | if option == "" or option == "C":
41 | exit(0)
42 | if option in options.keys():
43 | break
44 |
45 | echo = "echo " if not args.run else ""
46 | if option != "G":
47 | parsed_version = parse_version(package["version"])
48 | new_version = ""
49 | if option == "M":
50 | new_version = f"{int(parsed_version[0]) + 1}.0.0"
51 | elif option == "I":
52 | new_version = f"{int(parsed_version[0])}.{int(parsed_version[1]) + 1}.0"
53 | elif option == "P":
54 | new_version = f"{int(parsed_version[0])}.{int(parsed_version[1])}.{int(parsed_version[2]) + 1}"
55 |
56 | if new_version != latest_changelog_version:
57 | print("There isn't a changelog for this release. ABORTING")
58 | print(f"New version:\t\t{new_version}")
59 | print(f"Latest changelog:\t{latest_changelog_version}")
60 | exit(1)
61 | publish = input(
62 | f"New version will be: {new_version}, continue? [Y/n] ").upper()
63 | if publish == "N":
64 | exit(0)
65 | os.system(f"{echo}vsce publish {options[option]}")
66 | os.system(f"{echo}git push")
67 | os.system(f"{echo}git push --tags")
68 |
--------------------------------------------------------------------------------
/resources/icon-blend.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fcrespo82/vscode-markdown-table-formatter/073fe4868498fed1ed23ba4732b976aa7dfea2dc/resources/icon-blend.png
--------------------------------------------------------------------------------
/resources/icon.blend:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fcrespo82/vscode-markdown-table-formatter/073fe4868498fed1ed23ba4732b976aa7dfea2dc/resources/icon.blend
--------------------------------------------------------------------------------
/resources/icon.gvdesign:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fcrespo82/vscode-markdown-table-formatter/073fe4868498fed1ed23ba4732b976aa7dfea2dc/resources/icon.gvdesign
--------------------------------------------------------------------------------
/resources/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fcrespo82/vscode-markdown-table-formatter/073fe4868498fed1ed23ba4732b976aa7dfea2dc/resources/icon.png
--------------------------------------------------------------------------------
/src/MarkdownTable.ts:
--------------------------------------------------------------------------------
1 | import { Position, Range } from "vscode";
2 | import { addTailPipes, joinCells, splitCells, stripHeaderTailPipes } from "./formatter/MarkdownTableFormatterUtils";
3 | import { columnSizes } from "./MarkdownTableUtils";
4 | import { MarkdownTableSortDirection } from "./sorter/MarkdownTableSortDirection";
5 | import MarkdownTableSortOptions from "./sorter/MarkdownTableSortOptions";
6 | import md5 = require("md5");
7 | import XRegExp = require('xregexp');
8 | import { SortIndicator } from "./sorter/MTSortIndicator";
9 | import MarkdownTableFormatterSettings from "./formatter/MarkdownTableFormatter.types";
10 |
11 | export class MarkdownTable {
12 | private _id: string;
13 | private start: Position;
14 | private end: Position;
15 | readonly header!: string[];
16 | readonly ranges: Map = new Map();
17 | format: string[] = [];
18 | readonly body?: string[][] = [];
19 | readonly defaultBody: string[][] = [];
20 | readonly range: Range;
21 | readonly headerRange: Range;
22 | readonly formatRange: Range;
23 | private _columnSizes: number[] = [];
24 | private rawContainPipes = false
25 | private _isInList = false
26 | private _listIndentation: string[] = []
27 |
28 | get id(): string {
29 | return this._id;
30 | }
31 |
32 | get columns(): number {
33 | return this.header.length;
34 | }
35 |
36 | get bodyLines(): number {
37 | return this.body?.length || 0;
38 | }
39 |
40 | get totalLines(): number {
41 | return this.bodyLines + 2;
42 | }
43 |
44 | get columnSizes(): number[] {
45 | return this._columnSizes;
46 | }
47 | set columnSizes(value: number[]) {
48 | this._columnSizes = value;
49 | }
50 |
51 | get startLine(): number {
52 | return this.start.line;
53 | }
54 |
55 | get isInList(): boolean {
56 | return this._isInList;
57 | }
58 |
59 | get listIndentation(): string[] {
60 | return this._listIndentation;
61 | }
62 |
63 | constructor(start: Position, end: Position, regexpArray: XRegExp.ExecArray, config: MarkdownTableFormatterSettings) {
64 | this.start = start;
65 | this.end = end;
66 |
67 | this.range = new Range(this.start, this.end);
68 |
69 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
70 | const groups = regexpArray.groups!
71 |
72 | if (groups.body) {
73 | this.rawContainPipes = [groups.header, groups.format, ...groups.body?.split('\n').filter(x => { return x.trim().length > 0 })].every(v => {
74 | return v.search("^\\s*\\|") >= 0 && v.search("\\|\\s*\\r?\\n?$") > 0;
75 | });
76 | } else {
77 | this.rawContainPipes = [groups.header, groups.format].every(v => {
78 | return v.search("^\\s*\\|") >= 0 && v.search("\\|\\s*\\r?\\n?$") > 0;
79 | });
80 | }
81 |
82 | this.headerRange = new Range(this.start, new Position(this.start.line, groups.header.length));
83 |
84 | let firstLine = this.start.line;
85 | if (groups.header) {
86 | this.header = splitCells(stripHeaderTailPipes(groups.header));
87 | this.header = this.header.map(x => { return x.replace('\n', '') });
88 | // this.header = this.header.filter(x => { return x.trim().length > 0 })
89 | this.header.forEach((header, index) => {
90 | const length = header.length;
91 | const start = groups.header.indexOf(header);
92 | if (!this.ranges.has(index)) {
93 | this.ranges.set(index, []);
94 | }
95 | this.ranges.get(index)?.push(new Range(new Position(firstLine, start), new Position(firstLine, start + length)));
96 | });
97 | firstLine += 1;
98 | }
99 |
100 | this.format = splitCells(stripHeaderTailPipes(groups.format));
101 | this.format = this.format.map(x => { return x.replace('\n', '') });
102 | this.formatRange = new Range(this.start.with(this.start.line + 1), new Position(this.start.line + 1, groups.format.length));
103 |
104 | firstLine += 1;
105 |
106 | if (groups.body) {
107 | this.body = groups.body.replace(/^\r?\n+|\r?\n+$/g, '').split(/\r?\n/).map((lineBody: string) => {
108 | let result = splitCells(stripHeaderTailPipes(lineBody));
109 | result = result.map(x => { return x.replace('\n', '') });
110 | return result
111 | });
112 | this.body.forEach((line: string[], line_index) => {
113 | line.forEach((h, index) => {
114 | const length = h.length;
115 | const start = groups.body.split(/\r?\n/)[line_index].indexOf(h);
116 | if (!this.ranges.has(index)) {
117 | this.ranges.set(index, []);
118 | }
119 | this.ranges.get(index)?.push(new Range(new Position(firstLine, start), new Position(firstLine, start + length)));
120 | });
121 | firstLine += 1;
122 | });
123 | this._columnSizes = columnSizes(config, this.header, this.body);
124 | } else {
125 | this._columnSizes = columnSizes(config, this.header);
126 | }
127 |
128 | this._id = md5(this.startLine.toString());
129 |
130 | if (groups.inlist !== undefined) {
131 | this._isInList = true
132 | this._listIndentation[0] = groups.inlist
133 | for (let index = 1; index < this.totalLines; index++) {
134 | this._listIndentation.push(" ".repeat(groups.inlist.length))
135 | }
136 | } else if (groups.indentation !== undefined) {
137 | this._isInList = true
138 | for (let index = 0; index < this.totalLines; index++) {
139 | this._listIndentation.push(groups.indentation)
140 | }
141 | }
142 | }
143 |
144 | sortedByColumn = (): MarkdownTableSortOptions => {
145 | const mapped = this.header.map((v, i) => {
146 | let ind = undefined
147 | ind = v.indexOf(SortIndicator.ascending) >= 0 ? MarkdownTableSortDirection.Asc : ind
148 | ind = v.indexOf(SortIndicator.descending) >= 0 ? MarkdownTableSortDirection.Desc : ind
149 | return (ind !== undefined) ? { header_index: i, sort_direction: ind } : { header_index: -1, sort_direction: ind };
150 | })
151 | const filtered = mapped.filter((v) => {
152 | return v.header_index >= 0
153 | })
154 | return filtered[0];
155 | }
156 |
157 | updateSizes = (config: MarkdownTableFormatterSettings): void => {
158 | this._columnSizes = columnSizes(config, this.header, this.body);
159 | }
160 |
161 | notFormatted = (): string => {
162 | const addTailPipesIfNeeded = this.rawContainPipes ? addTailPipes : (x: string) => x;
163 | let joined = [this.format, ...this.body!].map(joinCells).map(addTailPipesIfNeeded);
164 | if (this.header) {
165 | joined = [this.header, this.format, ...this.body!].map(joinCells).map(addTailPipesIfNeeded);
166 | }
167 |
168 | if (this.isInList) {
169 | for (let index = 0; index < joined.length; index++) {
170 | joined[index] = this.listIndentation[index] + joined[index]
171 | }
172 | }
173 |
174 | return joined.join('\n');
175 | };
176 |
177 | }
178 |
179 |
--------------------------------------------------------------------------------
/src/MarkdownTableRegex.ts:
--------------------------------------------------------------------------------
1 | import XRegExp = require('xregexp');
2 | XRegExp.install("namespacing");
3 |
4 | export const tableRegex = XRegExp(String.raw`
5 | (?:
6 | (?(?:[-+*\.]+|[0-9]+[ ]?[-\)\.])[ ]*)
7 | |
8 | (?[ ]+)
9 | )?
10 | (?
11 | (?:[^\n]*\|[^\n]*)
12 | )\n
13 | (?:[ ]*?
14 | (?
15 | (?:[ :\t-]*\|[ :\t-]*)+
16 | )\r?\n?
17 | )$\r?\n?
18 | (?
19 | (?:
20 | (?:^[ ]*
21 | (?:[^\n]*\|[^\n]*)+
22 | )[\n|$]?
23 | )*
24 | )
25 | `,
26 | 'gmx',
27 | );
--------------------------------------------------------------------------------
/src/MarkdownTableUtils.ts:
--------------------------------------------------------------------------------
1 | import { Range, TextDocument, workspace } from 'vscode';
2 | import { MarkdownTable } from './MarkdownTable';
3 | import { tableRegex } from './MarkdownTableRegex';
4 | import wcswidth = require('wcwidth');
5 | import XRegExp = require('xregexp');
6 | import MarkdownTableFormatterSettings, { MarkdownTableFormatterLimitLastRowLength } from './formatter/MarkdownTableFormatter.types';
7 |
8 | export const stringWidth = (str: string): number => {
9 | // zero-width Unicode characters that we should ignore for purposes of computing string "display" width
10 | const zwcrx = /[\u200B-\u200D\uFEFF\u00AD]/g;
11 | const match = str.match(zwcrx);
12 | return wcswidth(str) - (match ? match.length : 0);
13 | };
14 |
15 | export const padding = (len: number, str = ' '): string => {
16 | const r = len >= 0 ? str.repeat(len) : "";
17 | return r;
18 | };
19 |
20 | export const columnSizes = (config: MarkdownTableFormatterSettings, header: string[], body: string[][] = [[]]): number[] => {
21 | const columnSizes = [header, ...body].map((line) => {
22 | return line.map((column) => {
23 | return stringWidth(column.trim());
24 | });
25 | }).reduce((previous, current) => {
26 | return previous.map((column, index) => {
27 | if (column <= current[index]) {
28 | return current[index];
29 | }
30 | return column;
31 | });
32 | });
33 |
34 | const preferredLineLength = workspace.getConfiguration('editor').get('wordWrapColumn');
35 | const limitLastColumnLength = config.limitLastColumnLength
36 | const padding = config.spacePadding
37 | const keepFirstAndLast = config.keepFirstAndLastPipes
38 | const otherColumnsSum = columnSizes.length === 1 ? 0 : sumArray(columnSizes.slice(0, -1));
39 | const dividers = keepFirstAndLast ? columnSizes.length + 1 : columnSizes.length - 1
40 | const allPadding = columnSizes.length * 2 * padding!
41 |
42 | switch (limitLastColumnLength) {
43 | case MarkdownTableFormatterLimitLastRowLength.EditorWordWrap:
44 | if ((columnSizes.reduce((x, y) => x + y) + dividers + allPadding) > preferredLineLength) {
45 | columnSizes[columnSizes.length - 1] = Math.max(
46 | preferredLineLength - (otherColumnsSum + dividers + allPadding),
47 | 3,
48 | );
49 | }
50 | break;
51 | case MarkdownTableFormatterLimitLastRowLength.HeaderRowLength:
52 | const headerLength = header.map((column) => {
53 | return stringWidth(column.trim());
54 | })
55 | columnSizes[columnSizes.length - 1] = headerLength[columnSizes.length - 1]
56 | break;
57 | case MarkdownTableFormatterLimitLastRowLength.None:
58 | break;
59 | default:
60 | break;
61 | }
62 |
63 | return columnSizes
64 | };
65 |
66 | export const sumArray = (array: number[]): number => {
67 | return array.reduce((p, c) => p + c);
68 | };
69 |
70 | export const discoverMaxColumnSizes = (tables: MarkdownTable[]): number[] => {
71 | return tables.map(table => {
72 | return table.columnSizes;
73 | }).reduce((p, c) => {
74 | const length = p.length > c.length ? p.length : c.length;
75 | const isPreviousBigger = p.length > c.length;
76 | const columnsSizes = p.length > c.length ? p : c;
77 | for (let index = 0; index < length; index++) {
78 | if (isPreviousBigger) {
79 | if (c[index] > p[index]) {
80 | columnsSizes[index] = c[index];
81 | }
82 | } else {
83 | if (p[index] > c[index]) {
84 | columnsSizes[index] = p[index];
85 | }
86 | }
87 | }
88 | return columnsSizes;
89 | });
90 | };
91 |
92 | export const discoverMaxTableSizes = (tables: MarkdownTable[], padding: number): number[][] => {
93 | const tableInfo = tables.map(table => {
94 | return { columnSizes: table.columnSizes, columns: table.columns };
95 | });
96 |
97 | const maxTableSize = tableInfo.reduce((p, c) => {
98 | return sumArray(p.columnSizes) + (p.columns * padding) > sumArray(c.columnSizes) + (c.columns * padding) ? p : c;
99 | });
100 |
101 | return tableInfo.map(info => {
102 | const totalCharsMaxTable = sumArray(maxTableSize.columnSizes) + (maxTableSize.columns * padding * 2) + (maxTableSize.columns + 1);
103 | const totalCharsCurrentTable = sumArray(info.columnSizes) + (info.columns * padding * 2) + (info.columns + 1);
104 | let missingAdjustment = Math.floor(totalCharsMaxTable - totalCharsCurrentTable);
105 | const remainder = missingAdjustment % info.columns;
106 | if (sumArray(info.columnSizes) !== sumArray(maxTableSize.columnSizes)) {
107 |
108 | for (; missingAdjustment > 0;) {
109 | info.columnSizes.forEach((size, i) => {
110 | if (missingAdjustment > 0) {
111 | info.columnSizes[i] += 1;
112 | }
113 | missingAdjustment--;
114 | });
115 | }
116 | if (sumArray(info.columnSizes) + (info.columns * padding * 2) + (info.columns + 1) < totalCharsMaxTable) {
117 | const rev = info.columnSizes.reverse();
118 | rev[0] += remainder;
119 | info.columnSizes = rev.reverse();
120 | }
121 | }
122 | return info.columnSizes;
123 | });
124 | };
125 |
126 | export const pad = (text: string, columns: number): string => {
127 | return (' '.repeat(columns) + text).slice(-columns);
128 | };
129 |
130 | export const tablesIn = (config: MarkdownTableFormatterSettings, document: TextDocument, range?: Range): MarkdownTable[] => {
131 | if (!range) {
132 | range = new Range(0, 0, document.lineCount + 1, 0);
133 | }
134 | range = document.validateRange(range);
135 | const tables: MarkdownTable[] = [];
136 |
137 | const tableRawText = document.getText(range);
138 | let position = 0;
139 | let match;
140 | while ((match = XRegExp.exec(tableRawText, tableRegex, position, false))) {
141 | position = match.index + match[0].length;
142 | const offset = document.offsetAt(range.start);
143 | const start = document.positionAt(offset + match.index);
144 | const length = match[0].replace(/^\n+|\n+$/g, '').length;
145 | const end = document.positionAt(offset + match.index + length);
146 | const table = new MarkdownTable(start, end, match, config);
147 | tables.push(table);
148 | }
149 | return tables;
150 | };
151 |
152 | /**
153 | * Check if a language is enabled in config.
154 | * @param languageId The language id to check.
155 | * @param config The config to check.
156 | */
157 | export const checkLanguage = (languageId: string, config: MarkdownTableFormatterSettings): boolean => {
158 | return config.markdownGrammarScopes!.includes(languageId)
159 | }
--------------------------------------------------------------------------------
/src/decoration/MarkdownTableDecorationProvider.ts:
--------------------------------------------------------------------------------
1 | import * as vscode from 'vscode';
2 | import MarkdownTableFormatterSettings from '../formatter/MarkdownTableFormatter.types';
3 | import {checkLanguage, tablesIn} from '../MarkdownTableUtils';
4 |
5 | export class MarkdownTableDecorationProvider implements vscode.Disposable {
6 |
7 | private disposables: vscode.Disposable[] = [];
8 |
9 | private decorationsEnabled = false;
10 |
11 | private decorations: vscode.DecorationOptions[] = [];
12 |
13 | private decorationType = vscode.window.createTextEditorDecorationType({
14 | backgroundColor: 'grey',
15 | rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed,
16 | overviewRulerColor: 'grey',
17 | overviewRulerLane: vscode.OverviewRulerLane.Full
18 | });
19 |
20 | private config: MarkdownTableFormatterSettings
21 |
22 | constructor(config: MarkdownTableFormatterSettings) {
23 | this.config = config;
24 | }
25 |
26 | dispose(): void {
27 | this.disposables.forEach(d => d.dispose());
28 | this.disposables = [];
29 | }
30 |
31 | public register(): void {
32 | this.disposables.push(
33 | vscode.commands.registerTextEditorCommand("markdown-table-formatter.toggleDebug", this.toggleDebug, this)
34 | );
35 | this.disposables.push(
36 | vscode.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this)
37 | );
38 | }
39 |
40 | private onDidChangeTextDocument(event: vscode.TextDocumentChangeEvent): void {
41 | if (!checkLanguage(event.document.languageId, this.config)) { return }
42 | const editor = vscode.window.activeTextEditor;
43 | if (editor != null) {
44 | this.addDecorations(editor);
45 | }
46 | }
47 |
48 | private createDecorations(document: vscode.TextDocument): vscode.DecorationOptions[] {
49 | const tables = tablesIn(this.config, document);
50 | const fullDecoration: vscode.DecorationOptions[] = tables.map(t => {
51 | return {
52 | range: t.range,
53 | hoverMessage: `ID: ${t.id}`,
54 | renderOptions: {}
55 | };
56 | });
57 | const headerDecoration: vscode.DecorationOptions[] = tables.map(t => {
58 | return {
59 | range: t.headerRange,
60 | renderOptions: {
61 | after: { contentText: ` ID: ${t.id}` }
62 | }
63 | };
64 | });
65 | return fullDecoration.concat(headerDecoration);
66 | }
67 |
68 | private addDecorations(editor: vscode.TextEditor) {
69 | if (!checkLanguage(editor.document.languageId, this.config)) { return }
70 | this.cleanDecorations(editor);
71 | if (this.decorationsEnabled) {
72 | this.decorations = this.createDecorations(editor.document);
73 | editor?.setDecorations(this.decorationType, this.decorations);
74 | }
75 | }
76 |
77 | private cleanDecorations(editor?: vscode.TextEditor) {
78 | editor?.setDecorations(this.decorationType, []);
79 | }
80 |
81 | private toggleDebug(editor: vscode.TextEditor) {
82 | if (!checkLanguage(editor.document.languageId, this.config)) { return }
83 | this.decorationsEnabled = !this.decorationsEnabled;
84 | this.addDecorations(editor);
85 | }
86 | }
--------------------------------------------------------------------------------
/src/extension.ts:
--------------------------------------------------------------------------------
1 | import * as vscode from 'vscode';
2 | import {MarkdownTableDecorationProvider} from './decoration/MarkdownTableDecorationProvider';
3 | import {MarkdownTableFormatterProvider} from './formatter/MarkdownTableFormatterProvider';
4 | import MarkdownTableFormatterSettingsImpl from './formatter/MarkdownTableFormatterSettingsImpl';
5 | import {MarkdownTableSortCodeLensProvider} from "./sorter/MarkdownTableSortCodeLensProvider";
6 |
7 | export async function activate(context: vscode.ExtensionContext): Promise {
8 | const config = MarkdownTableFormatterSettingsImpl.shared;
9 |
10 | const markdownTableFormatterProvider = new MarkdownTableFormatterProvider(config);
11 | const markdownTableCodeLensProvider = new MarkdownTableSortCodeLensProvider(config);
12 | const markdownTableDecorationProvider = new MarkdownTableDecorationProvider(config);
13 |
14 | context.subscriptions.push(markdownTableFormatterProvider);
15 | context.subscriptions.push(markdownTableCodeLensProvider);
16 | context.subscriptions.push(markdownTableDecorationProvider);
17 |
18 | markdownTableFormatterProvider.register();
19 | markdownTableCodeLensProvider.register();
20 | markdownTableDecorationProvider.register();
21 |
22 | vscode.workspace.onDidChangeConfiguration(changeConfigurationEvent => {
23 | if (changeConfigurationEvent.affectsConfiguration('markdown-table-formatter.enable') ||
24 | changeConfigurationEvent.affectsConfiguration('markdown-table-formatter.markdownGrammarScopes')) {
25 | if (config.enable) {
26 | markdownTableFormatterProvider.dispose();
27 | markdownTableFormatterProvider.register();
28 | markdownTableDecorationProvider.dispose();
29 | markdownTableDecorationProvider.register();
30 | } else {
31 | markdownTableFormatterProvider.dispose();
32 | markdownTableDecorationProvider.dispose();
33 | }
34 | }
35 | if (changeConfigurationEvent.affectsConfiguration('markdown-table-formatter.enableSort') ||
36 | changeConfigurationEvent.affectsConfiguration('markdown-table-formatter.markdownGrammarScopes')) {
37 | if (config.enableSort) {
38 | markdownTableCodeLensProvider.dispose();
39 | markdownTableCodeLensProvider.register();
40 | } else {
41 | markdownTableCodeLensProvider.dispose();
42 | }
43 | }
44 | });
45 |
46 | return Promise.resolve(true);
47 | }
48 |
49 | export async function deactivate(): Promise {
50 | return Promise.resolve(true);
51 | }
--------------------------------------------------------------------------------
/src/formatter/MarkdownTableFormatter.types.ts:
--------------------------------------------------------------------------------
1 | export enum MarkdownTableFormatterDelimiterRowPadding {
2 | None = "None",
3 | FollowSpacePadding = "Follow Space Padding",
4 | SingleApaceAlways = "Single Space Always",
5 | AlignmentMarker = "Alignment Marker"
6 | }
7 | export enum MarkdownTableFormatterLimitLastRowLength {
8 | None = "None",
9 | EditorWordWrap = "Follow editor's wordWrapColumn",
10 | HeaderRowLength = "Follow header row length"
11 | }
12 | export enum MarkdownTableFormatterGlobalColumnSizes {
13 | Disabled = "Disabled",
14 | SameColumnSize = "Same Column Size",
15 | SameTableSize = "Same Table Size"
16 | }
17 |
18 | export enum MarkdownTableFormatterDefaultTableJustification {
19 | Left = "Left",
20 | Right = "Right",
21 | Center = "Center"
22 | }
23 |
24 | export enum MarkdownTableFormatterWhichCodeLensesToShow {
25 | Format = "Format",
26 | Sort = "Sort",
27 | ReSort = "Re-Sort"
28 | }
29 |
30 | export default interface MarkdownTableFormatterSettings {
31 | enable?: boolean;
32 | enableSort?: boolean;
33 | sortCaseInsensitive?: boolean;
34 | spacePadding?: number;
35 | keepFirstAndLastPipes?: boolean;
36 | defaultTableJustification?: MarkdownTableFormatterDefaultTableJustification;
37 | removeColonsIfSameAsDefault?: boolean;
38 | markdownGrammarScopes?: string[];
39 | globalColumnSizes?: MarkdownTableFormatterGlobalColumnSizes;
40 | delimiterRowPadding?: MarkdownTableFormatterDelimiterRowPadding;
41 | limitLastColumnLength?: MarkdownTableFormatterLimitLastRowLength;
42 | allowEmptyRows?: boolean;
43 | whichCodeLensesToShow?: MarkdownTableFormatterWhichCodeLensesToShow[];
44 | }
45 |
--------------------------------------------------------------------------------
/src/formatter/MarkdownTableFormatterProvider.ts:
--------------------------------------------------------------------------------
1 | import * as vscode from 'vscode';
2 | import {MarkdownTable} from '../MarkdownTable';
3 | import {checkLanguage, discoverMaxColumnSizes, discoverMaxTableSizes, padding, stringWidth, tablesIn} from '../MarkdownTableUtils';
4 | import {getActiveSort, setActiveSort} from '../sorter/MarkdownTableSortUtils';
5 | import MarkdownTableFormatterSettings, {MarkdownTableFormatterDelimiterRowPadding, MarkdownTableFormatterGlobalColumnSizes} from './MarkdownTableFormatter.types';
6 | import MarkdownTableFormatterSettingsImpl from './MarkdownTableFormatterSettingsImpl';
7 | import {addTailPipes, fixJustification, getColumnIndexFromRange, joinCells, tableJustification} from './MarkdownTableFormatterUtils';
8 | import MarkdownTableSortCommandArguments from '../sorter/MarkdownTableSortCommandArguments';
9 |
10 | export class MarkdownTableFormatterProvider implements vscode.DocumentFormattingEditProvider, vscode.DocumentRangeFormattingEditProvider, vscode.Disposable {
11 |
12 | private disposables: vscode.Disposable[] = [];
13 |
14 | private config: MarkdownTableFormatterSettings
15 |
16 | constructor(config: MarkdownTableFormatterSettings) {
17 | this.config = config;
18 | }
19 |
20 | dispose(): void {
21 | this.disposables.forEach(d => d.dispose());
22 | this.disposables = [];
23 | }
24 |
25 | public setConfig(config: MarkdownTableFormatterSettings): void {
26 | this.config = config
27 | }
28 |
29 | public register(): void {
30 | if (!this.config) {
31 | this.config = MarkdownTableFormatterSettingsImpl.shared;
32 | }
33 | if (this.config.enable) {
34 | this.config.markdownGrammarScopes?.forEach((scope) => {
35 | this.registerFormatterForScope(scope);
36 | })
37 |
38 | this.disposables.push(vscode.commands.registerTextEditorCommand("markdown-table-formatter.formatTable", this.formatTableCommand, this));
39 | this.disposables.push(vscode.commands.registerTextEditorCommand("markdown-table-formatter.enableForCurrentScope", this.enableForCurrentScopeCommand, this));
40 | this.disposables.push(vscode.commands.registerTextEditorCommand("markdown-table-formatter.moveColumnRight", this.moveColumnRightCommand, this));
41 | this.disposables.push(vscode.commands.registerTextEditorCommand("markdown-table-formatter.moveColumnLeft", this.moveColumnLeftCommand, this));
42 | }
43 | }
44 |
45 | private flipColumn(table: MarkdownTable, leftIndex: number, rightIndex: number): MarkdownTable {
46 | if (table.header) {
47 | const header = table.header[rightIndex];
48 | table.header[rightIndex] = table.header[leftIndex];
49 | table.header[leftIndex] = header;
50 | }
51 |
52 | const format = table.format[rightIndex];
53 | table.format[rightIndex] = table.format[leftIndex];
54 | table.format[leftIndex] = format;
55 |
56 | table.body?.forEach((_, i) => {
57 | const body = table.body![i][rightIndex];
58 | table.body![i][rightIndex] = table.body![i][leftIndex];
59 | table.body![i][leftIndex] = body;
60 | });
61 | return table;
62 | }
63 |
64 | /**
65 | * Extract `edits` from the `range` of the `document` to format the tables
66 | * @param document Document to format
67 | * @param range Range of the document do format
68 | * @returns `TextEdit[]` of edits ({@link vscode.TextEdit})
69 | */
70 | public formatDocument(document: vscode.TextDocument, range: vscode.Range): vscode.TextEdit[] {
71 | const edits: vscode.TextEdit[] = [];
72 | // This check is in case some grammar is removed and VSCode is not reloaded yet
73 | if (!checkLanguage(document.languageId, this.config)) {
74 | vscode.window.showWarningMessage(`Markdown table formatter is not enabled for '${document.languageId}' language!`);
75 | return edits;
76 | }
77 | let tables: MarkdownTable[] = tablesIn(this.config, document, range);
78 |
79 | tables = tables.filter(table => this.checkColumnsPerLine(table))
80 |
81 | // Fix sizes of empty row tables
82 | tables.forEach(table => {
83 | if (table.body) {
84 | table.body?.forEach((line, i) => {
85 | if (table.header.length !== line.length) {
86 | if (this.config.allowEmptyRows) {
87 | if (table.header.length > line.length) {
88 | const lineFixed = line.concat(Array(table.header.length - line.length).fill(""))
89 | table.body![i] = lineFixed
90 | } else if (line.length > table.header.length) {
91 | const lineFixed = line.slice(0, table.header.length)
92 | table.body![i] = lineFixed
93 | }
94 | }
95 | }
96 | });
97 | }
98 | if (table.header.length !== table.format.length) {
99 | if (this.config.allowEmptyRows) {
100 | table.format = table.format.concat(Array(table.header.length - table.format.length).fill("-"))
101 | }
102 | }
103 |
104 | table.updateSizes(this.config);
105 | });
106 |
107 | if (this.config.globalColumnSizes === MarkdownTableFormatterGlobalColumnSizes.SameColumnSize) {
108 | if (tables.length > 0) {
109 | const maxSize = discoverMaxColumnSizes(tables);
110 | tables.forEach(table => {
111 | table.columnSizes = maxSize;
112 | });
113 | }
114 | }
115 | if (this.config.globalColumnSizes === MarkdownTableFormatterGlobalColumnSizes.SameTableSize) {
116 | const tableSizes = discoverMaxTableSizes(tables, this.config.spacePadding!);
117 | tables.forEach((table, i) => {
118 | table.columnSizes = tableSizes[i];
119 | });
120 | }
121 | tables.forEach(table => {
122 | edits.push(vscode.TextEdit.replace(table.range, this.formatTable(table, this.config)));
123 | });
124 | return edits;
125 | }
126 |
127 | private registerFormatterForScope(scope: vscode.DocumentSelector) {
128 | this.disposables.push(vscode.languages.registerDocumentFormattingEditProvider(scope, this));
129 | this.disposables.push(vscode.languages.registerDocumentRangeFormattingEditProvider(scope, this));
130 | }
131 |
132 | private formatLine(line: string[], format: string[], size: number[], settings: MarkdownTableFormatterSettings) {
133 | line = line.map((column, index) => {
134 | const columnSize = size[index];
135 | const columnJustification = format[index];
136 | const text = this.justify(column, columnJustification, columnSize, settings);
137 | return text;
138 | });
139 | return line;
140 | }
141 |
142 | private formatLines(lines: string[][], format: string[], size: number[], settings: MarkdownTableFormatterSettings) {
143 | lines = lines.map(line => {
144 | return this.formatLine(line, format, size, settings);
145 | });
146 | return lines;
147 | }
148 |
149 | private justify(text: string, justification: string, length: number, settings: MarkdownTableFormatterSettings) {
150 | text = text.trim();
151 | length = Math.max(length - stringWidth(text), 0);
152 | let justifySwitch = fixJustification(justification);
153 | if (justifySwitch === "--") {
154 | justifySwitch = tableJustification[settings.defaultTableJustification!];
155 | }
156 | switch (justifySwitch) {
157 | case '::':
158 | return padding(length / 2) + text + padding((length + 1) / 2);
159 | case '-:':
160 | return padding(length) + text;
161 | case ':-':
162 | return text + padding(length);
163 | default:
164 | throw new Error(`Unknown column justification ${justifySwitch}`);
165 | }
166 | }
167 |
168 | private formatTable(table: MarkdownTable, settings: MarkdownTableFormatterSettings): string {
169 | const addTailPipesIfNeeded = settings.keepFirstAndLastPipes
170 | ? addTailPipes
171 | : (x: string) => x;
172 |
173 | const header = this.formatLines([table.header], table.format, table.columnSizes, settings).map(line => {
174 | const cellPadding = padding(settings.spacePadding!);
175 | return line.map((cell) => {
176 | return `${cellPadding}${cell}${cellPadding}`;
177 | });
178 | }).map(joinCells).map(addTailPipesIfNeeded);
179 |
180 |
181 | const formatLine = this.formatLines([table.format], table.format, table.columnSizes, settings).map(line => {
182 | return line.map((cell, i) => {
183 | let line = "";
184 | let [front, back] = fixJustification(cell);
185 | if (settings.removeColonsIfSameAsDefault && (fixJustification(cell) === tableJustification[settings.defaultTableJustification!])) {
186 | front = back = '-';
187 | }
188 |
189 | const spacePadding = padding(settings.spacePadding!, ' ');
190 | switch (settings.delimiterRowPadding) {
191 | case MarkdownTableFormatterDelimiterRowPadding.None:
192 | line = front + padding(table.columnSizes[i] + (settings.spacePadding! * 2) - 2, '-') + back;
193 | break;
194 | case MarkdownTableFormatterDelimiterRowPadding.FollowSpacePadding:
195 | line = `${spacePadding}${front}${padding(table.columnSizes[i] - 2, '-')}${table.columnSizes[i] === 1 ? '' : back}${spacePadding}`;
196 | break;
197 | case MarkdownTableFormatterDelimiterRowPadding.SingleApaceAlways:
198 | line = ` ${front}${padding(table.columnSizes[i] + (settings.spacePadding! * 2) - 4, '-')}${back} `;
199 | break;
200 | case MarkdownTableFormatterDelimiterRowPadding.AlignmentMarker: {
201 | let justifySwitch = fixJustification(cell);
202 | if (justifySwitch === "--") {
203 | justifySwitch = tableJustification[settings.defaultTableJustification!];
204 | }
205 | switch (justifySwitch) {
206 | case '::':
207 | line = `${spacePadding}${front}${padding(table.columnSizes[i] - 2, '-')}${back}${spacePadding}`;
208 | break;
209 | case '-:':
210 | line = `${spacePadding}${front}${padding(table.columnSizes[i] - 2 + settings.spacePadding!, '-')}${back}`;
211 | break;
212 | case ':-':
213 | line = `${front}${padding(table.columnSizes[i] - 2 + settings.spacePadding!, '-')}${back}${spacePadding}`;
214 | break;
215 | }
216 | break;
217 | }
218 | }
219 |
220 | return line;
221 | });
222 | }).map(joinCells).map(addTailPipesIfNeeded);
223 |
224 | const body = this.formatLines(table.body || [[]], table.format, table.columnSizes, settings).map(line => {
225 | const cellPadding = padding(settings.spacePadding!);
226 | return line.map((cell) => {
227 | return `${cellPadding}${cell}${cellPadding}`;
228 | });
229 | }).map(joinCells).map(addTailPipesIfNeeded);
230 |
231 | const formatted = [header, formatLine, ...body]
232 |
233 | if (table.isInList) {
234 | for (let index = 0; index < formatted.length; index++) {
235 | formatted[index] = table.listIndentation[index] + formatted[index]
236 | }
237 | }
238 |
239 | return formatted.join('\n');
240 | }
241 |
242 | private formatTableCommand(textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit, args?: MarkdownTableSortCommandArguments): void {
243 | if (args?.markdownTableFormatterArguments) {
244 | const table = args?.markdownTableFormatterArguments.table;
245 | edit.replace(table.range, this.formatTable(table, this.config))
246 | }
247 | }
248 |
249 | private checkColumnsPerLine(table: MarkdownTable): boolean {
250 | if (table.header.length !== table.format.length) {
251 | vscode.window.showErrorMessage(`Table at line ${table.startLine + 1} has a line with different column number as the header.`, // - Header columns: ${table.header.length} - Format line columns: ${table.format.length}`,
252 | "Focus"
253 | ).then(choice => {
254 | if (choice === "Focus") {
255 | vscode.window.activeTextEditor?.revealRange(table.range)
256 | const s = new vscode.Selection(table.startLine + 1, 0, table.startLine + 2, 0)
257 | vscode.window.activeTextEditor!.selection = s
258 | }
259 | })
260 | return false
261 | }
262 | return true
263 | }
264 |
265 | // vscode.Commands
266 | private moveColumnRightCommand(editor: vscode.TextEditor, edit: vscode.TextEditorEdit) {
267 | if (!checkLanguage(editor.document.languageId, this.config)) { return }
268 | const tables = tablesIn(this.config, editor.document)
269 | const tableSelected = tables.find(t => {
270 | return t.range.contains(editor.selection);
271 | })
272 | if (!tableSelected) { return }
273 |
274 | const header = getColumnIndexFromRange(tableSelected, editor.selection);
275 | if (header < 0) {
276 | return;
277 | }
278 | const leftHeaderIndex = header;
279 | if ((leftHeaderIndex + 1) >= tableSelected.columns) {
280 | return;
281 | }
282 | const rightHeaderIndex = header + 1;
283 | const table = this.flipColumn(tableSelected, leftHeaderIndex, rightHeaderIndex);
284 |
285 | const active_sort = getActiveSort(editor.document, table.id)
286 | setActiveSort(editor.document, table.id, active_sort?.header_index === header ? rightHeaderIndex : leftHeaderIndex, active_sort?.sort_direction)
287 |
288 | edit.replace(table.range, table.notFormatted());
289 | }
290 |
291 | // vscode.Commands
292 | private enableForCurrentScopeCommand = (editor: vscode.TextEditor) => {
293 | const scopes = this.config.markdownGrammarScopes;
294 | if (!scopes?.includes(editor.document.languageId)) {
295 | scopes?.push(editor.document.languageId);
296 | vscode.workspace.getConfiguration('markdown-table-formatter').update("markdownGrammarScopes", scopes, true);
297 | this.registerFormatterForScope(editor.document.languageId);
298 | vscode.window.showInformationMessage(`Markdown table formatter enabled for '${editor.document.languageId}' language!`);
299 | }
300 | }
301 |
302 | private moveColumnLeftCommand(editor: vscode.TextEditor, edit: vscode.TextEditorEdit) {
303 | if (!checkLanguage(editor.document.languageId, this.config)) { return }
304 | const tables = tablesIn(this.config, editor.document)
305 | const tableSelected = tables.find(t => {
306 | return t.range.contains(editor.selection);
307 | })
308 | if (!tableSelected) { return }
309 |
310 | const header = getColumnIndexFromRange(tableSelected, editor.selection);
311 | if (header < 0) {
312 | return;
313 | }
314 | const leftHeaderIndex = header - 1;
315 | if (leftHeaderIndex < 0) {
316 | return;
317 | }
318 | const rightHeaderIndex = header;
319 | const table = this.flipColumn(tableSelected, leftHeaderIndex, rightHeaderIndex);
320 |
321 | const active_sort = getActiveSort(editor.document, table.id)
322 | setActiveSort(editor.document, table.id, active_sort?.header_index === header ? leftHeaderIndex : rightHeaderIndex, active_sort?.sort_direction)
323 |
324 | edit.replace(table.range, table.notFormatted());
325 | }
326 |
327 | // vscode.DocumentFormattingEditProvider implementation
328 | provideDocumentFormattingEdits(document: vscode.TextDocument): vscode.ProviderResult {
329 | const fullDocumentRange = new vscode.Range(0, 0, document.lineCount + 1, 0);
330 | const edits = this.formatDocument(document, fullDocumentRange);
331 | return edits;
332 | }
333 |
334 | // vscode.DocumentRangeFormattingEditProvider implementation
335 | provideDocumentRangeFormattingEdits(document: vscode.TextDocument, range: vscode.Range): vscode.ProviderResult {
336 | const edits = this.formatDocument(document, range);
337 | return edits;
338 | }
339 | }
340 |
--------------------------------------------------------------------------------
/src/formatter/MarkdownTableFormatterSettingsImpl.ts:
--------------------------------------------------------------------------------
1 | import {workspace, WorkspaceConfiguration} from "vscode";
2 | import MarkdownTableFormatterSettings, {MarkdownTableFormatterDefaultTableJustification, MarkdownTableFormatterDelimiterRowPadding, MarkdownTableFormatterGlobalColumnSizes, MarkdownTableFormatterLimitLastRowLength, MarkdownTableFormatterWhichCodeLensesToShow} from "./MarkdownTableFormatter.types";
3 |
4 | export default class MarkdownTableFormatterSettingsImpl implements MarkdownTableFormatterSettings {
5 |
6 | private config: WorkspaceConfiguration;
7 |
8 | private static instance: MarkdownTableFormatterSettings;
9 |
10 | public static get shared(): MarkdownTableFormatterSettings {
11 | if (this.instance == null) {
12 | this.instance = new MarkdownTableFormatterSettingsImpl();
13 | }
14 | return this.instance;
15 | }
16 |
17 | /**
18 | * Create a MarkdownTableFormatterSettings from a MarkdownTableFormatterSettings like object
19 | * @param options MarkdownTableFormatterSettings like object
20 | */
21 | public static create(options: MarkdownTableFormatterSettings): MarkdownTableFormatterSettings {
22 | options.toString = MarkdownTableFormatterSettingsImpl.prototype.toString
23 | return options
24 | }
25 |
26 | private constructor() {
27 | this.config = workspace.getConfiguration('markdown-table-formatter');
28 | workspace.onDidChangeConfiguration((changeEvent) => {
29 | if (changeEvent.affectsConfiguration('markdown-table-formatter')) {
30 | this.config = workspace.getConfiguration('markdown-table-formatter');
31 | }
32 | });
33 | }
34 |
35 | get enable(): boolean {
36 | return this.config.get('enable', true);
37 | }
38 | get enableSort(): boolean {
39 | return this.config.get('enableSort', true);
40 | }
41 | get sortCaseInsensitive(): boolean {
42 | return this.config.get('sortCaseInsensitive', false);
43 | }
44 | get spacePadding(): number {
45 | return this.config.get('spacePadding', 1);
46 | }
47 | get keepFirstAndLastPipes(): boolean {
48 | return this.config.get('keepFirstAndLastPipes', true);
49 | }
50 | get defaultTableJustification(): MarkdownTableFormatterDefaultTableJustification {
51 | return this.config.get('defaultTableJustification', MarkdownTableFormatterDefaultTableJustification.Left);
52 | }
53 | get removeColonsIfSameAsDefault(): boolean {
54 | return this.config.get('removeColonsIfSameAsDefault', false);
55 | }
56 | get markdownGrammarScopes(): string[] {
57 | return this.config.get('markdownGrammarScopes', ['markdown']);
58 | }
59 | get globalColumnSizes(): MarkdownTableFormatterGlobalColumnSizes {
60 | return this.config.get('globalColumnSizes', MarkdownTableFormatterGlobalColumnSizes.Disabled);
61 | }
62 | get delimiterRowPadding(): MarkdownTableFormatterDelimiterRowPadding {
63 | return this.config.get('delimiterRowPadding', MarkdownTableFormatterDelimiterRowPadding.None);
64 | }
65 | get limitLastColumnLength(): MarkdownTableFormatterLimitLastRowLength {
66 | return this.config.get('limitLastColumnLength', MarkdownTableFormatterLimitLastRowLength.None);
67 | }
68 | get whichCodeLensesToShow(): MarkdownTableFormatterWhichCodeLensesToShow[] {
69 | return this.config.get('whichCodeLensesToShow', [MarkdownTableFormatterWhichCodeLensesToShow.Format, MarkdownTableFormatterWhichCodeLensesToShow.Sort, MarkdownTableFormatterWhichCodeLensesToShow.ReSort]);
70 | }
71 | get allowEmptyRows(): boolean {
72 | return this.config.get('allowEmptyRows', true);
73 | }
74 |
75 | public toString(): string {
76 | return `{ enable: ${this.enable}, enableSort: ${this.enableSort}, sortCaseInsensitive: ${this.sortCaseInsensitive}, spacePadding: ${this.spacePadding}, keepFirstAndLastPipes: ${this.keepFirstAndLastPipes}, defaultTableJustification: ${this.defaultTableJustification}, removeColonsIfSameAsDefault: ${this.removeColonsIfSameAsDefault}, globalColumnSizes: ${this.globalColumnSizes}, delimiterRowPadding: ${this.delimiterRowPadding}, limitLastColumnLength: ${this.limitLastColumnLength} }`;
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/src/formatter/MarkdownTableFormatterUtils.ts:
--------------------------------------------------------------------------------
1 | import { Range } from "vscode";
2 | import { MarkdownTable } from "../MarkdownTable";
3 |
4 | export const tableJustification: { [key: string]: string } = {
5 | Left: ':-',
6 | Center: '::',
7 | Right: '-:'
8 | };
9 |
10 | export const addTailPipes = (str: string): string => {
11 | return `|${str}|`;
12 | };
13 |
14 | export const joinCells = (arr: string[]): string => {
15 | return arr.join('|');
16 | };
17 |
18 | export const stripHeaderTailPipes = (line: string | undefined): string => {
19 | return line?.trim().replace(/(^\||\|$)/g, '') ?? "";
20 | };
21 |
22 | export const getColumnIndexFromRange = (table: MarkdownTable, range: Range): number => {
23 | let response = -1;
24 | table.ranges.forEach((rangeList, columnIndex) => {
25 | rangeList.forEach(rangeItem => {
26 | if (rangeItem.contains(range)) {
27 | response = columnIndex;
28 | }
29 | });
30 | });
31 | return response;
32 | }
33 |
34 | export const splitCells = (str: string): string[] => {
35 | const items: string[] = [];
36 | let buffer = "";
37 | for (let i = 0; i <= str.length; i++) {
38 | if (((str[i] === "|") && (str[i-1] !== "\\")) || i === str.length) {
39 | if (buffer.length >= 0) {
40 | items.push(buffer);
41 | buffer = "";
42 | continue;
43 | }
44 | } else {
45 | buffer += str[i];
46 | }
47 | }
48 | return items;
49 | };
50 |
51 | export const fixJustification = (cell: string): string => {
52 | const trimmed = cell.trim();
53 | if (trimmed === "") {
54 | return "--";
55 | }
56 | const first = trimmed[0];
57 | const last = trimmed[trimmed.length - 1];
58 | return (first || ':') + (last || '-');
59 | };
--------------------------------------------------------------------------------
/src/sorter/MTSortIndicator.ts:
--------------------------------------------------------------------------------
1 | export enum SortIndicator {
2 | ascending = '▲',
3 | descending = '▼',
4 | separator = ' '
5 | }
--------------------------------------------------------------------------------
/src/sorter/MTSortInfo.ts:
--------------------------------------------------------------------------------
1 | import MarkdownTableSortOptions from "./MarkdownTableSortOptions";
2 |
3 | export default interface MTSortInfo {
4 | [propName: string]: { [propName: string]: MarkdownTableSortOptions };
5 | }
--------------------------------------------------------------------------------
/src/sorter/MarkdownTableSortCodeLensProvider.ts:
--------------------------------------------------------------------------------
1 | import * as vscode from 'vscode';
2 | import MarkdownTableFormatterSettings, { MarkdownTableFormatterWhichCodeLensesToShow } from '../formatter/MarkdownTableFormatter.types';
3 | import {MarkdownTable} from '../MarkdownTable';
4 | import {checkLanguage, tablesIn} from '../MarkdownTableUtils';
5 | import MarkdownTableSortCommandArguments from './MarkdownTableSortCommandArguments';
6 | import {MarkdownTableSortDirection} from './MarkdownTableSortDirection';
7 | import {cleanSortIndicator, getActiveSort, getSortIndicator, invertSort, setActiveSort} from './MarkdownTableSortUtils';
8 | import { getColumnIndexFromRange } from '../formatter/MarkdownTableFormatterUtils';
9 |
10 | export class MarkdownTableSortCodeLensProvider implements vscode.CodeLensProvider, vscode.Disposable {
11 |
12 | private disposables: vscode.Disposable[] = [];
13 |
14 | private config: MarkdownTableFormatterSettings
15 |
16 | constructor(config: MarkdownTableFormatterSettings) {
17 | this.config = config;
18 | }
19 |
20 | dispose(): void {
21 | this.disposables.forEach(d => d.dispose());
22 | this.disposables = [];
23 | }
24 |
25 | public register(): void {
26 | if (this.config.enableSort) {
27 | this.config.markdownGrammarScopes?.forEach((scope) => {
28 | this.registerCodeLensForScope(scope);
29 | });
30 |
31 | this.disposables.push(
32 | vscode.commands.registerTextEditorCommand('markdown-table-formatter.sortTable', this.sortTableCommand, this)
33 | );
34 | }
35 | }
36 |
37 | private registerCodeLensForScope(scope: vscode.DocumentSelector) {
38 | this.disposables.push(vscode.languages.registerCodeLensProvider(scope, this));
39 | }
40 |
41 | private codeLensForTable(table: MarkdownTable, document: vscode.TextDocument): vscode.CodeLens[] {
42 | const activeSort = getActiveSort(document, table.id);
43 | let lenses: vscode.CodeLens[] = [];
44 | if (this.config.whichCodeLensesToShow?.includes(MarkdownTableFormatterWhichCodeLensesToShow.Format)) {
45 | lenses.push(new vscode.CodeLens(table.range, {
46 | command: "markdown-table-formatter.formatTable",
47 | title: "Format",
48 | arguments: [{markdownTableFormatterArguments: { table: table }}]
49 | }))
50 | }
51 |
52 | if (this.config.whichCodeLensesToShow?.includes(MarkdownTableFormatterWhichCodeLensesToShow.Sort)) {
53 | lenses.push(...table.header.map((header, header_index) => {
54 |
55 | let nextSortDirection = invertSort(activeSort?.sort_direction);
56 |
57 | let headerText = `${header.trim()}`;
58 | if (header.trim() === "") {
59 | headerText = `Column ${header_index + 1}`;
60 | }
61 |
62 | if (activeSort && activeSort.header_index === header_index) {
63 | headerText = `${headerText + getSortIndicator(activeSort.sort_direction)}`;
64 | }
65 |
66 | return new vscode.CodeLens(table.range, {
67 | title: headerText,
68 | command: 'markdown-table-formatter.sortTable',
69 | arguments: [{markdownTableFormatterArguments: { table: table, options: { header_index, sort_direction: nextSortDirection } }}]
70 | });
71 | }));
72 | }
73 |
74 | if (this.config.whichCodeLensesToShow?.includes(MarkdownTableFormatterWhichCodeLensesToShow.ReSort)) {
75 | lenses.push(new vscode.CodeLens(table.range, {
76 | command: "markdown-table-formatter.sortTable",
77 | title: "Re-sort",
78 | arguments: [{markdownTableFormatterArguments: { table: table, options: activeSort }}]
79 | }))
80 | }
81 | return lenses;
82 | }
83 |
84 | public sortTable(table: MarkdownTable, headerIndex: number, sortDirection: MarkdownTableSortDirection): string {
85 | table.header.forEach((header, i) => {
86 | if (i !== headerIndex) {
87 | table.header[i] = cleanSortIndicator(header);
88 | }
89 | });
90 |
91 | const isIPV4 = table.body?.every(l => /\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}$/.test(l[headerIndex].trim()) || l[headerIndex].trim()==="" )
92 |
93 | const canSortByNumber = table.body?.every(l => /^-?\d+$/.test(l[headerIndex].trim()))
94 |
95 | const collator = new Intl.Collator(undefined, {
96 | numeric: canSortByNumber || isIPV4,
97 | sensitivity: this.config.sortCaseInsensitive ? "base" : "variant",
98 | ignorePunctuation: isIPV4
99 | })
100 |
101 | table.body?.sort((a: string[], b: string[]) => {
102 | let textA = a[headerIndex].trim() || "";
103 | let textB = b[headerIndex].trim() || "";
104 |
105 | const compareResult = collator.compare(textA, textB)
106 |
107 | return sortDirection * compareResult;
108 |
109 | });
110 |
111 | return table.notFormatted();
112 | }
113 |
114 | // vscode.Commands
115 | // vscode.Command
116 | private sortTableCommand(editor: vscode.TextEditor, edit: vscode.TextEditorEdit, args?: MarkdownTableSortCommandArguments) {
117 | if (!checkLanguage(editor.document.languageId, this.config)) { return }
118 |
119 | let table: MarkdownTable, index: number, direction: MarkdownTableSortDirection;
120 |
121 | if (!args?.markdownTableFormatterArguments) {
122 | const tables = tablesIn(this.config, editor.document);
123 | const tableFound = tables.find(t => t.range.contains(editor.selection));
124 | if (!tableFound) { return };
125 | table = tableFound;
126 | index = getColumnIndexFromRange(table, editor.selection);
127 | direction = invertSort(getActiveSort(editor.document, table.id)?.sort_direction);
128 | } else {
129 | table = args?.markdownTableFormatterArguments.table;
130 | index = args?.markdownTableFormatterArguments.options.header_index;
131 | direction = args?.markdownTableFormatterArguments?.options.sort_direction ?? invertSort(getActiveSort(editor.document, table.id)?.sort_direction);
132 | }
133 |
134 | setActiveSort(editor.document, table?.id, index, direction);
135 |
136 | edit.replace(table.range, this.sortTable(table, index, direction));
137 | }
138 |
139 | // vscode.CodeLensProvider implementation
140 | provideCodeLenses(document: vscode.TextDocument): vscode.CodeLens[] | Thenable {
141 | if (!checkLanguage(document.languageId, this.config)) { return [] }
142 |
143 | const tables = tablesIn(this.config, document);
144 |
145 | const lenses = tables
146 | .filter(table => table.bodyLines > 1)
147 | .map(table => this.codeLensForTable(table, document) ?? []);
148 |
149 | return lenses.reduce((acc, val) => acc.concat(val), []);
150 | }
151 |
152 | resolveCodeLens(codeLens: vscode.CodeLens): vscode.ProviderResult {
153 | return codeLens;
154 | }
155 | }
156 |
--------------------------------------------------------------------------------
/src/sorter/MarkdownTableSortCommandArguments.ts:
--------------------------------------------------------------------------------
1 | import { MarkdownTable } from "../MarkdownTable";
2 | import MarkdownTableSortOptions from "./MarkdownTableSortOptions";
3 |
4 | export default interface MarkdownTableSortCommandArguments {
5 | markdownTableFormatterArguments: {
6 | table: MarkdownTable;
7 | options: MarkdownTableSortOptions
8 | }
9 | }
--------------------------------------------------------------------------------
/src/sorter/MarkdownTableSortDirection.ts:
--------------------------------------------------------------------------------
1 | export enum MarkdownTableSortDirection {
2 | Asc = 1,
3 | Desc = -1
4 | }
--------------------------------------------------------------------------------
/src/sorter/MarkdownTableSortOptions.ts:
--------------------------------------------------------------------------------
1 | import { MarkdownTableSortDirection } from "./MarkdownTableSortDirection";
2 |
3 | export default interface MarkdownTableSortOptions {
4 | header_index: number;
5 | sort_direction?: MarkdownTableSortDirection;
6 | }
--------------------------------------------------------------------------------
/src/sorter/MarkdownTableSortUtils.ts:
--------------------------------------------------------------------------------
1 | import * as vscode from 'vscode';
2 | import { MarkdownTableSortDirection } from "./MarkdownTableSortDirection";
3 | import MarkdownTableSortOptions from "./MarkdownTableSortOptions";
4 | import { SortIndicator } from './MTSortIndicator';
5 | import MTSortInfo from './MTSortInfo';
6 |
7 | export const cleanSortIndicator = (text: string): string => {
8 | const replace = ' '.repeat((SortIndicator.separator + SortIndicator.ascending).length)
9 | return text.replace(SortIndicator.separator + SortIndicator.ascending, replace).replace(SortIndicator.separator + SortIndicator.descending, replace);
10 | };
11 | const hasAscendingSortIndicator = (text: string): boolean => {
12 | return text.indexOf(SortIndicator.ascending) >= 0;
13 | };
14 | const hasDescendingSortIndicator = (text: string): boolean => {
15 | return text.indexOf(SortIndicator.descending) >= 0;
16 | };
17 | const hasAnyIndicator = (text: string): boolean => {
18 | return hasAscendingSortIndicator(text) || hasDescendingSortIndicator(text);
19 | };
20 |
21 | export const invertSort = (direction?: MarkdownTableSortDirection): MarkdownTableSortDirection => {
22 | switch (direction) {
23 | case MarkdownTableSortDirection.Asc:
24 | return MarkdownTableSortDirection.Desc
25 | case MarkdownTableSortDirection.Desc:
26 | return MarkdownTableSortDirection.Asc
27 | default:
28 | return MarkdownTableSortDirection.Asc
29 | }
30 | }
31 |
32 | export const setSortIndicator = (text: string, direction: MarkdownTableSortDirection): string => {
33 | let indicator = ''
34 | let oldIndicator = ''
35 | if (direction === MarkdownTableSortDirection.Asc) {
36 | indicator = SortIndicator.ascending;
37 | oldIndicator = SortIndicator.descending
38 | }
39 | if (direction === MarkdownTableSortDirection.Desc) {
40 | indicator = SortIndicator.descending;
41 | oldIndicator = SortIndicator.ascending
42 | }
43 | if (hasAnyIndicator(text)) {
44 | text = text.replace(oldIndicator, indicator);
45 | } else {
46 | const size = Math.max(0, text.length - text.trimEnd().length - (SortIndicator.separator + indicator).length)
47 | text = text.trimEnd() + SortIndicator.separator + indicator + ' '.repeat(size)
48 | }
49 | return text;
50 | };
51 |
52 | const _activeSort: MTSortInfo = {};
53 |
54 | export function setActiveSort(document: vscode.TextDocument, table_id: string, header_index: number | undefined, sort_direction?: MarkdownTableSortDirection): void {
55 | if (!_activeSort[document.uri.path]) {
56 | _activeSort[document.uri.path] = {};
57 | }
58 | if (header_index !== undefined && header_index >= 0 && sort_direction) {
59 | _activeSort[document.uri.path][table_id] = {
60 | header_index, sort_direction
61 | };
62 | } else {
63 | delete _activeSort[document.uri.path][table_id];
64 | }
65 | }
66 |
67 | export function getActiveSort(document: vscode.TextDocument, table_id: string): MarkdownTableSortOptions | undefined {
68 | if (_activeSort && _activeSort[document.uri.path]) {
69 | return _activeSort[document.uri.path][table_id];
70 | }
71 | return undefined;
72 | }
73 |
74 | export function getSortIndicator(direction?: MarkdownTableSortDirection): string {
75 | switch (direction) {
76 | case MarkdownTableSortDirection.Asc:
77 | return SortIndicator.separator + SortIndicator.ascending;
78 | case MarkdownTableSortDirection.Desc:
79 | return SortIndicator.separator + SortIndicator.descending;
80 | default:
81 | return "";
82 | }
83 | }
--------------------------------------------------------------------------------
/src/test/files/onetable.md:
--------------------------------------------------------------------------------
1 | | f\|oo |
2 | | ------ |
3 | | apple |
4 | | Apple |
5 | | Blueberry |
6 | | Cherry |
7 | | Dewberry |
8 | | Eggplant |
9 | | Grape |
10 | | Horseradish |
11 | | Kale |
12 | | Lettuce |
13 | | Mango |
14 | | Nutmeg |
15 | | Orange |
16 | | Pineapple |
17 | | Radish |
18 | | Strawberry |
19 | | Tomato |
20 | | Watermelon |
21 | | Zucchini |
22 |
23 |
24 | | <> | <> | <>
25 | | --- | --- | ---
26 | | <> | <> | <>
27 | | <> | <> | <>
--------------------------------------------------------------------------------
/src/test/files/tables.md:
--------------------------------------------------------------------------------
1 | | Text | Result |
2 | |----------|-------------------|
3 | | `` $` `` | text before match |
4 | | `` $\|` `` | text before match |
5 |
6 | |header a|header b|
7 | |------------|------------|
8 | |column a 1|column b 1|
9 | |column a 2|column b 2|
10 |
11 | |DOuble header
12 | |header a|numeric header|
13 | |------------|------------|
14 | |column a 1|1|
15 | |column a 2|10|
16 | |column a 3|2|
17 |
18 | ## Lorem ipsum
19 | Lorem ipsum dolor sit amet, consectetur adipiscing elit.
20 | |Topic|Status|Notes|
21 | |----------------------------|-----------|-------|
22 | |Is source control used?|`NO`||
23 | |Are changes peer reviewed?|`PARTIAL`||
24 |
25 |
26 | ## Sed lacinia
27 | Sed lacinia tortor et ultrices semper.
28 | |Topic|Status|Notes|
29 | |--------------|--------|-------|
30 | |Is Iot used?|`NO`||
31 |
32 |
33 | |header a|header b|
34 | |------------|------------|
35 | |column a 1|column b 1|
36 | |column a 2|column b 2|
37 |
38 | |Left header|Center header|Right header|Default header|
39 | |:----------------|:---------------:|----------------:|------------------|
40 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D+|
41 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
42 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
43 |
44 |
45 | |Left header|Center header|Right header|Default header|
46 | |-----------------|-----------------|-----------------|-----------------|
47 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
48 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
49 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
50 |
51 | |Left header|Center header|Right header|Default header|
52 | |:----------------|:---------------:|----------------:|-----------------|
53 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
54 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
55 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
56 |
57 | |Left header|Center header|Right header|Default header|
58 | |:----------------|:---------------:|----------------:|-----------------|
59 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
60 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
61 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
62 |
63 |
64 | |Left header|Center header|Right header|Default header|
65 | |:----------------|:---------------:|----------------:|-----------------|
66 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
67 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
68 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
69 |
70 |
71 | |Left header|Center header|Right header|Default header|
72 | |:----------------|:---------------:|----------------:|-----------------|
73 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
74 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
75 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
76 |
77 |
78 | |Left header|Center header|Right header|Default header|
79 | |:----------------|:---------------:|----------------:|-----------------|
80 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
81 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
82 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
83 |
84 |
85 | |Left header|Center header|Right header|Default header|
86 | |:----------------|:---------------:|----------------:|-----------------|
87 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
88 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
89 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
90 |
91 |
92 |
93 | |Left header|Center header|Right header|Default header|
94 | |:----------------|:---------------:|----------------:|-----------------|
95 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
96 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
97 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
98 |
99 |
100 | |Left header|Center header|Right header|Default header|
101 | |:----------------|:---------------:|----------------:|-----------------|
102 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
103 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
104 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
105 |
106 |
107 | |Left header|Center header|Right header|Default header|
108 | |:----------------|:---------------:|----------------:|-----------------|
109 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
110 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
111 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
112 |
113 |
114 | |Left header|Center header|Right header|Default header|
115 | |:----------------|:---------------:|----------------:|-----------------|
116 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
117 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
118 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
119 |
120 |
121 | |Left header|Center header|Right header|Default header|
122 | |:----------------|:---------------:|----------------:|-----------------|
123 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
124 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
125 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
126 |
127 |
128 | |Left header|Center header|Right header|Default header|
129 | |:----------------|:---------------:|----------------:|-----------------|
130 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
131 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
132 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
133 |
134 |
135 | |header a|header b|
136 | |:-----------|------------|
137 | |column a 1|column b 1|
138 | |column a 2|column b 2|
139 |
140 |
141 | |header a|header b|
142 | |:-----------|------------:|
143 | |column a 1|column b 1|
144 | |column a 2|column b 20|
145 |
146 |
147 | |header a|header b|
148 | |:-----------|:----------:|
149 | |column a 1|column b 1|
150 | |column a 2|column b 2|
151 |
152 | |Topic|Status|Notes|
153 | |----------------------------|-------------|-------|
154 | |Is source control used?|\`NO\`||
155 | |Are changes peer reviewed?|\`PARTIAL\`||
156 |
157 |
158 |
159 | |Topic|Status|Notes|
160 | |--------------|--------|-------|
161 | |Is Iot used?|\`NO\`||
162 |
163 |
164 |
165 | |a|b|c|
166 | |:---------|:----------|:--|
167 | |fdasdfas|x \`\|\` y|z|
168 |
169 |
170 |
171 | |Name|Syntax|Equivalent GLSL|
172 | |-------------------|--------------------|-----------------------|
173 | |Negate|\`-a\`|\`-a\`|
174 | |Not|\`nota\`|\`!a\`|
175 | |Sine|\`sina\`|\`sin(a)\`|
176 | |Cosine|\`cosa\`|\`cos(a)\`|
177 | |Tangent|\`tana\`|\`tan(a)\`|
178 | |InverseSine|\`asina\`|\`asin(a)\`|
179 | |InverseCosine|\`acosa\`|\`acos(a)\`|
180 | |InverseTangent|\`atana\`|\`atan(a)\`|
181 | |InverseTangent2|\`aatanb\`|\`atan(a,b)\`|
182 | |Exponential|\`expa\`|\`exp(a)\`|
183 | |Logarithm|\`loga\`|\`log(a)\`|
184 | |Exponential2|\`exp2a\`|\`exp2(a)\`|
185 | |Logarithm2|\`log2a\`|\`log2(a)\`|
186 | |SquareRoot|\`sqrta\`|\`sqrt(a)\`|
187 | |InverseSquareRoot|\`inversesqrta\`|\`inversesqrt(a)\`|
188 | |Absolute|\`absa\`|\`abs(a)\`|
189 | |Sign|\`signa\`|\`sign(a)\`|
190 | |Floor|\`floora\`|\`floor(a)\`|
191 | |Ceiling|\`ceila\`|\`ceil(a)\`|
192 | |Fractional|\`fracta\`|\`fract(a)\`|
193 | |Multiply|\`a*b\`|\`a*b\`|
194 | |Divide|\`a/b\`|\`a/b\`|
195 | |Add|\`a+b\`|\`a+b\`|
196 | |Subtract|\`a-b\`|\`a-b\`|
197 | |LessThan|\`ab\`|\`a>b\`|
199 | |LessThanEqual|\`a<=b\`|\`a<=b\`|
200 | |GreaterThanEqual|\`a>=b\`|\`a>=b\`|
201 | |Equal|\`aisb\`|\`a==b\`|
202 | |NotEqual|\`anotb\`|\`a!=b\`|
203 | |And|\`a&&b\`|\`a&&b\`|
204 | |Or|\`a\|\|b\`|\`a\|b\`|
205 | |Exponentiate|\`apowb\`|\`pow(a,b)\`|
206 | |Modulo|\`a%b\`|\`mod(a,b)\`|
207 | |Minimum|\`aminb\`|\`min(a,b)\`|
208 | |Maximum|\`amaxb\`|\`max(a,b)\`|
209 | |Conditional|\`a?b:c\`|\`a?b:c\`|
210 | |Clamp|\`aclampb:c\`|\`clamp(b,c,a)\`|
211 | |Step|\`astepb\`|\`step(b,a)\`|
212 | |SmoothStep|\`asmoothstepb:c\`|\`smoothstep(b,c,a)\`|
213 | |LinearInterpolate|\`amixb:c\`|\`mix(b,c,a)\`|
214 |
215 |
216 | |Small a|Small b|
217 | |:--------|:--------|
218 | |L:1 C:A|L:1 C:B|
219 |
220 | |Large header a|Large header b|
221 | |:----------------|:----------------|
222 | |Line:1 Column:A|Line:1 Column:B|
223 |
224 |
225 | |Small a|Small b|Small c|
226 | |:--------|:--------|:--------|
227 | |L:1 C:A|L:1 C:B|L:1 C:C|
228 |
229 | |Large header a|Large header b|
230 | |:----------------|:----------------|
231 | |Line:1 Column:A|Line:1 Column:B|
232 |
233 |
234 | |Small a|Small b|Small c|
235 | |:--------|:--------|:--------|
236 | |L:1 C:A|L:1 C:B|L:1 C:C|
237 |
238 | |Large header a|Large header b|
239 | |:----------------|:----------------|
240 | |Line:1 Column:A|Line:1 Column:B|
241 |
242 |
243 | |Topic|Status|Notes|
244 | |:---------------------------|:--------|:------|
245 | |Is source control used?|NO||
246 | |Are changes peer reviewed?|PARTIAL||
247 |
248 | |Topic|Status|
249 | |:-------------|:-------|
250 | |Is Iot used?|NO|
251 |
252 |
253 | |Topic|Status|Notes|
254 | |:---------------------------|:--------|:------|
255 | |Is source control used?|NO||
256 | |Are changes peer reviewed?|PARTIAL||
257 |
258 | |Topic|Status|
259 | |:-------------|:-------|
260 | |Is Iot used?|NO|
261 |
262 |
263 | |1eft header|Center header|Right header|Default header|
264 | |:----------------|:---------------:|----------------:|-----------------|
265 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
266 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
267 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
268 |
269 | |Topic|Status|Notes|
270 | |----------------------------|---------|-------|
271 | |Is source control used?|NO||
272 | |Are changes peer reviewed?|PARTIAL||
273 |
274 | * |One|Two|Three|
275 | |---|---|-----|
276 | |'1'|'2'|'3'|
277 |
278 | |abc|def|
279 | |---|---|
280 | |bar|baz|
281 | > bar
282 |
283 | | f\|oo |
284 | | ------ |
285 | | b `\|` az |
286 | | b **\|** im |
287 |
288 |
289 | |abc|def|
290 | |---|---|
291 | |bar|baz|
292 | > bar
293 |
294 | 1. One | Two | Three
295 | --- | --- | -----
296 | '1' | '2' | '3'
297 |
298 | * Stuff:
299 | |One|Two|Three|
300 | |---|---|-----|
301 | |'1'|'2'|'3'|
--------------------------------------------------------------------------------
/src/test/files/tables.ts:
--------------------------------------------------------------------------------
1 | import MarkdownTableFormatterSettings, {MarkdownTableFormatterDefaultTableJustification, MarkdownTableFormatterDelimiterRowPadding, MarkdownTableFormatterGlobalColumnSizes, MarkdownTableFormatterLimitLastRowLength} from "../../formatter/MarkdownTableFormatter.types";
2 |
3 | export const testTables: { id: number, input: string, expected: string, settings?: MarkdownTableFormatterSettings }[] = [
4 | {
5 | id: 0,
6 | input: `\
7 | | Foo | Bar |
8 | | - | - |
9 | |'Baz'|Qux|`,
10 | expected: `\
11 | | Foo | Bar |
12 | | ----- | --- |
13 | | 'Baz' | Qux |`,
14 | settings: {
15 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.SingleApaceAlways
16 | }
17 | },
18 | {
19 | id: 1,
20 | input: `\
21 | |Left header|Center header |Right header|Default header|
22 | |:-|::|-:||
23 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
24 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
25 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|`,
26 | expected: `\
27 | | Left header | Center header | Right header | Default header |
28 | |:----------------|:---------------:|----------------:|-----------------|
29 | | Line:1 Column:A | Line:1 Column:B | Line:1 Column:C | Line:1 Column:D |
30 | | Line:2 Col:A | Line:2 Col:B | Line:2 Col:C | Line:2 Col:D |
31 | | L:3 C:A | L:3 C:B | L:3 C:C | L:3 C:D |`,
32 | settings: {
33 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Center
34 | }
35 | },
36 | {
37 | id: 2,
38 | input: `\
39 | |Left header|Center header |Right header|Default header|
40 | |:-|::|-:|-|
41 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
42 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
43 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|`,
44 | expected: `\
45 | | Left header | Center header | Right header | Default header |
46 | |:----------------|:---------------:|----------------:|-----------------|
47 | | Line:1 Column:A | Line:1 Column:B | Line:1 Column:C | Line:1 Column:D |
48 | | Line:2 Col:A | Line:2 Col:B | Line:2 Col:C | Line:2 Col:D |
49 | | L:3 C:A | L:3 C:B | L:3 C:C | L:3 C:D |`
50 | },
51 | {
52 | id: 3,
53 | input: `\
54 | |Left header|Center header |Right header|Default header|
55 | |:-|::|-:|-|
56 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
57 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
58 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|`,
59 | expected: `\
60 | | Left header | Center header | Right header | Default header |
61 | |:----------------|:---------------:|----------------:|-----------------|
62 | | Line:1 Column:A | Line:1 Column:B | Line:1 Column:C | Line:1 Column:D |
63 | | Line:2 Col:A | Line:2 Col:B | Line:2 Col:C | Line:2 Col:D |
64 | | L:3 C:A | L:3 C:B | L:3 C:C | L:3 C:D |`,
65 | settings: {
66 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Center,
67 | }
68 | },
69 | {
70 | id: 4,
71 | input: `\
72 | |Left header|Center header |Right header|Default header|
73 | |:-|::|-:|-|
74 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
75 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
76 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|`,
77 | expected: `\
78 | | Left header | Center header | Right header | Default header |
79 | |:----------------|:---------------:|----------------:|-----------------|
80 | | Line:1 Column:A | Line:1 Column:B | Line:1 Column:C | Line:1 Column:D |
81 | | Line:2 Col:A | Line:2 Col:B | Line:2 Col:C | Line:2 Col:D |
82 | | L:3 C:A | L:3 C:B | L:3 C:C | L:3 C:D |`,
83 | settings: {
84 | enable: true,
85 | enableSort: true,
86 | spacePadding: 1,
87 | keepFirstAndLastPipes: true,
88 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Right,
89 | markdownGrammarScopes: ['markdown'],
90 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
91 | removeColonsIfSameAsDefault: false,
92 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameColumnSize,
93 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
94 | allowEmptyRows: true
95 | }
96 | },
97 | {
98 | id: 5,
99 | input: `\
100 | |Left header|Center header |Right header|Default header|
101 | |:-|::|-:|-|
102 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
103 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
104 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|`,
105 | expected: `\
106 | | Left header | Center header | Right header | Default header |
107 | |-----------------|:---------------:|----------------:|-----------------|
108 | | Line:1 Column:A | Line:1 Column:B | Line:1 Column:C | Line:1 Column:D |
109 | | Line:2 Col:A | Line:2 Col:B | Line:2 Col:C | Line:2 Col:D |
110 | | L:3 C:A | L:3 C:B | L:3 C:C | L:3 C:D |`,
111 | settings: {
112 | enable: true,
113 | enableSort: true,
114 | spacePadding: 1,
115 | keepFirstAndLastPipes: true,
116 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Left,
117 | markdownGrammarScopes: ['markdown'],
118 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
119 | removeColonsIfSameAsDefault: true,
120 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameColumnSize,
121 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
122 | allowEmptyRows: true
123 | }
124 | },
125 | {
126 | id: 6,
127 | input: `\
128 | |Left header|Center header |Right header|Default header|
129 | |:-|::|-:|-|
130 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
131 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
132 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|`,
133 | expected: `\
134 | | Left header | Center header | Right header | Default header |
135 | |:----------------|-----------------|----------------:|-----------------|
136 | | Line:1 Column:A | Line:1 Column:B | Line:1 Column:C | Line:1 Column:D |
137 | | Line:2 Col:A | Line:2 Col:B | Line:2 Col:C | Line:2 Col:D |
138 | | L:3 C:A | L:3 C:B | L:3 C:C | L:3 C:D |`,
139 | settings: {
140 | enable: true,
141 | enableSort: true,
142 | spacePadding: 1,
143 | keepFirstAndLastPipes: true,
144 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Center,
145 | markdownGrammarScopes: ['markdown'],
146 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
147 | removeColonsIfSameAsDefault: true,
148 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameColumnSize,
149 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
150 | allowEmptyRows: true
151 | }
152 | },
153 | {
154 | id: 7,
155 | input: `\
156 | |Left header|Center header |Right header|Default header|
157 | |:-|::|-:|-|
158 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
159 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
160 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|`,
161 | expected: `\
162 | | Left header | Center header | Right header | Default header |
163 | |:----------------|:---------------:|-----------------|-----------------|
164 | | Line:1 Column:A | Line:1 Column:B | Line:1 Column:C | Line:1 Column:D |
165 | | Line:2 Col:A | Line:2 Col:B | Line:2 Col:C | Line:2 Col:D |
166 | | L:3 C:A | L:3 C:B | L:3 C:C | L:3 C:D |`,
167 | settings: {
168 | enable: true,
169 | enableSort: true,
170 | spacePadding: 1,
171 | keepFirstAndLastPipes: true,
172 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Right,
173 | markdownGrammarScopes: ['markdown'],
174 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
175 | removeColonsIfSameAsDefault: true,
176 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameColumnSize,
177 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
178 | allowEmptyRows: true
179 | }
180 | },
181 | {
182 | id: 8,
183 | input: `\
184 | |Left header|Center header |Right header|Default header|
185 | |:-|::|-:|-|
186 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
187 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
188 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|`,
189 | expected: `\
190 | | Left header | Center header | Right header | Default header |
191 | |:------------------|:-----------------:|------------------:|-------------------|
192 | | Line:1 Column:A | Line:1 Column:B | Line:1 Column:C | Line:1 Column:D |
193 | | Line:2 Col:A | Line:2 Col:B | Line:2 Col:C | Line:2 Col:D |
194 | | L:3 C:A | L:3 C:B | L:3 C:C | L:3 C:D |`,
195 | settings: {
196 | enable: true,
197 | enableSort: true,
198 | spacePadding: 2,
199 | keepFirstAndLastPipes: true,
200 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Left,
201 | markdownGrammarScopes: ['markdown'],
202 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
203 | removeColonsIfSameAsDefault: false,
204 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameColumnSize,
205 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
206 | allowEmptyRows: true
207 | }
208 | },
209 | {
210 | id: 9,
211 | input: `\
212 | |Left header|Center header |Right header|Default header|
213 | |:-|::|-:|-|
214 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
215 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
216 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|`,
217 | expected: `\
218 | | Left header | Center header | Right header | Default header |
219 | |:------------------|:-----------------:|------------------:|-------------------|
220 | | Line:1 Column:A | Line:1 Column:B | Line:1 Column:C | Line:1 Column:D |
221 | | Line:2 Col:A | Line:2 Col:B | Line:2 Col:C | Line:2 Col:D |
222 | | L:3 C:A | L:3 C:B | L:3 C:C | L:3 C:D |`,
223 | settings: {
224 | enable: true,
225 | enableSort: true,
226 | spacePadding: 2,
227 | keepFirstAndLastPipes: true,
228 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Center,
229 | markdownGrammarScopes: ['markdown'],
230 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
231 | removeColonsIfSameAsDefault: false,
232 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameColumnSize,
233 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
234 | allowEmptyRows: true
235 | }
236 | },
237 | {
238 | id: 10,
239 | input: `\
240 | |Left header|Center header |Right header|Default header|
241 | |:-|::|-:|-|
242 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
243 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
244 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|`,
245 | expected: `\
246 | | Left header | Center header | Right header | Default header |
247 | |:------------------|:-----------------:|------------------:|-------------------|
248 | | Line:1 Column:A | Line:1 Column:B | Line:1 Column:C | Line:1 Column:D |
249 | | Line:2 Col:A | Line:2 Col:B | Line:2 Col:C | Line:2 Col:D |
250 | | L:3 C:A | L:3 C:B | L:3 C:C | L:3 C:D |`,
251 | settings: {
252 | enable: true,
253 | enableSort: true,
254 | spacePadding: 2,
255 | keepFirstAndLastPipes: true,
256 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Right,
257 | markdownGrammarScopes: ['markdown'],
258 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
259 | removeColonsIfSameAsDefault: false,
260 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameColumnSize,
261 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
262 | allowEmptyRows: true
263 | }
264 | },
265 | {
266 | id: 11,
267 | input: `\
268 | |Left header|Center header |Right header|Default header|
269 | |:-|::|-:|-|
270 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
271 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
272 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|`,
273 | expected: `\
274 | Left header | Center header | Right header | Default header
275 | :----------------|:---------------:|----------------:|-----------------
276 | Line:1 Column:A | Line:1 Column:B | Line:1 Column:C | Line:1 Column:D
277 | Line:2 Col:A | Line:2 Col:B | Line:2 Col:C | Line:2 Col:D
278 | L:3 C:A | L:3 C:B | L:3 C:C | L:3 C:D `,
279 | settings: {
280 | enable: true,
281 | enableSort: true,
282 | spacePadding: 1,
283 | keepFirstAndLastPipes: false,
284 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Left,
285 | markdownGrammarScopes: ['markdown'],
286 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
287 | removeColonsIfSameAsDefault: false,
288 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameColumnSize,
289 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
290 | allowEmptyRows: true
291 | }
292 | },
293 | {
294 | id: 12,
295 | input: `\
296 | |Left header|Center header |Right header|Default header|
297 | |:-|::|-:|-|
298 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
299 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
300 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|`,
301 | expected: `\
302 | Left header | Center header | Right header | Default header
303 | :----------------|:---------------:|----------------:|-----------------
304 | Line:1 Column:A | Line:1 Column:B | Line:1 Column:C | Line:1 Column:D
305 | Line:2 Col:A | Line:2 Col:B | Line:2 Col:C | Line:2 Col:D
306 | L:3 C:A | L:3 C:B | L:3 C:C | L:3 C:D `,
307 | settings: {
308 | enable: true,
309 | enableSort: true,
310 | spacePadding: 1,
311 | keepFirstAndLastPipes: false,
312 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Center,
313 | markdownGrammarScopes: ['markdown'],
314 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
315 | removeColonsIfSameAsDefault: false,
316 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameColumnSize,
317 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
318 | allowEmptyRows: true
319 | }
320 | },
321 | {
322 | id: 13,
323 | input: `\
324 | |Left header|Center header |Right header|Default header|
325 | |:-|::|-:|-|
326 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
327 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
328 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|`,
329 | expected: `\
330 | Left header | Center header | Right header | Default header
331 | :----------------|:---------------:|----------------:|-----------------
332 | Line:1 Column:A | Line:1 Column:B | Line:1 Column:C | Line:1 Column:D
333 | Line:2 Col:A | Line:2 Col:B | Line:2 Col:C | Line:2 Col:D
334 | L:3 C:A | L:3 C:B | L:3 C:C | L:3 C:D `,
335 | settings: {
336 | enable: true,
337 | enableSort: true,
338 | spacePadding: 1,
339 | keepFirstAndLastPipes: false,
340 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Right,
341 | markdownGrammarScopes: ['markdown'],
342 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
343 | removeColonsIfSameAsDefault: false,
344 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameColumnSize,
345 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
346 | allowEmptyRows: true
347 | }
348 | },
349 | {
350 | id: 14,
351 | input: `\
352 | |header a |header b|
353 | |:-|-|
354 | |column a 1|column b 1|
355 | |column a 2|column b 2|`,
356 | expected: `\
357 | | header a | header b |
358 | |:-----------|------------|
359 | | column a 1 | column b 1 |
360 | | column a 2 | column b 2 |`
361 | },
362 | {
363 | id: 15,
364 | input: `\
365 | |header a |header b|
366 | |:-|-:|
367 | |column a 1|column b 1|
368 | |column a 2|column b 20|`,
369 | expected: `\
370 | | header a | header b |
371 | |:-----------|------------:|
372 | | column a 1 | column b 1 |
373 | | column a 2 | column b 20 |`
374 | },
375 | {
376 | id: 16,
377 | input: `\
378 | |header a |header b|
379 | |:-|::|
380 | |column a 1|column b 1|
381 | |column a 2|column b 2|`,
382 | expected: `\
383 | | header a | header b |
384 | |:-----------|:----------:|
385 | | column a 1 | column b 1 |
386 | | column a 2 | column b 2 |`
387 | },
388 | {
389 | id: 17,
390 | input: `\
391 | | Topic | Status | Notes |
392 | |----------------------------|-----------|-------|
393 | | Is source control used? | \`NO\` | |
394 | | Are changes peer reviewed? | \`PARTIAL\` | |`
395 | ,
396 | expected: `\
397 | | Topic | Status | Notes |
398 | |----------------------------|-----------|-------|
399 | | Is source control used? | \`NO\` | |
400 | | Are changes peer reviewed? | \`PARTIAL\` | |`
401 | },
402 | {
403 | id: 18,
404 | input: `\
405 | | Topic | Status | Notes |
406 | |--------------|--------|-------|
407 | | Is Iot used? | \`NO\` | |`
408 | ,
409 | expected: `\
410 | | Topic | Status | Notes |
411 | |--------------|--------|-------|
412 | | Is Iot used? | \`NO\` | |`
413 | },
414 | {
415 | id: 19,
416 | input: `\
417 | | a | b | c |
418 | |:---------|:--|:--|
419 | | fdasdfas | x \`\\|\` y | z |`
420 | ,
421 | expected: `\
422 | | a | b | c |
423 | |:---------|:---------|:--|
424 | | fdasdfas | x \`\\|\` y | z |`
425 | },
426 | {
427 | id: 20,
428 | input: `\
429 | |Name|Syntax|Equivalent GLSL|
430 | |-------------------|----------------------|-----------------------|
431 | |Negate|\`-a\`|\`-a\`|
432 | |Not|\`nota\`|\`!a\`|
433 | |Sine|\`sina\`|\`sin(a)\`|
434 | |Cosine|\`cosa\`|\`cos(a)\`|
435 | |Tangent|\`tana\`|\`tan(a)\`|
436 | |InverseSine|\`asina\`|\`asin(a)\`|
437 | |InverseCosine|\`acosa\`|\`acos(a)\`|
438 | |InverseTangent|\`atana\`|\`atan(a)\`|
439 | |InverseTangent2|\`aatanb\`|\`atan(a,b)\`|
440 | |Exponential|\`expa\`|\`exp(a)\`|
441 | |Logarithm|\`loga\`|\`log(a)\`|
442 | |Exponential2|\`exp2a\`|\`exp2(a)\`|
443 | |Logarithm2|\`log2a\`|\`log2(a)\`|
444 | |SquareRoot|\`sqrta\`|\`sqrt(a)\`|
445 | |InverseSquareRoot|\`inversesqrta\`|\`inversesqrt(a)\`|
446 | |Absolute|\`absa\`|\`abs(a)\`|
447 | |Sign|\`signa\`|\`sign(a)\`|
448 | |Floor|\`floora\`|\`floor(a)\`|
449 | |Ceiling|\`ceila\`|\`ceil(a)\`|
450 | |Fractional|\`fracta\`|\`fract(a)\`|
451 | |Multiply|\`a*b\`|\`a*b\`|
452 | |Divide|\`a/b\`|\`a/b\`|
453 | |Add|\`a+b\`|\`a+b\`|
454 | |Subtract|\`a-b\`|\`a-b\`|
455 | |LessThan|\`ab\`|\`a>b\`|
457 | |LessThanEqual|\`a<=b\`|\`a<=b\`|
458 | |GreaterThanEqual|\`a>=b\`|\`a>=b\`|
459 | |Equal|\`aisb\`|\`a==b\`|
460 | |NotEqual|\`anotb\`|\`a!=b\`|
461 | |And|\`a&&b\`|\`a&&b\`|
462 | |Or|\`a\\|\\|b\`|\`a\\|b\`|
463 | |Exponentiate|\`apowb\`|\`pow(a,b)\`|
464 | |Modulo|\`a%b\`|\`mod(a,b)\`|
465 | |Minimum|\`aminb\`|\`min(a,b)\`|
466 | |Maximum|\`amaxb\`|\`max(a,b)\`|
467 | |Conditional|\`a?b:c\`|\`a?b:c\`|
468 | |Clamp|\`aclampb:c\`|\`clamp(b,c,a)\`|
469 | |Step|\`astepb\`|\`step(b,a)\`|
470 | |SmoothStep|\`asmoothstepb:c\`|\`smoothstep(b,c,a)\`|
471 | |LinearInterpolate|\`amixb:c\`|\`mix(b,c,a)\`|`,
472 | expected: `\
473 | | Name | Syntax | Equivalent GLSL |
474 | |-------------------|------------------|---------------------|
475 | | Negate | \`-a\` | \`-a\` |
476 | | Not | \`nota\` | \`!a\` |
477 | | Sine | \`sina\` | \`sin(a)\` |
478 | | Cosine | \`cosa\` | \`cos(a)\` |
479 | | Tangent | \`tana\` | \`tan(a)\` |
480 | | InverseSine | \`asina\` | \`asin(a)\` |
481 | | InverseCosine | \`acosa\` | \`acos(a)\` |
482 | | InverseTangent | \`atana\` | \`atan(a)\` |
483 | | InverseTangent2 | \`aatanb\` | \`atan(a,b)\` |
484 | | Exponential | \`expa\` | \`exp(a)\` |
485 | | Logarithm | \`loga\` | \`log(a)\` |
486 | | Exponential2 | \`exp2a\` | \`exp2(a)\` |
487 | | Logarithm2 | \`log2a\` | \`log2(a)\` |
488 | | SquareRoot | \`sqrta\` | \`sqrt(a)\` |
489 | | InverseSquareRoot | \`inversesqrta\` | \`inversesqrt(a)\` |
490 | | Absolute | \`absa\` | \`abs(a)\` |
491 | | Sign | \`signa\` | \`sign(a)\` |
492 | | Floor | \`floora\` | \`floor(a)\` |
493 | | Ceiling | \`ceila\` | \`ceil(a)\` |
494 | | Fractional | \`fracta\` | \`fract(a)\` |
495 | | Multiply | \`a*b\` | \`a*b\` |
496 | | Divide | \`a/b\` | \`a/b\` |
497 | | Add | \`a+b\` | \`a+b\` |
498 | | Subtract | \`a-b\` | \`a-b\` |
499 | | LessThan | \`ab\` | \`a>b\` |
501 | | LessThanEqual | \`a<=b\` | \`a<=b\` |
502 | | GreaterThanEqual | \`a>=b\` | \`a>=b\` |
503 | | Equal | \`aisb\` | \`a==b\` |
504 | | NotEqual | \`anotb\` | \`a!=b\` |
505 | | And | \`a&&b\` | \`a&&b\` |
506 | | Or | \`a\\|\\|b\` | \`a\\|b\` |
507 | | Exponentiate | \`apowb\` | \`pow(a,b)\` |
508 | | Modulo | \`a%b\` | \`mod(a,b)\` |
509 | | Minimum | \`aminb\` | \`min(a,b)\` |
510 | | Maximum | \`amaxb\` | \`max(a,b)\` |
511 | | Conditional | \`a?b:c\` | \`a?b:c\` |
512 | | Clamp | \`aclampb:c\` | \`clamp(b,c,a)\` |
513 | | Step | \`astepb\` | \`step(b,a)\` |
514 | | SmoothStep | \`asmoothstepb:c\` | \`smoothstep(b,c,a)\` |
515 | | LinearInterpolate | \`amixb:c\` | \`mix(b,c,a)\` |`
516 | },
517 | {
518 | id: 21,
519 | input: `\
520 | |Small a|Small b|
521 | |:-|:-|
522 | |L:1 C:A|L:1 C:B|
523 |
524 | |Large header a|Large header b|
525 | |:-|:-|
526 | |Line:1 Column:A|Line:1 Column:B|`,
527 | expected: `\
528 | | Small a | Small b |
529 | |:----------------|:----------------|
530 | | L:1 C:A | L:1 C:B |
531 |
532 | | Large header a | Large header b |
533 | |:----------------|:----------------|
534 | | Line:1 Column:A | Line:1 Column:B |`
535 | },
536 | {
537 | id: 22,
538 | input: `\
539 | |Small a|Small b|Small c|
540 | |:-|:-|:-|
541 | |L:1 C:A|L:1 C:B|L:1 C:C|
542 |
543 | |Large header a|Large header b|
544 | |:-|:-|
545 | |Line:1 Column:A|Line:1 Column:B|`,
546 | expected: `\
547 | | Small a | Small b | Small c |
548 | |:----------------|:----------------|:--------|
549 | | L:1 C:A | L:1 C:B | L:1 C:C |
550 |
551 | | Large header a | Large header b |
552 | |:----------------|:----------------|
553 | | Line:1 Column:A | Line:1 Column:B |`
554 | },
555 | {
556 | id: 23,
557 | input: `\
558 | |Small a|Small b|Small c|
559 | |:-|:-|:-|
560 | |L:1 C:A|L:1 C:B|L:1 C:C|
561 |
562 | |Large header a|Large header b|
563 | |:-|:-|
564 | |Line:1 Column:A|Line:1 Column:B|`,
565 | expected: `\
566 | | Small a | Small b | Small c |
567 | |:----------|:----------|:----------|
568 | | L:1 C:A | L:1 C:B | L:1 C:C |
569 |
570 | | Large header a | Large header b |
571 | |:----------------|:----------------|
572 | | Line:1 Column:A | Line:1 Column:B |`,
573 | settings: {
574 | enable: true,
575 | enableSort: true,
576 | spacePadding: 1,
577 | keepFirstAndLastPipes: true,
578 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Left,
579 | markdownGrammarScopes: ['markdown'],
580 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
581 | removeColonsIfSameAsDefault: false,
582 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameTableSize,
583 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
584 | allowEmptyRows: true
585 | }
586 | },
587 | {
588 | id: 24,
589 | input: `\
590 | | Topic| Status| Notes |
591 | |:---|:----|:-|
592 | | Is source control used?| NO| |
593 | | Are changes peer reviewed? | PARTIAL | |
594 |
595 | | Topic| Status|
596 | |:-|:--|
597 | | Is Iot used?| NO|`,
598 | expected: `\
599 | | Topic | Status | Notes |
600 | |:---------------------------|:--------|:------|
601 | | Is source control used? | NO | |
602 | | Are changes peer reviewed? | PARTIAL | |
603 |
604 | | Topic | Status |
605 | |:-------------------------|:------------------|
606 | | Is Iot used? | NO |`,
607 | settings: {
608 | enable: true,
609 | enableSort: true,
610 | spacePadding: 1,
611 | keepFirstAndLastPipes: true,
612 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Left,
613 | markdownGrammarScopes: ['markdown'],
614 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
615 | removeColonsIfSameAsDefault: false,
616 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameTableSize,
617 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
618 | allowEmptyRows: true
619 | }
620 | },
621 | {
622 | id: 25,
623 | input: `\
624 | | Topic| Status| Notes |
625 | |:---|:----|:-|
626 | | Is source control used?| NO| |
627 | | Are changes peer reviewed? | PARTIAL | |
628 |
629 | | Topic| Status|
630 | |:-|:--|
631 | | Is Iot used?| NO|`,
632 | expected: `\
633 | | Topic | Status | Notes |
634 | |:-----------------------------|:----------|:--------|
635 | | Is source control used? | NO | |
636 | | Are changes peer reviewed? | PARTIAL | |
637 |
638 | | Topic | Status |
639 | |:----------------------------|:---------------------|
640 | | Is Iot used? | NO |`,
641 | settings: {
642 | enable: true,
643 | enableSort: true,
644 | spacePadding: 2,
645 | keepFirstAndLastPipes: true,
646 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Left,
647 | markdownGrammarScopes: ['markdown'],
648 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
649 | removeColonsIfSameAsDefault: false,
650 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameTableSize,
651 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
652 | allowEmptyRows: true
653 | }
654 | },
655 | {
656 | id: 26,
657 | input: `\
658 | |1eft header|Center header |Right header|Default header|
659 | |:-|::|-:|-|
660 | |Line:1 Column:A|Line:1 Column:B|Line:1 Column:C|Line:1 Column:D|
661 | |Line:2 Col:A|Line:2 Col:B|Line:2 Col:C|Line:2 Col:D|
662 | |L:3 C:A|L:3 C:B|L:3 C:C|L:3 C:D|
663 |
664 | | Topic | Status | Notes |
665 | |----------------------------|-----------|-------|
666 | | Is source control used? | NO | |
667 | | Are changes peer reviewed? | PARTIAL | |`
668 | , expected: `\
669 | | 1eft header | Center header | Right header | Default header |
670 | |:----------------|:---------------:|----------------:|-----------------|
671 | | Line:1 Column:A | Line:1 Column:B | Line:1 Column:C | Line:1 Column:D |
672 | | Line:2 Col:A | Line:2 Col:B | Line:2 Col:C | Line:2 Col:D |
673 | | L:3 C:A | L:3 C:B | L:3 C:C | L:3 C:D |
674 |
675 | | Topic | Status | Notes |
676 | |-------------------------------------|-----------------|---------------|
677 | | Is source control used? | NO | |
678 | | Are changes peer reviewed? | PARTIAL | |`,
679 | settings: {
680 | enable: true,
681 | enableSort: true,
682 | spacePadding: 1,
683 | keepFirstAndLastPipes: true,
684 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Left,
685 | markdownGrammarScopes: ['markdown'],
686 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
687 | removeColonsIfSameAsDefault: false,
688 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameTableSize,
689 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
690 | allowEmptyRows: true
691 | }
692 | },
693 | {
694 | id: 27,
695 | input: `\
696 | | a | b |
697 | |------------|---------------|
698 | | 1234567890 | 1234567890 |`,
699 | expected: `\
700 | | a | b |
701 | |------------|------------|
702 | | 1234567890 | 1234567890 |`
703 | },
704 | {
705 | id: 28,
706 | input: `\
707 | | | |
708 | |------------|---------------|
709 | | 1234567890 | 1234567890 |`,
710 | expected: `\
711 | | | |
712 | |------------|------------|
713 | | 1234567890 | 1234567890 |`
714 | },
715 | {
716 | id: 29,
717 | input: `\
718 | | Text | Result |
719 | |----------|-------------------|
720 | | \`\` $\` \`\` | text before match |`,
721 | expected: `\
722 | | Text | Result |
723 | |----------|-------------------|
724 | | \`\` $\` \`\` | text before match |`
725 | },
726 | {
727 | id: 30,
728 | input: `\
729 | |a|
730 | |-|
731 | |a|`,
732 | expected: `\
733 | | a |
734 | |---|
735 | | a |`
736 | },
737 | {
738 | id: 31,
739 | input: `\
740 | | symbol | name
741 | |-|-
742 | | " | quote
743 | | « | left-pointing double angle quote
744 | | \` | backtick`,
745 | expected: `\
746 | | symbol | name |
747 | |--------|----------------------------------|
748 | | " | quote |
749 | | « | left-pointing double angle quote |
750 | | \` | backtick |`
751 | },
752 | {
753 | id: 32,
754 | input: `\
755 | * Stuff:
756 | |One|Two|Three|
757 | |---|---|-----|
758 | |'1'|'2'|'3'|`,
759 | expected: `\
760 | * Stuff:
761 | | One | Two | Three |
762 | |-----|-----|-------|
763 | | '1' | '2' | '3' |`
764 | },
765 | {
766 | id: 33,
767 | input: `\
768 | 1. One | Two | Three
769 | --- | --- | -----
770 | '1' | '2' | '3'`,
771 | expected: `\
772 | 1. | One | Two | Three |
773 | |-----|-----|-------|
774 | | '1' | '2' | '3' |`
775 | },
776 | {
777 | id: 34,
778 | input: `\
779 | * |One|Two|Three|
780 | |---|---|-----|
781 | |'1'|'2'|'3'|`,
782 | expected: `\
783 | * | One | Two | Three |
784 | |-----|-----|-------|
785 | | '1' | '2' | '3' |`
786 | },
787 | {
788 | id: 35,
789 | input: `\
790 | |abc|def|
791 | |---|---|
792 | |bar|baz|
793 | > bar`,
794 | expected: `\
795 | | abc | def |
796 | |-----|-----|
797 | | bar | baz |
798 | > bar`
799 | },
800 | {
801 | id: 36,
802 | input: `\
803 | | abc | def |
804 | | ------ | -------- |`,
805 | expected: `\
806 | | abc | def |
807 | |-----|-----|`
808 | },
809 | {
810 | id: 37,
811 | input: `\
812 | | f\\|oo |
813 | | ------ |
814 | | b \`\\|\` az |
815 | | b **\\|** im |`,
816 | expected: `\
817 | | f\\|oo |
818 | |-------------|
819 | | b \`\\|\` az |
820 | | b **\\|** im |`
821 | },
822 | {
823 | id: 38,
824 | input: `\
825 | // Not a table
826 | | abc | def |
827 | | --- |
828 | | bar |`,
829 | expected: `\
830 | // Not a table
831 | | abc | def |
832 | | --- |
833 | | bar |`
834 | },
835 | {
836 | id: 39,
837 | input: `\
838 | | abc | def |
839 | | --- | --- |
840 | | bar |
841 | | bar | baz | boo |`,
842 | expected: `\
843 | | abc | def |
844 | |-----|-----|
845 | | bar | |
846 | | bar | baz |`
847 | },
848 | {
849 | id: 40,
850 | input: `\
851 | (Paragraph omitted) blah blah blah:
852 |
853 | with mask:
854 | # x y and out are all 16-bit so are subdivided at:
855 | # | mask[0] mask[1] mask[3] |
856 | # | 0-3 | 4-7 | 8-11 | 12-15 |
857 | x = PartitionedSignal(16) # identical except for mask
858 | y = PartitionedSignal(16) # identical except for mask
859 | out = PartitionedSignal(16) # identical except for mask`,
860 | expected: `\
861 | (Paragraph omitted) blah blah blah:
862 |
863 | with mask:
864 | # x y and out are all 16-bit so are subdivided at:
865 | # | mask[0] mask[1] mask[3] |
866 | # | 0-3 | 4-7 | 8-11 | 12-15 |
867 | x = PartitionedSignal(16) # identical except for mask
868 | y = PartitionedSignal(16) # identical except for mask
869 | out = PartitionedSignal(16) # identical except for mask`,
870 | },
871 | {
872 | id: 41,
873 | input: `\
874 | | <> | <> | <>
875 | | --- | --- | ---
876 | | <> | <> | <>`,
877 | expected: `\
878 | | <> | <> | <> |
879 | |-----------|-----------|-----------|
880 | | <> | <> | <> |`,
881 | },
882 | {
883 | id: 42,
884 | settings: {
885 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None
886 | },
887 | input: `\
888 | | App name| Default status | Requirements |
889 | |---|---|----|
890 | | App one| Enabled| None|
891 | | App ten| Disabled| Use on Thursdays |
892 | | App twenty | Enabled| If you are going to use this application, ensure you have fulfilled the prerequisites and can no longer use any other option |`,
893 | expected: `\
894 | | App name | Default status | Requirements |
895 | |------------|----------------|------------------------------------------------------------------------------------------------------------------------------|
896 | | App one | Enabled | None |
897 | | App ten | Disabled | Use on Thursdays |
898 | | App twenty | Enabled | If you are going to use this application, ensure you have fulfilled the prerequisites and can no longer use any other option |`
899 | },
900 | {
901 | id: 43,
902 | settings: {
903 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.EditorWordWrap,
904 | },
905 | input: `\
906 | | App name| Default status | Requirements |
907 | |---|---|----|
908 | | App one| Enabled| None|
909 | | App ten| Disabled| Use on Thursdays |
910 | | App twenty | Enabled| If you are going to use this application, ensure you have fulfilled the prerequisites and can no longer use any other option |`,
911 | expected: `\
912 | | App name | Default status | Requirements |
913 | |------------|----------------|------------------------------------------------|
914 | | App one | Enabled | None |
915 | | App ten | Disabled | Use on Thursdays |
916 | | App twenty | Enabled | If you are going to use this application, ensure you have fulfilled the prerequisites and can no longer use any other option |`
917 | },
918 | {
919 | id: 44,
920 | settings: {
921 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.HeaderRowLength
922 | },
923 | input: `\
924 | | App name| Default status | Requirements |
925 | |---|---|----|
926 | | App one| Enabled| None|
927 | | App ten| Disabled| Use on Thursdays |
928 | | App twenty | Enabled| If you are going to use this application, ensure you have fulfilled the prerequisites and can no longer use any other option |`,
929 | expected: `\
930 | | App name | Default status | Requirements |
931 | |------------|----------------|--------------|
932 | | App one | Enabled | None |
933 | | App ten | Disabled | Use on Thursdays |
934 | | App twenty | Enabled | If you are going to use this application, ensure you have fulfilled the prerequisites and can no longer use any other option |`
935 | }
936 | ];
--------------------------------------------------------------------------------
/src/test/files/tables2.md:
--------------------------------------------------------------------------------
1 |
2 | | Host | VM | IP | Núcleos | RAM | Disco | Finalidade | Responsável |
3 | |:--------:|:--------:|:-------------|:-------:|:---:|:-----:|:-------------------|:------------|
4 | | alsrv414 | alsrv903 | 172.20.48.3 | 2 | 8GB | 40GB | CaaS Adm | SSys |
5 | | | alsrv904 | 172.20.48.4 | 2 | 8GB | 40GB | CaaS M1 | SSys |
6 | | | alsrv905 | 172.20.48.5 | 2 | 8GB | 40GB | CaaS W1 | SSys |
7 | | | alsrv906 | 172.20.48.6 | 2 | 8GB | 40GB | CaaS W2 | SSys |
8 | | alsrv415 | | | | | | | adcarvalho |
9 | | alsrv416 | alsrv907 | 172.20.48.7 | | | | OpenShift M1 | SManager |
10 | | alsrv417 | alsrv908 | 172.20.48.8 | | | | OpenShift M2 | SManager |
11 | | alsrv418 | alsrv909 | 172.20.48.9 | | | | OpenShift I1 | SManager |
12 | | | alsrv910 | 172.20.48.10 | | | | OpenShift I2 | SManager |
13 | | alsrv419 | | | | | | | adcarvalho |
14 | | alsrv420 | alsrv911 | 172.20.48.11 | | | | OpenShift AppNode1 | SManager |
15 | | | alsrv912 | 172.20.48.12 | | | | OpenShift AppNode2 | SManager |
16 | | alsrv421 | alsrv913 | 172.20.48.13 | | | | OpenShift Bastion | SManager |
17 | | alsrv422 | alsrv995 | 172.20.48.95 | 2 | 8GB | 100GB | NAM | fxcrespo |
18 | | | alsrv990 | 172.20.48.90 | 2 | 8GB | 40GB | Docker Swarm | adcarvalho |
19 | | | alsrv992 | 172.20.48.92 | 2 | 8GB | 40GB | Docker Swarm | adcarvalho |
20 | | | alsrv993 | 172.20.48.93 | 2 | 8GB | 40GB | Docker Swarm | adcarvalho |
21 |
22 |
23 |
24 |
25 | | | |
26 | |-----------------|---------|
27 | | abc | defghi |
28 | | | |
29 | | | |
30 |
31 | | Foo | Bar |
32 | | - | - |
33 | |Baz|Qux|
34 |
35 | | Foo | Bar |
36 | |-:|-|
37 | |Baz|Qux|
38 |
39 |
40 |
41 |
42 | | Hostname | IP | Usado? |
43 | |----------|--------------|:-------------:|
44 | | alsrv903 | 172.20.48.3 | POC KUB |
45 | | alsrv904 | 172.20.48.4 | POC KUB |
46 | | alsrv905 | 172.20.48.5 | POC KUB |
47 | | alsrv906 | 172.20.48.6 | POC KUB |
48 | | alsrv907 | 172.20.48.7 | POC KUB |
49 | | alsrv908 | 172.20.48.8 | POC KUB |
50 | | alsrv909 | 172.20.48.9 | POC KUB |
51 | | alsrv910 | 172.20.48.10 | POC KUB |
52 | | alsrv911 | 172.20.48.11 | POC KUB |
53 | | alsrv912 | 172.20.48.12 | POC KUB |
54 | | alsrv913 | 172.20.48.13 | POC KUB |
55 | | alsrv914 | 172.20.48.14 | POC KUB |
56 | | alsrv923 | 172.20.48.23 | - |
57 | | alsrv924 | 172.20.48.24 | - |
58 | | alsrv925 | 172.20.48.25 | - |
59 | | alsrv926 | 172.20.48.26 | archivematica |
60 | | alsrv950 | 172.20.48.50 | Traefik |
61 | | alsrv951 | 172.20.48.51 | Docker 01 |
62 | | alsrv952 | 172.20.48.52 | Docker 02 |
63 | | alsrv953 | 172.20.48.53 | Docker 03 |
64 | | alsrv954 | 172.20.48.54 | Docker 04 |
65 | | alsrv959 | 172.20.48.59 | NFS-Server |
66 | | alsrv990 | 172.20.48.90 | Test DOCKER01 |
67 | | alsrv991 | 172.20.48.91 | ddo@atom |
68 | | alsrv992 | 172.20.48.92 | Test DOCKER02 |
69 | | alsrv993 | 172.20.48.93 | Test DOCKER03 |
70 | | alsrv994 | 172.20.48.94 | Test DOCKER04 |
71 | | alsrv995 | 172.20.48.95 | NAM DEV |
72 |
73 |
74 | | Configuração | Valor |
75 | |----------------------------------|--------------------------------------------|
76 | | hostname | um daqueles da lista que passei (alsrv9xx) |
77 | | IP | um daqueles da lista que passei |
78 | | CIDR | 172.20.0.0/16 |
79 | | mascara | 255.255.0.0 |
80 | | domainname | al.sp.gov.br |
81 | | DNS 1 | 172.20.0.15 |
82 | | DNS 2 | 172.20.0.9 |
83 | | gateway | 172.20.30.100 |
84 | | DNS search list ou search domain | al.sp.gov.br |
--------------------------------------------------------------------------------
/src/test/files/tables3.md:
--------------------------------------------------------------------------------
1 | | Text | Result |
2 | |-----------|------------|
3 | | `` $` `` | text before match |
4 | | `` $|` `` | text before match text before match text before match text before match text before match text before match text before match |
5 |
6 | | 12345678 | 12345678 | 12345678 |
7 | |:--------:|:---------|---------:|
8 | | 12345678 | 12345678 | 12345678 |
9 |
10 | | Topic | Status | Notes |
11 | |-------------------------|------------|--|
12 | | Issourcecontrolused? | `NO`| |
13 | | Arechangespeerreviewed? | `PARTIAL`| |
14 |
15 | | 1234567890 | 1234567890 | 1234567890 |
16 | |:----------:|:-----------|-----------:|
17 | | 1234567890 | 1234567890 | 1234567890 |
18 |
19 |
20 | # Incorrectly render but its a font problem #21
21 | # https://github.com/fcrespo82/vscode-markdown-table-formatter/issues/21
22 | | code | 描述 | 详细解释 |
23 | |:-----|:-----------------|:-----------|
24 | | 200 | 成功 | 成功 |
25 | | 400 | 错误请求 | 该请求是无效的,详细的错误信息会说明原因 |
26 | | 401 | 验证错误 | 验证失败,详细的错误信息会说明原因 |
27 | | 403 | 被拒绝 | 被拒绝调用,详细的错误信息会说明原因 |
28 | | 404 | 无法找到 | 资源不存在 |
29 | | 429 | 过多的请求 | 超出了调用频率限制,详细的错误信息会说明原因 |
30 | | 500 | 内部服务错误 | 服务器内部出错了,请联系我们尽快解决问题 |
31 | | 504 | 内部服务响应超时 | 服务器在运行,本次请求响应超时,请稍后重试 |
32 |
33 | | a | a | a | a |
34 | |-|-|
35 | | bb | bb |
36 | | bb | bb |
37 |
38 |
39 | | a | a | a | a |
40 | |
41 | |
42 | |
43 | |
44 |
45 |
46 | | a | a | a | LOOOOng |
47 | |-:|-:|-:|-:|
48 | |
49 | |
50 | |
51 |
--------------------------------------------------------------------------------
/src/test/runTest.ts:
--------------------------------------------------------------------------------
1 | import * as path from 'path';
2 | import { runTests } from '@vscode/test-electron';
3 |
4 | async function main() {
5 | try {
6 | // The folder containing the Extension Manifest package.json
7 | // Passed to `--extensionDevelopmentPath`
8 | const extensionDevelopmentPath = path.resolve(__dirname, '../../');
9 |
10 | // The path to test runner
11 | // Passed to --extensionTestsPath
12 | const extensionTestsPath = path.resolve(__dirname, './suite/index');
13 |
14 | // Download VS Code, unzip it and run the integration test
15 | await runTests({ extensionDevelopmentPath, extensionTestsPath });
16 | } catch (err) {
17 | console.error(err);
18 | console.error('Failed to run tests');
19 | process.exit(1);
20 | }
21 | }
22 |
23 | main();
24 |
--------------------------------------------------------------------------------
/src/test/suite/extension.test.ts:
--------------------------------------------------------------------------------
1 | import * as assert from 'assert';
2 | import * as vscode from 'vscode';
3 | import {MarkdownTableFormatterProvider} from '../../formatter/MarkdownTableFormatterProvider';
4 | import MarkdownTableFormatterSettings, {MarkdownTableFormatterDefaultTableJustification, MarkdownTableFormatterDelimiterRowPadding, MarkdownTableFormatterGlobalColumnSizes, MarkdownTableFormatterLimitLastRowLength} from '../../formatter/MarkdownTableFormatter.types';
5 | import {pad} from '../../MarkdownTableUtils';
6 | import {testTables} from '../files/tables';
7 |
8 | suite('Extension Test Suite', () => {
9 |
10 | suiteSetup(() => {
11 | vscode.workspace.registerTextDocumentContentProvider('test-table', testTablesProvider);
12 | vscode.window.showInformationMessage('Starting all tests.');
13 | });
14 |
15 | suiteTeardown(() => {
16 | vscode.window.showInformationMessage('Finalizing all tests.');
17 | });
18 |
19 | const defaultTestSettings: MarkdownTableFormatterSettings = {
20 | enable: true,
21 | enableSort: true,
22 | spacePadding: 1,
23 | keepFirstAndLastPipes: true,
24 | defaultTableJustification: MarkdownTableFormatterDefaultTableJustification.Left,
25 | markdownGrammarScopes: ['markdown'],
26 | limitLastColumnLength: MarkdownTableFormatterLimitLastRowLength.None,
27 | removeColonsIfSameAsDefault: false,
28 | globalColumnSizes: MarkdownTableFormatterGlobalColumnSizes.SameColumnSize,
29 | delimiterRowPadding: MarkdownTableFormatterDelimiterRowPadding.None,
30 | allowEmptyRows: true
31 | };
32 |
33 | testTables.forEach((testTable, i) => {
34 |
35 | test(`Should format correctly table ${pad(String(testTable.id), 2)}`, async () => {
36 | const testSettings: MarkdownTableFormatterSettings = { ...defaultTestSettings, ...testTable.settings };
37 |
38 | const formatterProvider = new MarkdownTableFormatterProvider(testSettings)
39 |
40 | const uri = vscode.Uri.parse('test-table:' + i);
41 | const textEditor = await vscode.window.showTextDocument(uri);
42 | await vscode.languages.setTextDocumentLanguage(textEditor.document, "markdown")
43 |
44 | const fullDocumentRange = textEditor.document.validateRange(new vscode.Range(0, 0, textEditor.document.lineCount + 1, 0));
45 | const textEdits = formatterProvider.formatDocument(textEditor.document, fullDocumentRange)
46 | const edit = new vscode.WorkspaceEdit();
47 |
48 | for (const textEdit of textEdits) {
49 | edit.replace(uri, textEdit.range, textEdit.newText);
50 | }
51 | await vscode.workspace.applyEdit(edit);
52 | assert.equal(textEditor.document.getText(), testTable.expected)
53 | });
54 | });
55 | });
56 |
57 | const testTablesProvider = new class implements vscode.TextDocumentContentProvider {
58 | provideTextDocumentContent(uri: vscode.Uri): string {
59 | return testTables[Number(uri.path)].input;
60 | }
61 | };
--------------------------------------------------------------------------------
/src/test/suite/index.ts:
--------------------------------------------------------------------------------
1 | import * as glob from 'glob';
2 | import * as Mocha from 'mocha';
3 | import * as path from 'path';
4 |
5 | export function run(): Promise {
6 | // Create the mocha test
7 | const mocha = new Mocha({
8 | ui: 'tdd',
9 | color: true
10 | });
11 |
12 | const testsRoot = path.resolve(__dirname, '..');
13 |
14 | return new Promise((c, e) => {
15 | glob('**/**.test.js', { cwd: testsRoot }, (err, files) => {
16 | if (err) {
17 | return e(err);
18 | }
19 |
20 | // Add files to the test suite
21 | files.forEach(f => mocha.addFile(path.resolve(testsRoot, f)));
22 |
23 | try {
24 | // Run the mocha test
25 | mocha.run(failures => {
26 | if (failures > 0) {
27 | e(new Error(`${failures} tests failed.`));
28 | } else {
29 | c();
30 | }
31 | });
32 | } catch (err) {
33 | e(err);
34 | }
35 | });
36 | });
37 | }
38 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "module": "commonjs",
4 | "target": "es6",
5 | "outDir": "out",
6 | "lib": [
7 | "es7",
8 | "es2019"
9 | ],
10 | "sourceMap": true,
11 | "rootDir": "src",
12 | /* Strict Type-Checking Option */
13 | "strict": true, /* enable all strict type-checking options */
14 | /* Additional Checks */
15 | // "noUnusedLocals": true /* Report errors on unused locals. */
16 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
17 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
18 | // "noUnusedParameters": true, /* Report errors on unused parameters. */
19 | },
20 | "exclude": [
21 | "node_modules",
22 | ".vscode-test"
23 | ],
24 | "include": [
25 | "src/**/*.ts",
26 | "./node_modules/vscode/vscode.d.ts",
27 | "./node_modules/vscode/lib/*",
28 | ]
29 | }
--------------------------------------------------------------------------------