From 83d96e2bbbcb4e2bab96c0b2897c5f35a65d0adc Mon Sep 17 00:00:00 2001 From: Ethan P Date: Mon, 5 Oct 2020 18:40:38 -0700 Subject: [PATCH 001/243] Rename SASS tests to SCSS, since they're using SCSS syntax --- .../highlighted/{SASS/example.sass => SCSS/example.scss} | 0 tests/syntax-tests/source/{SASS => SCSS}/LICENSE.md | 0 .../syntax-tests/source/{SASS/example.sass => SCSS/example.scss} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename tests/syntax-tests/highlighted/{SASS/example.sass => SCSS/example.scss} (100%) rename tests/syntax-tests/source/{SASS => SCSS}/LICENSE.md (100%) rename tests/syntax-tests/source/{SASS/example.sass => SCSS/example.scss} (100%) diff --git a/tests/syntax-tests/highlighted/SASS/example.sass b/tests/syntax-tests/highlighted/SCSS/example.scss similarity index 100% rename from tests/syntax-tests/highlighted/SASS/example.sass rename to tests/syntax-tests/highlighted/SCSS/example.scss diff --git a/tests/syntax-tests/source/SASS/LICENSE.md b/tests/syntax-tests/source/SCSS/LICENSE.md similarity index 100% rename from tests/syntax-tests/source/SASS/LICENSE.md rename to tests/syntax-tests/source/SCSS/LICENSE.md diff --git a/tests/syntax-tests/source/SASS/example.sass b/tests/syntax-tests/source/SCSS/example.scss similarity index 100% rename from tests/syntax-tests/source/SASS/example.sass rename to tests/syntax-tests/source/SCSS/example.scss From 894d3f1722f8d2ab760da0a1ea01e1f263ae16fd Mon Sep 17 00:00:00 2001 From: Ethan P Date: Mon, 5 Oct 2020 18:59:14 -0700 Subject: [PATCH 002/243] Replace SCSS example with unlicensed one --- .../highlighted/SCSS/example.scss | 95 +++++++++++++++---- tests/syntax-tests/source/SCSS/LICENSE.md | 25 ----- tests/syntax-tests/source/SCSS/example.scss | 91 +++++++++++++++--- 3 files changed, 156 insertions(+), 55 deletions(-) delete mode 100644 tests/syntax-tests/source/SCSS/LICENSE.md diff --git a/tests/syntax-tests/highlighted/SCSS/example.scss b/tests/syntax-tests/highlighted/SCSS/example.scss index ed78c867..7ba949d8 100644 --- a/tests/syntax-tests/highlighted/SCSS/example.scss +++ b/tests/syntax-tests/highlighted/SCSS/example.scss @@ -1,19 +1,82 @@ -@mixin button-base() { - @include typography(button); - @include ripple-surface; - @include ripple-radius-bounded; +@import 'fonts'; - display: inline-flex; - position: relative; - height: $button-height; - border: none; - vertical-align: middle; +$theme_dark: ( + "background-color": null, +); +$theme_main: ( + "text-size": 3em, + "text-color": black, + "text-shadow": #36ad 0px 0px 3px, + "card-background": #d6f, + "card-shadow": #11121212 0px 0px 2px 1px, + "card-padding": 1rem, + "card-margin": 0.5in, + "image-width": 600px, + "image-height": 100vh, + "background-color": #dedbef, + "i-ran-out-of-placeholders-for-units": (1vw 100% 60pt), +); - &:hover { cursor: pointer; } +$current_theme: $theme_main; - &:disabled { - color: $mdc-button-disabled-ink-color; - cursor: default; - pointer-events: none; - } -} +@mixin themed() { + $current_theme: $theme_main !global; + @content; + + @media (prefers-color-scheme: dark) { + $current_theme: $theme_dark !global; + @content; + } +  + .#{"dark"} & { + $current_theme: $theme_dark !global; + @content; + } +} + +@function theme($variable) { + @if map-has_key($current_theme, $variable) { + @return map-get($current_theme, $variable); + } @else { + @error "Unknown theme variable: #{$variable}"; + } +} + +body { + @include themed { + background-color: theme('background-color'); + background-image: url("https://github.com/sharkdp/bat/raw/master/doc/logo-header.svg"); + } +  + header[data-selectable="false"] { + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: /* CSS comment */ none; + cursor: default !important; // SCSS comment + } +  + > div { + border: #04f 1px solid; +  + &::after { + content: 'Pseudo'; + color: #2F5F7F; + box-sizing: border-box; + } + } +} + +@keyframes rotate { + 0% { + transform: rotate(0deg); + } + 50% { + transform: rotate(180deg)} + 100% {transform: rotate(0rad);} +} + +@font-face { + font-family: 'Example Font'; + src: url(example.ttf) format('ttf'); + src: local('Comic Sans MS'); +} diff --git a/tests/syntax-tests/source/SCSS/LICENSE.md b/tests/syntax-tests/source/SCSS/LICENSE.md deleted file mode 100644 index ee554ef1..00000000 --- a/tests/syntax-tests/source/SCSS/LICENSE.md +++ /dev/null @@ -1,25 +0,0 @@ -This file has been copied from https://sass-lang.com/documentation/syntax - - -LICENSE: - - -Copyright (c) 2006-2018 Hampton Catlin, Natalie Weizenbaum, Chris Eppstein, and -Jina Anne - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tests/syntax-tests/source/SCSS/example.scss b/tests/syntax-tests/source/SCSS/example.scss index 9f948578..14b622e0 100644 --- a/tests/syntax-tests/source/SCSS/example.scss +++ b/tests/syntax-tests/source/SCSS/example.scss @@ -1,19 +1,82 @@ -@mixin button-base() { - @include typography(button); - @include ripple-surface; - @include ripple-radius-bounded; +@import 'fonts'; - display: inline-flex; - position: relative; - height: $button-height; - border: none; - vertical-align: middle; +$theme_dark: ( + "background-color": null, +); +$theme_main: ( + "text-size": 3em, + "text-color": black, + "text-shadow": #36ad 0px 0px 3px, + "card-background": #d6f, + "card-shadow": #11121212 0px 0px 2px 1px, + "card-padding": 1rem, + "card-margin": 0.5in, + "image-width": 600px, + "image-height": 100vh, + "background-color": #dedbef, + "i-ran-out-of-placeholders-for-units": (1vw 100% 60pt), +); - &:hover { cursor: pointer; } +$current_theme: $theme_main; - &:disabled { - color: $mdc-button-disabled-ink-color; - cursor: default; - pointer-events: none; +@mixin themed() { + $current_theme: $theme_main !global; + @content; + + @media (prefers-color-scheme: dark) { + $current_theme: $theme_dark !global; + @content; + } + + .#{"dark"} & { + $current_theme: $theme_dark !global; + @content; } } + +@function theme($variable) { + @if map-has_key($current_theme, $variable) { + @return map-get($current_theme, $variable); + } @else { + @error "Unknown theme variable: #{$variable}"; + } +} + +body { + @include themed { + background-color: theme('background-color'); + background-image: url("https://github.com/sharkdp/bat/raw/master/doc/logo-header.svg"); + } + + header[data-selectable="false"] { + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: /* CSS comment */ none; + cursor: default !important; // SCSS comment + } + + > div { + border: #04f 1px solid; + + &::after { + content: 'Pseudo'; + color: #2F5F7F; + box-sizing: border-box; + } + } +} + +@keyframes rotate { + 0% { + transform: rotate(0deg); + } + 50% { + transform: rotate(180deg)} + 100% {transform: rotate(0rad);} +} + +@font-face { + font-family: 'Example Font'; + src: url(example.ttf) format('ttf'); + src: local('Comic Sans MS'); +} From f41bf2082a06c06ad5d79ef9b01b12094742499b Mon Sep 17 00:00:00 2001 From: Matthew Zegar Date: Mon, 5 Oct 2020 18:26:05 -0700 Subject: [PATCH 003/243] Added CSS syntax highlight file and folder --- tests/syntax-tests/source/CSS/style.css | 115 ++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 tests/syntax-tests/source/CSS/style.css diff --git a/tests/syntax-tests/source/CSS/style.css b/tests/syntax-tests/source/CSS/style.css new file mode 100644 index 00000000..b1722114 --- /dev/null +++ b/tests/syntax-tests/source/CSS/style.css @@ -0,0 +1,115 @@ +/*Scrolling*/ +html { scroll-behavior: smooth; } + +/*Header text*/ +.jumbotron { + background-image: linear-gradient(90deg, #849EB5, #30394A); + padding-bottom: 20px; + padding-top: 20px; + text-shadow: 0px 2px 4px #000000; +} + +.container { + margin-top: -25px; +} + +/*Background related*/ +body { + background: #161616; +} + +/*Text related CSS*/ +h4 { + font-size: 70px; + color: #FFFFFF; + font-family: News Cycle, serif; +} + +h3 { + color: #e5e5e5; +} + +p { + font-size: 17px; + font-family: News Cycle, serif; + color: #DEDEDE; +} + +p2 { + font-size: 24px; + color: #DEDEDE; + font-family: News Cycle, serif; +} + +date { + font-family: News Cycle, serif; + font-style: italic; + font-size: 17px; + color: #DEDEDE; +} + +jobtitle { + font-size: 17px; + font-weight: bold; + font-family: News Cycle, serif; + color: #DEDEDE; +} + +jobtilenolink { + font-size: 17px; + font-weight: bold; + font-family: News Cycle, serif; + color: #DEDEDE; +} + +li { + font-family: News Cycle, serif; + color: #DEDEDE; +} + + + +a { + color: #4A8ECC; +} + +p a:visited { + color: #4A8ECC; +} + +.href { + color: #4A8ECC; +} + +a:visited { + color: #4A8ECC; +} + +p a:hover { + color: #4FB1F4; +} + +a:hover { + color: #4FB1F4; +} + +jobtitle:hover { + color: #4FB1F4; +} + +/*Section*/ +section { + background-color: #1B1B1B; + padding: 20px; + margin: -5px; + margin-bottom: 30px; + box-shadow: 0px 2px 4px rgba(0,0,0,0.3); +} + + +/*Icon related*/ +.icon { + position: relative; + top: 3px; + right: 5px; +} \ No newline at end of file From edf30e1fa17248a96abf30cd7ec786a4fc621a9d Mon Sep 17 00:00:00 2001 From: Matthew Zegar Date: Mon, 5 Oct 2020 18:41:51 -0700 Subject: [PATCH 004/243] Added missing highlighted generated test file --- tests/syntax-tests/highlighted/CSS/style.css | 115 +++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 tests/syntax-tests/highlighted/CSS/style.css diff --git a/tests/syntax-tests/highlighted/CSS/style.css b/tests/syntax-tests/highlighted/CSS/style.css new file mode 100644 index 00000000..bad4a4dd --- /dev/null +++ b/tests/syntax-tests/highlighted/CSS/style.css @@ -0,0 +1,115 @@ +/*Scrolling*/ +html { scroll-behavior: smooth; } + +/*Header text*/ +.jumbotron { + background-image: linear-gradient(90deg, #849EB5, #30394A); + padding-bottom: 20px; + padding-top: 20px; + text-shadow: 0px 2px 4px #000000; +} + +.container { + margin-top: -25px; +} + +/*Background related*/ +body { + background: #161616; +} + +/*Text related CSS*/ +h4 { + font-size: 70px; + color: #FFFFFF; + font-family: News Cycle, serif; +} + +h3 { + color: #e5e5e5; +} + +p { + font-size: 17px; + font-family: News Cycle, serif; + color: #DEDEDE; +} + +p2 { + font-size: 24px; + color: #DEDEDE; + font-family: News Cycle, serif; +} + +date { + font-family: News Cycle, serif; + font-style: italic; + font-size: 17px; + color: #DEDEDE; +} + +jobtitle { + font-size: 17px; + font-weight: bold; + font-family: News Cycle, serif; + color: #DEDEDE; +} + +jobtilenolink { + font-size: 17px; + font-weight: bold; + font-family: News Cycle, serif; + color: #DEDEDE; +} + +li { + font-family: News Cycle, serif; + color: #DEDEDE; +} + + + +a { + color: #4A8ECC; +} + +p a:visited { + color: #4A8ECC; +} + +.href { + color: #4A8ECC; +} + +a:visited { + color: #4A8ECC; +} + +p a:hover { + color: #4FB1F4; +} + +a:hover { + color: #4FB1F4; +} + +jobtitle:hover { + color: #4FB1F4; +} + +/*Section*/ +section { + background-color: #1B1B1B; + padding: 20px; + margin: -5px; + margin-bottom: 30px; + box-shadow: 0px 2px 4px rgba(0,0,0,0.3); +} + + +/*Icon related*/ +.icon { + position: relative; + top: 3px; + right: 5px; +} From a999975bc9f429ab4bdb16316dfe04e867eddfc5 Mon Sep 17 00:00:00 2001 From: sharkdp Date: Tue, 6 Oct 2020 06:58:23 +0200 Subject: [PATCH 005/243] Add missing newline --- tests/syntax-tests/source/CSS/style.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/syntax-tests/source/CSS/style.css b/tests/syntax-tests/source/CSS/style.css index b1722114..48f6267a 100644 --- a/tests/syntax-tests/source/CSS/style.css +++ b/tests/syntax-tests/source/CSS/style.css @@ -112,4 +112,4 @@ section { position: relative; top: 3px; right: 5px; -} \ No newline at end of file +} From 13e01841caa818f875fb6606d4e95cb516dffddc Mon Sep 17 00:00:00 2001 From: Gede Wahyu Date: Tue, 6 Oct 2020 13:13:59 +0800 Subject: [PATCH 006/243] pascal: add syntax highlight file --- .../syntax-tests/highlighted/Pascal/test.pas | 42 +++++++++++++++++++ tests/syntax-tests/source/Pascal/test.pas | 42 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Pascal/test.pas create mode 100644 tests/syntax-tests/source/Pascal/test.pas diff --git a/tests/syntax-tests/highlighted/Pascal/test.pas b/tests/syntax-tests/highlighted/Pascal/test.pas new file mode 100644 index 00000000..40659b86 --- /dev/null +++ b/tests/syntax-tests/highlighted/Pascal/test.pas @@ -0,0 +1,42 @@ +program Hello; +uses crt; + +type str = string[1]; + arr = array[1..20, 1..60] of char; + +var x, y:integer; + carr:arr; + c:char; + +Procedure start; +{comment here} +begin write (' Press enter to begin. '); +readln; +end; + +Function Valid (var choice:char): boolean; +begin  + valid:= false; + case choice of  + '1':valid:= true; + '2': valid:= true; + '3': valid:= true; + '4': valid:= true; + '5': valid:= true; + '6': valid:= true; + end; +end; + +begin + for y:=1 to 3 do + begin + writeln (y); + end; +  + repeat + writeln(y); + y := y + 1; + until y > 5; + writeln ('Hello World'); +end. + diff --git a/tests/syntax-tests/source/Pascal/test.pas b/tests/syntax-tests/source/Pascal/test.pas new file mode 100644 index 00000000..414e9e68 --- /dev/null +++ b/tests/syntax-tests/source/Pascal/test.pas @@ -0,0 +1,42 @@ +program Hello; +uses crt; + +type str = string[1]; + arr = array[1..20, 1..60] of char; + +var x, y:integer; + carr:arr; + c:char; + +Procedure start; +{comment here} +begin write (' Press enter to begin. '); +readln; +end; + +Function Valid (var choice:char): boolean; +begin + valid:= false; + case choice of + '1':valid:= true; + '2': valid:= true; + '3': valid:= true; + '4': valid:= true; + '5': valid:= true; + '6': valid:= true; + end; +end; + +begin + for y:=1 to 3 do + begin + writeln (y); + end; + + repeat + writeln(y); + y := y + 1; + until y > 5; + writeln ('Hello World'); +end. + From 44bfad24a1a7cd5ce9093926f85f22cca8386f7f Mon Sep 17 00:00:00 2001 From: "scott.eppler" Date: Tue, 6 Oct 2020 10:43:13 -0500 Subject: [PATCH 007/243] Add Terraform example file for Syntax Highlighting --- .../highlighted/Terraform/main.tf | 48 +++++++++++++++++++ tests/syntax-tests/source/Terraform/main.tf | 48 +++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Terraform/main.tf create mode 100644 tests/syntax-tests/source/Terraform/main.tf diff --git a/tests/syntax-tests/highlighted/Terraform/main.tf b/tests/syntax-tests/highlighted/Terraform/main.tf new file mode 100644 index 00000000..80fb6a92 --- /dev/null +++ b/tests/syntax-tests/highlighted/Terraform/main.tf @@ -0,0 +1,48 @@ +provider "github" { + organization = var.github_organization +} + +resource "tls_private_key" "deploy_key" { + algorithm = "RSA" + rsa_bits = "4096" +} + +resource "null_resource" "private_key_file" { + triggers = { + deploy_key = tls_private_key.deploy_key.private_key_pem + } + + provisioner "file" { + content = tls_private_key.deploy_key.private_key_pem + destination = "~/${var.repo_name}_deploy_key.pem" + + connection { + type = "ssh" + user = "centos" + private_key = var.terraform_ssh_key + host = var.server_ip + } + } + + provisioner "remote-exec" { + inline = [ + "sudo mv ~/${var.repo_name}_deploy_key.pem /app/ssh_keys/", + "sudo chmod 0400 /app/ssh_keys/${var.repo_name}_deploy_key.pem", + "sudo chown app:app /app/ssh_keys/${var.repo_name}_deploy_key.pem", + ] + + connection { + type = "ssh" + user = "centos" + private_key = var.terraform_ssh_key + host = var.server_ip + } + } +} + +resource "github_repository_deploy_key" "repo_deploy_key" { + title = "${var.env_name} Deploy Key" + repository = var.repo_name + key = tls_private_key.deploy_key.public_key_openssh + read_only = var.read_only +} diff --git a/tests/syntax-tests/source/Terraform/main.tf b/tests/syntax-tests/source/Terraform/main.tf new file mode 100644 index 00000000..2ff02b2c --- /dev/null +++ b/tests/syntax-tests/source/Terraform/main.tf @@ -0,0 +1,48 @@ +provider "github" { + organization = var.github_organization +} + +resource "tls_private_key" "deploy_key" { + algorithm = "RSA" + rsa_bits = "4096" +} + +resource "null_resource" "private_key_file" { + triggers = { + deploy_key = tls_private_key.deploy_key.private_key_pem + } + + provisioner "file" { + content = tls_private_key.deploy_key.private_key_pem + destination = "~/${var.repo_name}_deploy_key.pem" + + connection { + type = "ssh" + user = "centos" + private_key = var.terraform_ssh_key + host = var.server_ip + } + } + + provisioner "remote-exec" { + inline = [ + "sudo mv ~/${var.repo_name}_deploy_key.pem /app/ssh_keys/", + "sudo chmod 0400 /app/ssh_keys/${var.repo_name}_deploy_key.pem", + "sudo chown app:app /app/ssh_keys/${var.repo_name}_deploy_key.pem", + ] + + connection { + type = "ssh" + user = "centos" + private_key = var.terraform_ssh_key + host = var.server_ip + } + } +} + +resource "github_repository_deploy_key" "repo_deploy_key" { + title = "${var.env_name} Deploy Key" + repository = var.repo_name + key = tls_private_key.deploy_key.public_key_openssh + read_only = var.read_only +} From aa205c6a9face3a833d1b743562a93de8928cc9a Mon Sep 17 00:00:00 2001 From: Thiago Arrais Date: Tue, 6 Oct 2020 13:47:56 -0300 Subject: [PATCH 008/243] Add CSV syntax hightlighting test --- .../highlighted/CSV/comma_in_quotes.csv | 7 +++++ tests/syntax-tests/source/CSV/LICENSE.md | 27 +++++++++++++++++++ .../source/CSV/comma_in_quotes.csv | 7 +++++ 3 files changed, 41 insertions(+) create mode 100644 tests/syntax-tests/highlighted/CSV/comma_in_quotes.csv create mode 100644 tests/syntax-tests/source/CSV/LICENSE.md create mode 100644 tests/syntax-tests/source/CSV/comma_in_quotes.csv diff --git a/tests/syntax-tests/highlighted/CSV/comma_in_quotes.csv b/tests/syntax-tests/highlighted/CSV/comma_in_quotes.csv new file mode 100644 index 00000000..2ad5b914 --- /dev/null +++ b/tests/syntax-tests/highlighted/CSV/comma_in_quotes.csv @@ -0,0 +1,7 @@ +first,last,address,city,zip +John,Doe,120 any st.,"Anytown, WW",08123 +a,b +1,"ha  +""ha""  +ha",120 any st.,"Anytown, WW",08123 +3,4,120 any st.,"Anytown, WW",08123 diff --git a/tests/syntax-tests/source/CSV/LICENSE.md b/tests/syntax-tests/source/CSV/LICENSE.md new file mode 100644 index 00000000..5585cebf --- /dev/null +++ b/tests/syntax-tests/source/CSV/LICENSE.md @@ -0,0 +1,27 @@ +The `comma_in_quotes.csv` file" has been added from https://github.com/maxogden/csv-spectrum under the following license: + +BSD 2-Clause License + +Copyright (c) [year], [fullname] +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tests/syntax-tests/source/CSV/comma_in_quotes.csv b/tests/syntax-tests/source/CSV/comma_in_quotes.csv new file mode 100644 index 00000000..499ae280 --- /dev/null +++ b/tests/syntax-tests/source/CSV/comma_in_quotes.csv @@ -0,0 +1,7 @@ +first,last,address,city,zip +John,Doe,120 any st.,"Anytown, WW",08123 +a,b +1,"ha +""ha"" +ha",120 any st.,"Anytown, WW",08123 +3,4,120 any st.,"Anytown, WW",08123 From 5e0b7f013ac636bb6e37b3bfcb4769c8bdf5b406 Mon Sep 17 00:00:00 2001 From: Niklas Sombert Date: Mon, 5 Oct 2020 17:52:40 +0200 Subject: [PATCH 009/243] Add support for comments after section headers (closes #1259) There's no canonical definition of what's the INI syntax, but Python's `ConfigParser` supports comments after section headers: ```ini [section] ; comment ``` --- assets/README.md | 2 +- assets/syntaxes/02_Extra/INI.sublime-syntax | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/assets/README.md b/assets/README.md index de4ec1f6..db87179f 100644 --- a/assets/README.md +++ b/assets/README.md @@ -33,7 +33,7 @@ The following files have been manually modified after converting from a `.tmLang * `Apache.sublime_syntax`=> removed `.conf` and `.CONF` file types. * `Dart.sublime-syntax` => removed `#regex.dart` include. -* `INI.sublime-syntax` => added `.hgrc`, `hgrc`, and `desktop` file types. +* `INI.sublime-syntax` => added `.hgrc`, `hgrc`, and `desktop` file types and support for comments after section headers * `Org mode.sublime-syntax` => removed `task` file type. * `SML.sublime_syntax` => removed `ml` file type. diff --git a/assets/syntaxes/02_Extra/INI.sublime-syntax b/assets/syntaxes/02_Extra/INI.sublime-syntax index 827b7477..4d31bffd 100644 --- a/assets/syntaxes/02_Extra/INI.sublime-syntax +++ b/assets/syntaxes/02_Extra/INI.sublime-syntax @@ -25,12 +25,13 @@ contexts: scope: comment.line.semicolon.ini captures: 1: punctuation.definition.comment.ini - - match: '^\s*(\[)(.*?)(\])' + - match: '^\s*(\[)(.*?)(\])\s*(;.*)?$\n?' scope: meta.tag.section.ini captures: 1: punctuation.definition.section.ini 2: entity.section.ini 3: punctuation.definition.section.ini + 4: comment.definition.section.ini - match: '^(\s*(["'']?)(.+?)(\2)\s*(=))?\s*((["'']?)(.*?)(\7))\s*(;.*)?$\n?' scope: meta.declaration.ini captures: From 85ff81f2388cd2ce10a65dfc3d2a00eb137fecae Mon Sep 17 00:00:00 2001 From: Felipe Garcia Date: Tue, 6 Oct 2020 20:45:12 -0300 Subject: [PATCH 010/243] Add Lua syntax test. --- tests/syntax-tests/highlighted/Lua/test.lua | 34 +++++++++++++++++++++ tests/syntax-tests/source/Lua/test.lua | 34 +++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Lua/test.lua create mode 100644 tests/syntax-tests/source/Lua/test.lua diff --git a/tests/syntax-tests/highlighted/Lua/test.lua b/tests/syntax-tests/highlighted/Lua/test.lua new file mode 100644 index 00000000..3c37aeee --- /dev/null +++ b/tests/syntax-tests/highlighted/Lua/test.lua @@ -0,0 +1,34 @@ +--- Finds factorial of a number. +-- @param value Number to find factorial. +-- @return Factorial of number. +local function factorial(value) + if value <= 1 then + return 1 + else + return value * factorial(value - 1) + end +end + +--- Joins a table of strings into a new string. +-- @param table Table of strings. +-- @param separator Separator character. +-- @return Joined string. +local function join(table, separator) + local data = "" +  + for index, value in ipairs(table) do + data = data .. value .. separator + end +  + data = data:sub(1, data:len() - 1) +  + return data +end + +local a = factorial(5) + +print(a) + +local b = join({ "l", "u", "a" }, ",") + +print(b) diff --git a/tests/syntax-tests/source/Lua/test.lua b/tests/syntax-tests/source/Lua/test.lua new file mode 100644 index 00000000..68eb90e6 --- /dev/null +++ b/tests/syntax-tests/source/Lua/test.lua @@ -0,0 +1,34 @@ +--- Finds factorial of a number. +-- @param value Number to find factorial. +-- @return Factorial of number. +local function factorial(value) + if value <= 1 then + return 1 + else + return value * factorial(value - 1) + end +end + +--- Joins a table of strings into a new string. +-- @param table Table of strings. +-- @param separator Separator character. +-- @return Joined string. +local function join(table, separator) + local data = "" + + for index, value in ipairs(table) do + data = data .. value .. separator + end + + data = data:sub(1, data:len() - 1) + + return data +end + +local a = factorial(5) + +print(a) + +local b = join({ "l", "u", "a" }, ",") + +print(b) From e6c3f9693131db18a83cb971c7326798d0101c66 Mon Sep 17 00:00:00 2001 From: Felipe Garcia Date: Tue, 6 Oct 2020 21:56:08 -0300 Subject: [PATCH 011/243] Add Groovy syntax test. --- .../highlighted/Groovy/test.groovy | 77 +++++++++++++++++++ tests/syntax-tests/source/Groovy/test.groovy | 77 +++++++++++++++++++ 2 files changed, 154 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Groovy/test.groovy create mode 100644 tests/syntax-tests/source/Groovy/test.groovy diff --git a/tests/syntax-tests/highlighted/Groovy/test.groovy b/tests/syntax-tests/highlighted/Groovy/test.groovy new file mode 100644 index 00000000..0c648df9 --- /dev/null +++ b/tests/syntax-tests/highlighted/Groovy/test.groovy @@ -0,0 +1,77 @@ +interface Display { + String asText() +} + +trait Entity { + Integer id +} + +class Product implements Entity, Display { + public String name + public Boolean available + public Float price + + private String key + protected String data + + /** + * Creates a new product instance. + * @param id Product ID. + * @param name Product name. + * @param available Product availability. + * @param price Product price. + * @param key Product key. + * @param data Product internal data. + */ + Product(id, name, available, price, key = "key", data = "internal") { + this.id = id + this.name = name + this.available = available + this.price = price + this.key = key + this.data = data + } + + /**@ + * Returns product data as text. + * @return Data string. + */ + String asText() { + return """ID [${id}] Name [${name}] Available [${available}] Price [${price}]""" + } +} + +/* Creates a new product instance */ +def product = new Product(1, "T-Shirt", true, 15.00) + +println(product.asText()) + +product.available = false +product.price = 0.0 + +// Check values +assert product.asText() == "ID [1] Name [T-Shirt] Available [false] Price [0.0]" + +def factorial(Integer value) { + if (value <= 1) { + return 1 + } else { + return value * factorial(value - 1) + } +} + +assert factorial(5) == 120 + +static String join(List list, String separator) { + String data = "" + + list.each { item -> + data += item + separator + } + + data = data.substring(0, data.length() - 1) + + return data +} + +assert join(["g", "r", "o", "o", "v", "y"], " ") == "g r o o v y" diff --git a/tests/syntax-tests/source/Groovy/test.groovy b/tests/syntax-tests/source/Groovy/test.groovy new file mode 100644 index 00000000..43d1477b --- /dev/null +++ b/tests/syntax-tests/source/Groovy/test.groovy @@ -0,0 +1,77 @@ +interface Display { + String asText() +} + +trait Entity { + Integer id +} + +class Product implements Entity, Display { + public String name + public Boolean available + public Float price + + private String key + protected String data + + /** + * Creates a new product instance. + * @param id Product ID. + * @param name Product name. + * @param available Product availability. + * @param price Product price. + * @param key Product key. + * @param data Product internal data. + */ + Product(id, name, available, price, key = "key", data = "internal") { + this.id = id + this.name = name + this.available = available + this.price = price + this.key = key + this.data = data + } + + /**@ + * Returns product data as text. + * @return Data string. + */ + String asText() { + return """ID [${id}] Name [${name}] Available [${available}] Price [${price}]""" + } +} + +/* Creates a new product instance */ +def product = new Product(1, "T-Shirt", true, 15.00) + +println(product.asText()) + +product.available = false +product.price = 0.0 + +// Check values +assert product.asText() == "ID [1] Name [T-Shirt] Available [false] Price [0.0]" + +def factorial(Integer value) { + if (value <= 1) { + return 1 + } else { + return value * factorial(value - 1) + } +} + +assert factorial(5) == 120 + +static String join(List list, String separator) { + String data = "" + + list.each { item -> + data += item + separator + } + + data = data.substring(0, data.length() - 1) + + return data +} + +assert join(["g", "r", "o", "o", "v", "y"], " ") == "g r o o v y" From b30f9a1677a4726b498828dfab1de2dcfc67c995 Mon Sep 17 00:00:00 2001 From: Spencer Williams Date: Tue, 6 Oct 2020 22:14:42 -0400 Subject: [PATCH 012/243] Add sample Crystal file --- .../syntax-tests/highlighted/Crystal/test.cr | 117 ++++++++++++++++++ tests/syntax-tests/source/Crystal/test.cr | 117 ++++++++++++++++++ 2 files changed, 234 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Crystal/test.cr create mode 100644 tests/syntax-tests/source/Crystal/test.cr diff --git a/tests/syntax-tests/highlighted/Crystal/test.cr b/tests/syntax-tests/highlighted/Crystal/test.cr new file mode 100644 index 00000000..38c53cad --- /dev/null +++ b/tests/syntax-tests/highlighted/Crystal/test.cr @@ -0,0 +1,117 @@ +# An example file to test Crystal syntax highlighting in bat +my_var : Nil = nil +my_var_also : Int32 = 42 +my_other_var = 4.0 +another_float = 4.0_f32 +another_float_2 = 4e10 +another_float_3 = -0.5 +big_one = 1_000_000.111_111e-4 +ternary = 1 > 2 : 3 ? 4 +my_symbol = :ThisOne? +my_other_symbol = :No_That_One! +plus = :+ +minus = :- +my_string : String = "this string right here, with an interpolated value of #{my_var_also}" +my_array : Array(Int32) = [1,2,3,4] +my_tuple : Tuple(Int32, Int32, Int32, Int32) = {1,2,3,4} +my_named_tuple : NamedTuple(one: Int32, two: Int32) = {"one": 1, "two": 2} +my_hash : Hash(String, Int32) = {"one" => 1, "two" => 2} +my_proc : Proc(Int32, Int32) = ->(x : Int32){ x * x} +my_other_proc : Proc(String) = ->{ "Wow, neat!" } +puts my_string +puts(my_string) + +enum Colors + Red + Green + Blue +end + +class Greeter + @instance_field = Colors::Red + @@class_field = Colors::Green + + def initialize(@name = "world") + end + + def greet  + puts "Hello, #{@name}" + end + + def render_greeting : String + "Hello, #{@name}" + end + + def with_greeting + yield render_greeting + end + + def is_color_default? + @instance_field == @@class_field + end + + def self.greet_static(name : String) : Unit + puts "Hello, #{name}" + end +end + +greeter = Greeter.new("bat") +greeter.with_greeting do |greeting| + puts greeting +end + +puts <<-EOF + this is a heredoc and it has a value in it of #{greeter.render_greeting}! +EOF + +# This is a command: +`echo yay!` +$?.success? + +my_color = Colors::Red + +puts  + case my_color + when Colors::Red, .red? + "Red" + when Colors::Green, .green? + "Green" + when Colors::Blue, .blue? + "Blue" + else + "I dunno, man. Chartreuse? Maroon?" + end + +class MyGenericClass(T) + def initialize(@wrapped_value : T) + end + + def get + return @wrapped_value + end +end + + +def do_stuff_with_range(r : Range(Int|String)) + return if r.empty? + return unless !(r.empty?) + r.each do |item| + if /e/.match(item.to_s) + puts "#{item} contains the letter e!" + elsif item.to_s.empty? + break + else + next # this is unnecessary, but whatever + end + end +end + + +macro print_range(range) + {% for i in range %} + puts {{i.id}} + {% end %} +end + +print_range(1..3) +print_range(1...3) diff --git a/tests/syntax-tests/source/Crystal/test.cr b/tests/syntax-tests/source/Crystal/test.cr new file mode 100644 index 00000000..179a5577 --- /dev/null +++ b/tests/syntax-tests/source/Crystal/test.cr @@ -0,0 +1,117 @@ +# An example file to test Crystal syntax highlighting in bat +my_var : Nil = nil +my_var_also : Int32 = 42 +my_other_var = 4.0 +another_float = 4.0_f32 +another_float_2 = 4e10 +another_float_3 = -0.5 +big_one = 1_000_000.111_111e-4 +ternary = 1 > 2 : 3 ? 4 +my_symbol = :ThisOne? +my_other_symbol = :No_That_One! +plus = :+ +minus = :- +my_string : String = "this string right here, with an interpolated value of #{my_var_also}" +my_array : Array(Int32) = [1,2,3,4] +my_tuple : Tuple(Int32, Int32, Int32, Int32) = {1,2,3,4} +my_named_tuple : NamedTuple(one: Int32, two: Int32) = {"one": 1, "two": 2} +my_hash : Hash(String, Int32) = {"one" => 1, "two" => 2} +my_proc : Proc(Int32, Int32) = ->(x : Int32){ x * x} +my_other_proc : Proc(String) = ->{ "Wow, neat!" } +puts my_string +puts(my_string) + +enum Colors + Red + Green + Blue +end + +class Greeter + @instance_field = Colors::Red + @@class_field = Colors::Green + + def initialize(@name = "world") + end + + def greet + puts "Hello, #{@name}" + end + + def render_greeting : String + "Hello, #{@name}" + end + + def with_greeting + yield render_greeting + end + + def is_color_default? + @instance_field == @@class_field + end + + def self.greet_static(name : String) : Unit + puts "Hello, #{name}" + end +end + +greeter = Greeter.new("bat") +greeter.with_greeting do |greeting| + puts greeting +end + +puts <<-EOF + this is a heredoc and it has a value in it of #{greeter.render_greeting}! +EOF + +# This is a command: +`echo yay!` +$?.success? + +my_color = Colors::Red + +puts + case my_color + when Colors::Red, .red? + "Red" + when Colors::Green, .green? + "Green" + when Colors::Blue, .blue? + "Blue" + else + "I dunno, man. Chartreuse? Maroon?" + end + +class MyGenericClass(T) + def initialize(@wrapped_value : T) + end + + def get + return @wrapped_value + end +end + + +def do_stuff_with_range(r : Range(Int|String)) + return if r.empty? + return unless !(r.empty?) + r.each do |item| + if /e/.match(item.to_s) + puts "#{item} contains the letter e!" + elsif item.to_s.empty? + break + else + next # this is unnecessary, but whatever + end + end +end + + +macro print_range(range) + {% for i in range %} + puts {{i.id}} + {% end %} +end + +print_range(1..3) +print_range(1...3) From 9257c7ce208e5362ee07e0b4e1aeed21226bcb29 Mon Sep 17 00:00:00 2001 From: Spencer Williams Date: Tue, 6 Oct 2020 23:48:05 -0400 Subject: [PATCH 013/243] Regenerate using a fresh latest build of bat --- .../syntax-tests/highlighted/Crystal/test.cr | 198 +++++++++--------- 1 file changed, 99 insertions(+), 99 deletions(-) diff --git a/tests/syntax-tests/highlighted/Crystal/test.cr b/tests/syntax-tests/highlighted/Crystal/test.cr index 38c53cad..d0971438 100644 --- a/tests/syntax-tests/highlighted/Crystal/test.cr +++ b/tests/syntax-tests/highlighted/Crystal/test.cr @@ -1,117 +1,117 @@ # An example file to test Crystal syntax highlighting in bat -my_var : Nil = nil -my_var_also : Int32 = 42 -my_other_var = 4.0 -another_float = 4.0_f32 -another_float_2 = 4e10 -another_float_3 = -0.5 -big_one = 1_000_000.111_111e-4 -ternary = 1 > 2 : 3 ? 4 -my_symbol = :ThisOne? -my_other_symbol = :No_That_One! -plus = :+ -minus = :- -my_string : String = "this string right here, with an interpolated value of #{my_var_also}" -my_array : Array(Int32) = [1,2,3,4] -my_tuple : Tuple(Int32, Int32, Int32, Int32) = {1,2,3,4} -my_named_tuple : NamedTuple(one: Int32, two: Int32) = {"one": 1, "two": 2} -my_hash : Hash(String, Int32) = {"one" => 1, "two" => 2} -my_proc : Proc(Int32, Int32) = ->(x : Int32){ x * x} -my_other_proc : Proc(String) = ->{ "Wow, neat!" } +my_var : Nil = nil +my_var_also : Int32 = 42 +my_other_var = 4.0 +another_float = 4.0_f32 +another_float_2 = 4e10 +another_float_3 = -0.5 +big_one = 1_000_000.111_111e-4 +ternary = 1 > 2 : 3 ? 4 +my_symbol = :ThisOne? +my_other_symbol = :No_That_One! +plus = :+ +minus = :- +my_string : String = "this string right here, with an interpolated value of #{my_var_also}" +my_array : Array(Int32) = [1,2,3,4] +my_tuple : Tuple(Int32, Int32, Int32, Int32) = {1,2,3,4} +my_named_tuple : NamedTuple(one: Int32, two: Int32) = {"one": 1, "two": 2} +my_hash : Hash(String, Int32) = {"one" => 1, "two" => 2} +my_proc : Proc(Int32, Int32) = ->(x : Int32){ x * x} +my_other_proc : Proc(String) = ->{ "Wow, neat!" } puts my_string -puts(my_string) - -enum Colors - Red - Green - Blue -end - -class Greeter - @instance_field = Colors::Red - @@class_field = Colors::Green - +puts(my_string) + +enum Colors + Red + Green + Blue +end + +class Greeter + @instance_field = Colors::Red + @@class_field = Colors::Green +  def initialize(@name = "world") - end - + end +  def greet  - puts "Hello, #{@name}" - end - - def render_greeting : String - "Hello, #{@name}" - end - - def with_greeting + puts "Hello, #{@name}" + end + + def render_greeting : String + "Hello, #{@name}" + end + + def with_greeting  yield render_greeting - end - - def is_color_default? - @instance_field == @@class_field - end - - def self.greet_static(name : String) : Unit - puts "Hello, #{name}" - end -end - -greeter = Greeter.new("bat") -greeter.with_greeting do |greeting| + end + + def is_color_default? + @instance_field == @@class_field + end + + def self.greet_static(name : String) : Unit + puts "Hello, #{name}" + end +end + +greeter = Greeter.new("bat") +greeter.with_greeting do |greeting|  puts greeting -end - -puts <<-EOF +end + +puts <<-EOF  this is a heredoc and it has a value in it of #{greeter.render_greeting}! -EOF - +EOF + # This is a command: -`echo yay!` +`echo yay!` $?.success? - -my_color = Colors::Red - + +my_color = Colors::Red + puts   case my_color  when Colors::Red, .red? - "Red" + "Red"  when Colors::Green, .green? - "Green" + "Green"  when Colors::Blue, .blue? - "Blue" - else - "I dunno, man. Chartreuse? Maroon?" - end - -class MyGenericClass(T) + "Blue" + else + "I dunno, man. Chartreuse? Maroon?" + end + +class MyGenericClass(T)  def initialize(@wrapped_value : T) - end - - def get - return @wrapped_value - end -end - - -def do_stuff_with_range(r : Range(Int|String)) + end + + def get + return @wrapped_value + end +end + + +def do_stuff_with_range(r : Range(Int|String))  return if r.empty? - return unless !(r.empty?) - r.each do |item| - if /e/.match(item.to_s) - puts "#{item} contains the letter e!" + return unless !(r.empty?) + r.each do |item| + if /e/.match(item.to_s) + puts "#{item} contains the letter e!"  elsif item.to_s.empty? - break - else + break + else  next # this is unnecessary, but whatever - end - end -end - - -macro print_range(range) - {% for i in range %} - puts {{i.id}} - {% end %} -end - -print_range(1..3) -print_range(1...3) + end + end +end + + +macro print_range(range) + {% for i in range %} + puts {{i.id}} + {% end %} +end + +print_range(1..3) +print_range(1...3) From 09631ed119d94504f6701326b2321569890160c6 Mon Sep 17 00:00:00 2001 From: R1tschY Date: Tue, 6 Oct 2020 20:47:04 +0200 Subject: [PATCH 014/243] Add Batch syntax test --- .../syntax-tests/highlighted/Batch/build.bat | 59 +++++++++++++++++++ tests/syntax-tests/source/Batch/LICENSE.md | 26 ++++++++ tests/syntax-tests/source/Batch/build.bat | 59 +++++++++++++++++++ 3 files changed, 144 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Batch/build.bat create mode 100644 tests/syntax-tests/source/Batch/LICENSE.md create mode 100644 tests/syntax-tests/source/Batch/build.bat diff --git a/tests/syntax-tests/highlighted/Batch/build.bat b/tests/syntax-tests/highlighted/Batch/build.bat new file mode 100644 index 00000000..a066dcc8 --- /dev/null +++ b/tests/syntax-tests/highlighted/Batch/build.bat @@ -0,0 +1,59 @@ +@echo off + + +:: Change to your LLVM installation +set "LLVMPath=C:\Program Files\LLVM" +:: Change to your Visual Studio 2017 installation +set "VSPath=C:\Program Files (x86)\Microsoft Visual Studio\2017\Community" +set "VSVersion=14.10.25017" +:: Change to your Windows Kit version & installation +set "WinSDKVersion=10.0.15063.0" +set "WinSDKPath=C:\Program Files (x86)\Windows Kits\10" +:: Change this to your resulting exe +set "OUTPUT=test.exe" + + +:: Setup +set "VSBasePath=%VSPath%\VC\Tools\MSVC\%VSVersion%" +set "PATH=%PATH%;%LLVMPath%\bin;%VSBasePath%\bin\HostX64\x64" + +:: Compiler Flags +set CFLAGS= ^ + -std=c++14 -Wall -Wextra + +set CPPFLAGS= ^ + -I "%VSBasePath%\include" ^ + -I "%WinSDKPath%\Include\%WinSDKVersion%\shared" ^ + -I "%WinSDKPath%\Include\%WinSDKVersion%\ucrt" ^ + -I "%WinSDKPath%\Include\%WinSDKVersion%\um" + + +:: Linker Libs +set LDFLAGS= ^ + -machine:x64 ^ + -nodefaultlib ^ + -subsystem:console + +set LDLIBS= ^ + -libpath:"%VSBasePath%\lib\x64" ^ + -libpath:"%WinSDKPath%\Lib\%WinSDKVersion%\ucrt\x64" ^ + -libpath:"%WinSDKPath%\Lib\%WinSDKVersion%\um\x64" ^ + libucrt.lib libvcruntime.lib libcmt.lib libcpmt.lib ^ + legacy_stdio_definitions.lib oldnames.lib ^ + legacy_stdio_wide_specifiers.lib ^ + kernel32.lib User32.lib + + +:: Compiling +@echo on +@for %%f in (*.cc) do ( + clang++.exe "%%~f" -o "%%~nf.o" -c %CFLAGS% +) + +:: Linking +@set "LINK_FILES=" +@for %%f in (*.o) do ( + @set "LINK_FILES=%LINK_FILES% %%~f" +) + +lld-link.exe %LINK_FILES% -out:"%OUTPUT%" %LDFLAGS% %LDLIBS% diff --git a/tests/syntax-tests/source/Batch/LICENSE.md b/tests/syntax-tests/source/Batch/LICENSE.md new file mode 100644 index 00000000..299169db --- /dev/null +++ b/tests/syntax-tests/source/Batch/LICENSE.md @@ -0,0 +1,26 @@ +The `build.bat` file has been added from https://github.com/Leandros/ClangOnWindows/blob/master/build.bat under the following license: + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to \ No newline at end of file diff --git a/tests/syntax-tests/source/Batch/build.bat b/tests/syntax-tests/source/Batch/build.bat new file mode 100644 index 00000000..56a262e2 --- /dev/null +++ b/tests/syntax-tests/source/Batch/build.bat @@ -0,0 +1,59 @@ +@echo off + + +:: Change to your LLVM installation +set "LLVMPath=C:\Program Files\LLVM" +:: Change to your Visual Studio 2017 installation +set "VSPath=C:\Program Files (x86)\Microsoft Visual Studio\2017\Community" +set "VSVersion=14.10.25017" +:: Change to your Windows Kit version & installation +set "WinSDKVersion=10.0.15063.0" +set "WinSDKPath=C:\Program Files (x86)\Windows Kits\10" +:: Change this to your resulting exe +set "OUTPUT=test.exe" + + +:: Setup +set "VSBasePath=%VSPath%\VC\Tools\MSVC\%VSVersion%" +set "PATH=%PATH%;%LLVMPath%\bin;%VSBasePath%\bin\HostX64\x64" + +:: Compiler Flags +set CFLAGS= ^ + -std=c++14 -Wall -Wextra + +set CPPFLAGS= ^ + -I "%VSBasePath%\include" ^ + -I "%WinSDKPath%\Include\%WinSDKVersion%\shared" ^ + -I "%WinSDKPath%\Include\%WinSDKVersion%\ucrt" ^ + -I "%WinSDKPath%\Include\%WinSDKVersion%\um" + + +:: Linker Libs +set LDFLAGS= ^ + -machine:x64 ^ + -nodefaultlib ^ + -subsystem:console + +set LDLIBS= ^ + -libpath:"%VSBasePath%\lib\x64" ^ + -libpath:"%WinSDKPath%\Lib\%WinSDKVersion%\ucrt\x64" ^ + -libpath:"%WinSDKPath%\Lib\%WinSDKVersion%\um\x64" ^ + libucrt.lib libvcruntime.lib libcmt.lib libcpmt.lib ^ + legacy_stdio_definitions.lib oldnames.lib ^ + legacy_stdio_wide_specifiers.lib ^ + kernel32.lib User32.lib + + +:: Compiling +@echo on +@for %%f in (*.cc) do ( + clang++.exe "%%~f" -o "%%~nf.o" -c %CFLAGS% +) + +:: Linking +@set "LINK_FILES=" +@for %%f in (*.o) do ( + @set "LINK_FILES=%LINK_FILES% %%~f" +) + +lld-link.exe %LINK_FILES% -out:"%OUTPUT%" %LDFLAGS% %LDLIBS% \ No newline at end of file From 8832a96e82cb7a1135d6188972f9634f21e83a4c Mon Sep 17 00:00:00 2001 From: Daniel Wolbach Date: Wed, 7 Oct 2020 17:11:26 +0200 Subject: [PATCH 015/243] add GLSL syntax highlighting test --- tests/syntax-tests/highlighted/GLSL/test.glsl | 42 +++++++++++++++++++ tests/syntax-tests/source/GLSL/test.glsl | 42 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 tests/syntax-tests/highlighted/GLSL/test.glsl create mode 100644 tests/syntax-tests/source/GLSL/test.glsl diff --git a/tests/syntax-tests/highlighted/GLSL/test.glsl b/tests/syntax-tests/highlighted/GLSL/test.glsl new file mode 100644 index 00000000..1233c312 --- /dev/null +++ b/tests/syntax-tests/highlighted/GLSL/test.glsl @@ -0,0 +1,42 @@ +#version 330 core + +#ifdef TEST +layout (location = 0) in vec4 vertex; +#else +layout (location = 6) in vec4 vertex; +#endif + +out vec2 p_textureVertex; + +/* + * This stores offsets + */ +struct Data +{ + double offsetX; + double offsetY; +} + +uniform mat4 projectionMatrix; +uniform bool test; +uniform Data data; + +double calc() +{ + if (test) + { + return 1.0; + } + else + { + return 0.0; + } +} + +void main() +{ + // This GLSL code serves the purpose of bat syntax highlighting tests + double x = data.offsetX + calc(); + gl_Position = projectionMatrix * vec4(vertex.xy, data.offsetX, data.offsetY); + p_textureVertex = vertex.zw; +} diff --git a/tests/syntax-tests/source/GLSL/test.glsl b/tests/syntax-tests/source/GLSL/test.glsl new file mode 100644 index 00000000..c0dda705 --- /dev/null +++ b/tests/syntax-tests/source/GLSL/test.glsl @@ -0,0 +1,42 @@ +#version 330 core + +#ifdef TEST +layout (location = 0) in vec4 vertex; +#else +layout (location = 6) in vec4 vertex; +#endif + +out vec2 p_textureVertex; + +/* + * This stores offsets + */ +struct Data +{ + double offsetX; + double offsetY; +} + +uniform mat4 projectionMatrix; +uniform bool test; +uniform Data data; + +double calc() +{ + if (test) + { + return 1.0; + } + else + { + return 0.0; + } +} + +void main() +{ + // This GLSL code serves the purpose of bat syntax highlighting tests + double x = data.offsetX + calc(); + gl_Position = projectionMatrix * vec4(vertex.xy, data.offsetX, data.offsetY); + p_textureVertex = vertex.zw; +} From 5fe98689d4301f43831f9a104b3be51b91ae068a Mon Sep 17 00:00:00 2001 From: Filip Czaplicki Date: Wed, 7 Oct 2020 17:30:48 +0200 Subject: [PATCH 016/243] test: x86-64 Assembly NASM syntax test --- .../highlighted/Assembly (x86_64)/test.nasm | 86 +++++++++++++++++++ .../source/Assembly (x86_64)/test.nasm | 86 +++++++++++++++++++ 2 files changed, 172 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Assembly (x86_64)/test.nasm create mode 100644 tests/syntax-tests/source/Assembly (x86_64)/test.nasm diff --git a/tests/syntax-tests/highlighted/Assembly (x86_64)/test.nasm b/tests/syntax-tests/highlighted/Assembly (x86_64)/test.nasm new file mode 100644 index 00000000..816ec75e --- /dev/null +++ b/tests/syntax-tests/highlighted/Assembly (x86_64)/test.nasm @@ -0,0 +1,86 @@ +global enlight + +section .data + red dq 0 ; some comment + green dq 0 + blue dq 0 + data dq 0 + N dd 0 + M dd 0 + change dd 0 + delta db 0 + +section .text +enlight: + call assign_arguments + call set_data + call make_deltas + ret + +assign_arguments: + mov qword[red], rdi + mov qword[green], rsi + mov qword[blue], rdx + mov dword[N], ecx + mov dword[M], r8d + mov dword[change], r9d + mov al, byte[rsp + 16] + mov byte[delta], al + ret + +set_data: + mov eax, dword[change] + cmp eax, 1 + jne not_1 + mov rax, qword[red] + mov qword[data], rax + ret +not_1: + cmp eax, 2 + jne not_2 + mov rax, qword[green] + mov qword[data], rax + ret +not_2: + mov rax, qword[blue] + mov qword[data], rax + ret + + +make_deltas: + mov ecx, dword[N] + mov eax, dword[M] + imul ecx, eax +loop_start: + call make_delta + loop loop_start + ret + +make_delta: + mov rax, qword[data] + add rax, rcx + dec rax + mov dl, byte[delta] + cmp dl, 0 + jl substracting +adding: + add dl, byte[rax] + jc adding_overflow + mov byte[rax], dl + ret +adding_overflow: + mov byte[rax], 255  + ret +substracting: + mov r9b, dl + mov dl, 0 + sub dl, r9b + mov r8b, byte[rax] + sub r8b, dl + jc substracting_overflow + mov byte[rax], r8b + ret +; another comment +substracting_overflow: + mov byte[rax], 0 + ret diff --git a/tests/syntax-tests/source/Assembly (x86_64)/test.nasm b/tests/syntax-tests/source/Assembly (x86_64)/test.nasm new file mode 100644 index 00000000..05c87947 --- /dev/null +++ b/tests/syntax-tests/source/Assembly (x86_64)/test.nasm @@ -0,0 +1,86 @@ +global enlight + +section .data + red dq 0 ; some comment + green dq 0 + blue dq 0 + data dq 0 + N dd 0 + M dd 0 + change dd 0 + delta db 0 + +section .text +enlight: + call assign_arguments + call set_data + call make_deltas + ret + +assign_arguments: + mov qword[red], rdi + mov qword[green], rsi + mov qword[blue], rdx + mov dword[N], ecx + mov dword[M], r8d + mov dword[change], r9d + mov al, byte[rsp + 16] + mov byte[delta], al + ret + +set_data: + mov eax, dword[change] + cmp eax, 1 + jne not_1 + mov rax, qword[red] + mov qword[data], rax + ret +not_1: + cmp eax, 2 + jne not_2 + mov rax, qword[green] + mov qword[data], rax + ret +not_2: + mov rax, qword[blue] + mov qword[data], rax + ret + + +make_deltas: + mov ecx, dword[N] + mov eax, dword[M] + imul ecx, eax +loop_start: + call make_delta + loop loop_start + ret + +make_delta: + mov rax, qword[data] + add rax, rcx + dec rax + mov dl, byte[delta] + cmp dl, 0 + jl substracting +adding: + add dl, byte[rax] + jc adding_overflow + mov byte[rax], dl + ret +adding_overflow: + mov byte[rax], 255 + ret +substracting: + mov r9b, dl + mov dl, 0 + sub dl, r9b + mov r8b, byte[rax] + sub r8b, dl + jc substracting_overflow + mov byte[rax], r8b + ret +; another comment +substracting_overflow: + mov byte[rax], 0 + ret From b6e729abeb37306d70d791d79dcb4bcf03c2c299 Mon Sep 17 00:00:00 2001 From: Benjamin Neff Date: Thu, 8 Oct 2020 01:24:13 +0200 Subject: [PATCH 017/243] Add Diff syntax highlight test --- ...7786e747b1fcfac1f963ae6415a22ec9caae1.diff | 353 ++++++++++++++++++ ...7786e747b1fcfac1f963ae6415a22ec9caae1.diff | 353 ++++++++++++++++++ 2 files changed, 706 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Diff/82e7786e747b1fcfac1f963ae6415a22ec9caae1.diff create mode 100644 tests/syntax-tests/source/Diff/82e7786e747b1fcfac1f963ae6415a22ec9caae1.diff diff --git a/tests/syntax-tests/highlighted/Diff/82e7786e747b1fcfac1f963ae6415a22ec9caae1.diff b/tests/syntax-tests/highlighted/Diff/82e7786e747b1fcfac1f963ae6415a22ec9caae1.diff new file mode 100644 index 00000000..39f95b74 --- /dev/null +++ b/tests/syntax-tests/highlighted/Diff/82e7786e747b1fcfac1f963ae6415a22ec9caae1.diff @@ -0,0 +1,353 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index ced88213..973eba9a 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -2,6 +2,11 @@ +  +  + ## Features ++ ++- Add a new `--diff` option that can be used to only show lines surrounding ++ Git changes, i.e. added, removed or modified lines. The amount of additional ++ context can be controlled with `--diff-context=N`. See #23 and #940 ++ + ## Bugfixes + ## Other + ## `bat` as a library +diff --git a/src/bin/bat/app.rs b/src/bin/bat/app.rs +index e5221455..f0f519ea 100644 +--- a/src/bin/bat/app.rs ++++ b/src/bin/bat/app.rs +@@ -15,7 +15,7 @@ use console::Term; +  + use bat::{ + assets::HighlightingAssets, +- config::Config, ++ config::{Config, VisibleLines}, + error::*, + input::Input, + line_range::{HighlightedLineRanges, LineRange, LineRanges}, +@@ -196,13 +196,23 @@ impl App { + } + }) + .unwrap_or_else(|| String::from(HighlightingAssets::default_theme())), +- line_ranges: self +- .matches +- .values_of("line-range") +- .map(|vs| vs.map(LineRange::from).collect()) +- .transpose()? +- .map(LineRanges::from) +- .unwrap_or_default(), ++ visible_lines: if self.matches.is_present("diff") { ++ VisibleLines::DiffContext( ++ self.matches ++ .value_of("diff-context") ++ .and_then(|t| t.parse().ok()) ++ .unwrap_or(2), ++ ) ++ } else { ++ VisibleLines::Ranges( ++ self.matches ++ .values_of("line-range") ++ .map(|vs| vs.map(LineRange::from).collect()) ++ .transpose()? ++ .map(LineRanges::from) ++ .unwrap_or_default(), ++ ) ++ }, + style_components, + syntax_mapping, + pager: self.matches.value_of("pager"), +diff --git a/src/bin/bat/clap_app.rs b/src/bin/bat/clap_app.rs +index c7344991..85edefde 100644 +--- a/src/bin/bat/clap_app.rs ++++ b/src/bin/bat/clap_app.rs +@@ -105,6 +105,34 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> { + data to bat from STDIN when bat does not otherwise know \ + the filename."), + ) ++ .arg( ++ Arg::with_name("diff") ++ .long("diff") ++ .help("Only show lines that have been added/removed/modified.") ++ .long_help( ++ "Only show lines that have been added/removed/modified with respect \ ++ to the Git index. Use --diff-context=N to control how much context you want to see.", ++ ), ++ ) ++ .arg( ++ Arg::with_name("diff-context") ++ .long("diff-context") ++ .overrides_with("diff-context") ++ .takes_value(true) ++ .value_name("N") ++ .validator( ++ |n| { ++ n.parse::() ++ .map_err(|_| "must be a number") ++ .map(|_| ()) // Convert to Result<(), &str> ++ .map_err(|e| e.to_string()) ++ }, // Convert to Result<(), String> ++ ) ++ .hidden_short_help(true) ++ .long_help( ++ "Include N lines of context around added/removed/modified lines when using '--diff'.", ++ ), ++ ) + .arg( + Arg::with_name("tabs") + .long("tabs") +@@ -339,6 +367,7 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> { + .takes_value(true) + .number_of_values(1) + .value_name("N:M") ++ .conflicts_with("diff") + .help("Only print the lines from N to M.") + .long_help( + "Only print the specified range of lines for each file. \ +diff --git a/src/config.rs b/src/config.rs +index d5df9910..3c24b77f 100644 +--- a/src/config.rs ++++ b/src/config.rs +@@ -5,6 +5,32 @@ use crate::style::StyleComponents; + use crate::syntax_mapping::SyntaxMapping; + use crate::wrapping::WrappingMode; +  ++#[derive(Debug, Clone)] ++pub enum VisibleLines { ++ /// Show all lines which are included in the line ranges ++ Ranges(LineRanges), ++ ++ #[cfg(feature = "git")] ++ /// Only show lines surrounding added/deleted/modified lines ++ DiffContext(usize), ++} ++ ++impl VisibleLines { ++ pub fn diff_context(&self) -> bool { ++ match self { ++ Self::Ranges(_) => false, ++ #[cfg(feature = "git")] ++ Self::DiffContext(_) => true, ++ } ++ } ++} ++ ++impl Default for VisibleLines { ++ fn default() -> Self { ++ VisibleLines::Ranges(LineRanges::default()) ++ } ++} ++ + #[derive(Debug, Clone, Default)] + pub struct Config<'a> { + /// The explicitly configured language, if any +@@ -39,8 +65,8 @@ pub struct Config<'a> { + #[cfg(feature = "paging")] + pub paging_mode: PagingMode, +  +- /// Specifies the lines that should be printed +- pub line_ranges: LineRanges, ++ /// Specifies which lines should be printed ++ pub visible_lines: VisibleLines, +  + /// The syntax highlighting theme + pub theme: String, +@@ -62,10 +88,7 @@ pub struct Config<'a> { + fn default_config_should_include_all_lines() { + use crate::line_range::RangeCheckResult; +  +- assert_eq!( +- Config::default().line_ranges.check(17), +- RangeCheckResult::InRange +- ); ++ assert_eq!(LineRanges::default().check(17), RangeCheckResult::InRange); + } +  + #[test] +diff --git a/src/controller.rs b/src/controller.rs +index 09c6ec2a..f636d5fd 100644 +--- a/src/controller.rs ++++ b/src/controller.rs +@@ -1,9 +1,13 @@ + use std::io::{self, Write}; +  + use crate::assets::HighlightingAssets; +-use crate::config::Config; ++use crate::config::{Config, VisibleLines}; ++#[cfg(feature = "git")] ++use crate::diff::{get_git_diff, LineChanges}; + use crate::error::*; + use crate::input::{Input, InputReader, OpenedInput}; ++#[cfg(feature = "git")] ++use crate::line_range::LineRange; + use crate::line_range::{LineRanges, RangeCheckResult}; + use crate::output::OutputType; + #[cfg(feature = "paging")] +@@ -68,6 +72,32 @@ impl<'b> Controller<'b> { + no_errors = false; + } + Ok(mut opened_input) => { ++ #[cfg(feature = "git")] ++ let line_changes = if self.config.visible_lines.diff_context() ++ || (!self.config.loop_through && self.config.style_components.changes()) ++ { ++ if let crate::input::OpenedInputKind::OrdinaryFile(ref path) = ++ opened_input.kind ++ { ++ let diff = get_git_diff(path); ++ ++ if self.config.visible_lines.diff_context() ++ && diff ++ .as_ref() ++ .map(|changes| changes.is_empty()) ++ .unwrap_or(false) ++ { ++ continue; ++ } ++ ++ diff ++ } else { ++ None ++ } ++ } else { ++ None ++ }; ++ + let mut printer: Box = if self.config.loop_through { + Box::new(SimplePrinter::new()) + } else { +@@ -75,10 +105,18 @@ impl<'b> Controller<'b> { + &self.config, + &self.assets, + &mut opened_input, ++ #[cfg(feature = "git")] ++ &line_changes, + )) + }; +  +- let result = self.print_file(&mut *printer, writer, &mut opened_input); ++ let result = self.print_file( ++ &mut *printer, ++ writer, ++ &mut opened_input, ++ #[cfg(feature = "git")] ++ &line_changes, ++ ); +  + if let Err(error) = result { + handle_error(&error); +@@ -96,13 +134,31 @@ impl<'b> Controller<'b> { + printer: &mut dyn Printer, + writer: &mut dyn Write, + input: &mut OpenedInput, ++ #[cfg(feature = "git")] line_changes: &Option, + ) -> Result<()> { + if !input.reader.first_line.is_empty() || self.config.style_components.header() { + printer.print_header(writer, input)?; + } +  + if !input.reader.first_line.is_empty() { +- self.print_file_ranges(printer, writer, &mut input.reader, &self.config.line_ranges)?; ++ let line_ranges = match self.config.visible_lines { ++ VisibleLines::Ranges(ref line_ranges) => line_ranges.clone(), ++ #[cfg(feature = "git")] ++ VisibleLines::DiffContext(context) => { ++ let mut line_ranges: Vec = vec![]; ++ ++ if let Some(line_changes) = line_changes { ++ for line in line_changes.keys() { ++ let line = *line as usize; ++ line_ranges.push(LineRange::new(line - context, line + context)); ++ } ++ } ++ ++ LineRanges::from(line_ranges) ++ } ++ }; ++ ++ self.print_file_ranges(printer, writer, &mut input.reader, &line_ranges)?; + } + printer.print_footer(writer, input)?; +  +diff --git a/src/pretty_printer.rs b/src/pretty_printer.rs +index 0c78ea90..13bd5dbc 100644 +--- a/src/pretty_printer.rs ++++ b/src/pretty_printer.rs +@@ -6,7 +6,7 @@ use syntect::parsing::SyntaxReference; +  + use crate::{ + assets::HighlightingAssets, +- config::Config, ++ config::{Config, VisibleLines}, + controller::Controller, + error::Result, + input::Input, +@@ -205,7 +205,7 @@ impl<'a> PrettyPrinter<'a> { +  + /// Specify the lines that should be printed (default: all) + pub fn line_ranges(&mut self, ranges: LineRanges) -> &mut Self { +- self.config.line_ranges = ranges; ++ self.config.visible_lines = VisibleLines::Ranges(ranges); + self + } +  +diff --git a/src/printer.rs b/src/printer.rs +index 5eed437e..2b245cfd 100644 +--- a/src/printer.rs ++++ b/src/printer.rs +@@ -24,7 +24,7 @@ use crate::config::Config; + use crate::decorations::LineChangesDecoration; + use crate::decorations::{Decoration, GridBorderDecoration, LineNumberDecoration}; + #[cfg(feature = "git")] +-use crate::diff::{get_git_diff, LineChanges}; ++use crate::diff::LineChanges; + use crate::error::*; + use crate::input::OpenedInput; + use crate::line_range::RangeCheckResult; +@@ -90,7 +90,7 @@ pub(crate) struct InteractivePrinter<'a> { + ansi_prefix_sgr: String, + content_type: Option, + #[cfg(feature = "git")] +- pub line_changes: Option, ++ pub line_changes: &'a Option, + highlighter: Option>, + syntax_set: &'a SyntaxSet, + background_color_highlight: Option, +@@ -101,6 +101,7 @@ impl<'a> InteractivePrinter<'a> { + config: &'a Config, + assets: &'a HighlightingAssets, + input: &mut OpenedInput, ++ #[cfg(feature = "git")] line_changes: &'a Option, + ) -> Self { + let theme = assets.get_theme(&config.theme); +  +@@ -145,9 +146,6 @@ impl<'a> InteractivePrinter<'a> { + panel_width = 0; + } +  +- #[cfg(feature = "git")] +- let mut line_changes = None; +- + let highlighter = if input + .reader + .content_type +@@ -155,18 +153,6 @@ impl<'a> InteractivePrinter<'a> { + { + None + } else { +- // Get the Git modifications +- #[cfg(feature = "git")] +- { +- use crate::input::OpenedInputKind; +- +- if config.style_components.changes() { +- if let OpenedInputKind::OrdinaryFile(ref path) = input.kind { +- line_changes = get_git_diff(path); +- } +- } +- } +- + // Determine the type of syntax for highlighting + let syntax = assets.get_syntax(config.language, input, &config.syntax_mapping); + Some(HighlightLines::new(syntax, theme)) diff --git a/tests/syntax-tests/source/Diff/82e7786e747b1fcfac1f963ae6415a22ec9caae1.diff b/tests/syntax-tests/source/Diff/82e7786e747b1fcfac1f963ae6415a22ec9caae1.diff new file mode 100644 index 00000000..ebbee60c --- /dev/null +++ b/tests/syntax-tests/source/Diff/82e7786e747b1fcfac1f963ae6415a22ec9caae1.diff @@ -0,0 +1,353 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index ced88213..973eba9a 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -2,6 +2,11 @@ + + + ## Features ++ ++- Add a new `--diff` option that can be used to only show lines surrounding ++ Git changes, i.e. added, removed or modified lines. The amount of additional ++ context can be controlled with `--diff-context=N`. See #23 and #940 ++ + ## Bugfixes + ## Other + ## `bat` as a library +diff --git a/src/bin/bat/app.rs b/src/bin/bat/app.rs +index e5221455..f0f519ea 100644 +--- a/src/bin/bat/app.rs ++++ b/src/bin/bat/app.rs +@@ -15,7 +15,7 @@ use console::Term; + + use bat::{ + assets::HighlightingAssets, +- config::Config, ++ config::{Config, VisibleLines}, + error::*, + input::Input, + line_range::{HighlightedLineRanges, LineRange, LineRanges}, +@@ -196,13 +196,23 @@ impl App { + } + }) + .unwrap_or_else(|| String::from(HighlightingAssets::default_theme())), +- line_ranges: self +- .matches +- .values_of("line-range") +- .map(|vs| vs.map(LineRange::from).collect()) +- .transpose()? +- .map(LineRanges::from) +- .unwrap_or_default(), ++ visible_lines: if self.matches.is_present("diff") { ++ VisibleLines::DiffContext( ++ self.matches ++ .value_of("diff-context") ++ .and_then(|t| t.parse().ok()) ++ .unwrap_or(2), ++ ) ++ } else { ++ VisibleLines::Ranges( ++ self.matches ++ .values_of("line-range") ++ .map(|vs| vs.map(LineRange::from).collect()) ++ .transpose()? ++ .map(LineRanges::from) ++ .unwrap_or_default(), ++ ) ++ }, + style_components, + syntax_mapping, + pager: self.matches.value_of("pager"), +diff --git a/src/bin/bat/clap_app.rs b/src/bin/bat/clap_app.rs +index c7344991..85edefde 100644 +--- a/src/bin/bat/clap_app.rs ++++ b/src/bin/bat/clap_app.rs +@@ -105,6 +105,34 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> { + data to bat from STDIN when bat does not otherwise know \ + the filename."), + ) ++ .arg( ++ Arg::with_name("diff") ++ .long("diff") ++ .help("Only show lines that have been added/removed/modified.") ++ .long_help( ++ "Only show lines that have been added/removed/modified with respect \ ++ to the Git index. Use --diff-context=N to control how much context you want to see.", ++ ), ++ ) ++ .arg( ++ Arg::with_name("diff-context") ++ .long("diff-context") ++ .overrides_with("diff-context") ++ .takes_value(true) ++ .value_name("N") ++ .validator( ++ |n| { ++ n.parse::() ++ .map_err(|_| "must be a number") ++ .map(|_| ()) // Convert to Result<(), &str> ++ .map_err(|e| e.to_string()) ++ }, // Convert to Result<(), String> ++ ) ++ .hidden_short_help(true) ++ .long_help( ++ "Include N lines of context around added/removed/modified lines when using '--diff'.", ++ ), ++ ) + .arg( + Arg::with_name("tabs") + .long("tabs") +@@ -339,6 +367,7 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> { + .takes_value(true) + .number_of_values(1) + .value_name("N:M") ++ .conflicts_with("diff") + .help("Only print the lines from N to M.") + .long_help( + "Only print the specified range of lines for each file. \ +diff --git a/src/config.rs b/src/config.rs +index d5df9910..3c24b77f 100644 +--- a/src/config.rs ++++ b/src/config.rs +@@ -5,6 +5,32 @@ use crate::style::StyleComponents; + use crate::syntax_mapping::SyntaxMapping; + use crate::wrapping::WrappingMode; + ++#[derive(Debug, Clone)] ++pub enum VisibleLines { ++ /// Show all lines which are included in the line ranges ++ Ranges(LineRanges), ++ ++ #[cfg(feature = "git")] ++ /// Only show lines surrounding added/deleted/modified lines ++ DiffContext(usize), ++} ++ ++impl VisibleLines { ++ pub fn diff_context(&self) -> bool { ++ match self { ++ Self::Ranges(_) => false, ++ #[cfg(feature = "git")] ++ Self::DiffContext(_) => true, ++ } ++ } ++} ++ ++impl Default for VisibleLines { ++ fn default() -> Self { ++ VisibleLines::Ranges(LineRanges::default()) ++ } ++} ++ + #[derive(Debug, Clone, Default)] + pub struct Config<'a> { + /// The explicitly configured language, if any +@@ -39,8 +65,8 @@ pub struct Config<'a> { + #[cfg(feature = "paging")] + pub paging_mode: PagingMode, + +- /// Specifies the lines that should be printed +- pub line_ranges: LineRanges, ++ /// Specifies which lines should be printed ++ pub visible_lines: VisibleLines, + + /// The syntax highlighting theme + pub theme: String, +@@ -62,10 +88,7 @@ pub struct Config<'a> { + fn default_config_should_include_all_lines() { + use crate::line_range::RangeCheckResult; + +- assert_eq!( +- Config::default().line_ranges.check(17), +- RangeCheckResult::InRange +- ); ++ assert_eq!(LineRanges::default().check(17), RangeCheckResult::InRange); + } + + #[test] +diff --git a/src/controller.rs b/src/controller.rs +index 09c6ec2a..f636d5fd 100644 +--- a/src/controller.rs ++++ b/src/controller.rs +@@ -1,9 +1,13 @@ + use std::io::{self, Write}; + + use crate::assets::HighlightingAssets; +-use crate::config::Config; ++use crate::config::{Config, VisibleLines}; ++#[cfg(feature = "git")] ++use crate::diff::{get_git_diff, LineChanges}; + use crate::error::*; + use crate::input::{Input, InputReader, OpenedInput}; ++#[cfg(feature = "git")] ++use crate::line_range::LineRange; + use crate::line_range::{LineRanges, RangeCheckResult}; + use crate::output::OutputType; + #[cfg(feature = "paging")] +@@ -68,6 +72,32 @@ impl<'b> Controller<'b> { + no_errors = false; + } + Ok(mut opened_input) => { ++ #[cfg(feature = "git")] ++ let line_changes = if self.config.visible_lines.diff_context() ++ || (!self.config.loop_through && self.config.style_components.changes()) ++ { ++ if let crate::input::OpenedInputKind::OrdinaryFile(ref path) = ++ opened_input.kind ++ { ++ let diff = get_git_diff(path); ++ ++ if self.config.visible_lines.diff_context() ++ && diff ++ .as_ref() ++ .map(|changes| changes.is_empty()) ++ .unwrap_or(false) ++ { ++ continue; ++ } ++ ++ diff ++ } else { ++ None ++ } ++ } else { ++ None ++ }; ++ + let mut printer: Box = if self.config.loop_through { + Box::new(SimplePrinter::new()) + } else { +@@ -75,10 +105,18 @@ impl<'b> Controller<'b> { + &self.config, + &self.assets, + &mut opened_input, ++ #[cfg(feature = "git")] ++ &line_changes, + )) + }; + +- let result = self.print_file(&mut *printer, writer, &mut opened_input); ++ let result = self.print_file( ++ &mut *printer, ++ writer, ++ &mut opened_input, ++ #[cfg(feature = "git")] ++ &line_changes, ++ ); + + if let Err(error) = result { + handle_error(&error); +@@ -96,13 +134,31 @@ impl<'b> Controller<'b> { + printer: &mut dyn Printer, + writer: &mut dyn Write, + input: &mut OpenedInput, ++ #[cfg(feature = "git")] line_changes: &Option, + ) -> Result<()> { + if !input.reader.first_line.is_empty() || self.config.style_components.header() { + printer.print_header(writer, input)?; + } + + if !input.reader.first_line.is_empty() { +- self.print_file_ranges(printer, writer, &mut input.reader, &self.config.line_ranges)?; ++ let line_ranges = match self.config.visible_lines { ++ VisibleLines::Ranges(ref line_ranges) => line_ranges.clone(), ++ #[cfg(feature = "git")] ++ VisibleLines::DiffContext(context) => { ++ let mut line_ranges: Vec = vec![]; ++ ++ if let Some(line_changes) = line_changes { ++ for line in line_changes.keys() { ++ let line = *line as usize; ++ line_ranges.push(LineRange::new(line - context, line + context)); ++ } ++ } ++ ++ LineRanges::from(line_ranges) ++ } ++ }; ++ ++ self.print_file_ranges(printer, writer, &mut input.reader, &line_ranges)?; + } + printer.print_footer(writer, input)?; + +diff --git a/src/pretty_printer.rs b/src/pretty_printer.rs +index 0c78ea90..13bd5dbc 100644 +--- a/src/pretty_printer.rs ++++ b/src/pretty_printer.rs +@@ -6,7 +6,7 @@ use syntect::parsing::SyntaxReference; + + use crate::{ + assets::HighlightingAssets, +- config::Config, ++ config::{Config, VisibleLines}, + controller::Controller, + error::Result, + input::Input, +@@ -205,7 +205,7 @@ impl<'a> PrettyPrinter<'a> { + + /// Specify the lines that should be printed (default: all) + pub fn line_ranges(&mut self, ranges: LineRanges) -> &mut Self { +- self.config.line_ranges = ranges; ++ self.config.visible_lines = VisibleLines::Ranges(ranges); + self + } + +diff --git a/src/printer.rs b/src/printer.rs +index 5eed437e..2b245cfd 100644 +--- a/src/printer.rs ++++ b/src/printer.rs +@@ -24,7 +24,7 @@ use crate::config::Config; + use crate::decorations::LineChangesDecoration; + use crate::decorations::{Decoration, GridBorderDecoration, LineNumberDecoration}; + #[cfg(feature = "git")] +-use crate::diff::{get_git_diff, LineChanges}; ++use crate::diff::LineChanges; + use crate::error::*; + use crate::input::OpenedInput; + use crate::line_range::RangeCheckResult; +@@ -90,7 +90,7 @@ pub(crate) struct InteractivePrinter<'a> { + ansi_prefix_sgr: String, + content_type: Option, + #[cfg(feature = "git")] +- pub line_changes: Option, ++ pub line_changes: &'a Option, + highlighter: Option>, + syntax_set: &'a SyntaxSet, + background_color_highlight: Option, +@@ -101,6 +101,7 @@ impl<'a> InteractivePrinter<'a> { + config: &'a Config, + assets: &'a HighlightingAssets, + input: &mut OpenedInput, ++ #[cfg(feature = "git")] line_changes: &'a Option, + ) -> Self { + let theme = assets.get_theme(&config.theme); + +@@ -145,9 +146,6 @@ impl<'a> InteractivePrinter<'a> { + panel_width = 0; + } + +- #[cfg(feature = "git")] +- let mut line_changes = None; +- + let highlighter = if input + .reader + .content_type +@@ -155,18 +153,6 @@ impl<'a> InteractivePrinter<'a> { + { + None + } else { +- // Get the Git modifications +- #[cfg(feature = "git")] +- { +- use crate::input::OpenedInputKind; +- +- if config.style_components.changes() { +- if let OpenedInputKind::OrdinaryFile(ref path) = input.kind { +- line_changes = get_git_diff(path); +- } +- } +- } +- + // Determine the type of syntax for highlighting + let syntax = assets.get_syntax(config.language, input, &config.syntax_mapping); + Some(HighlightLines::new(syntax, theme)) From bbef2f41ec0c670dcc54a78ac5b497a084c2557b Mon Sep 17 00:00:00 2001 From: gahag Date: Wed, 7 Oct 2020 12:28:25 -0300 Subject: [PATCH 018/243] Add `-S` flag to less when `--wrap=never` (closes #1255) Prevent less from wrapping lines by setting the proper flag when `--wrap=never`. If the user set a custom value for `--pager`, no additional flag is set. --- src/controller.rs | 5 ++++- src/output.rs | 21 ++++++++++++++++----- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/controller.rs b/src/controller.rs index 3fe44a72..dff817cd 100644 --- a/src/controller.rs +++ b/src/controller.rs @@ -54,7 +54,10 @@ impl<'b> Controller<'b> { paging_mode = PagingMode::Never; } } - output_type = OutputType::from_mode(paging_mode, self.config.pager)?; + + let wrapping_mode = self.config.wrapping_mode; + + output_type = OutputType::from_mode(paging_mode, wrapping_mode, self.config.pager)?; } #[cfg(not(feature = "paging"))] diff --git a/src/output.rs b/src/output.rs index e7d59d67..c42fe68d 100644 --- a/src/output.rs +++ b/src/output.rs @@ -7,6 +7,8 @@ use crate::error::*; use crate::less::retrieve_less_version; #[cfg(feature = "paging")] use crate::paging::PagingMode; +#[cfg(feature = "paging")] +use crate::wrapping::WrappingMode; #[derive(Debug)] pub enum OutputType { @@ -17,18 +19,23 @@ pub enum OutputType { impl OutputType { #[cfg(feature = "paging")] - pub fn from_mode(mode: PagingMode, pager: Option<&str>) -> Result { + pub fn from_mode(paging_mode: PagingMode, wrapping_mode: WrappingMode, pager: Option<&str>) -> Result { use self::PagingMode::*; - Ok(match mode { - Always => OutputType::try_pager(false, pager)?, - QuitIfOneScreen => OutputType::try_pager(true, pager)?, + use self::WrappingMode::*; + Ok(match paging_mode { + Always => OutputType::try_pager(false, wrapping_mode == Character, pager)?, + QuitIfOneScreen => OutputType::try_pager(true, wrapping_mode == Character, pager)?, _ => OutputType::stdout(), }) } /// Try to launch the pager. Fall back to stdout in case of errors. #[cfg(feature = "paging")] - fn try_pager(quit_if_one_screen: bool, pager_from_config: Option<&str>) -> Result { + fn try_pager( + quit_if_one_screen: bool, + line_wrap: bool, + pager_from_config: Option<&str> + ) -> Result { use std::env; use std::ffi::OsString; use std::path::PathBuf; @@ -82,6 +89,10 @@ impl OutputType { p.arg("--quit-if-one-screen"); } + if !line_wrap { + p.arg("-S"); + } + // Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older // versions of 'less'. Unfortunately, it also breaks mouse-wheel support. // From 53f5a37f01c0c354a552c50aa87a8edf38f9b9f0 Mon Sep 17 00:00:00 2001 From: gahag Date: Wed, 7 Oct 2020 14:50:44 -0300 Subject: [PATCH 019/243] Code review - Replace bools with enums - Replace short flag with long flag --- src/output.rs | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/output.rs b/src/output.rs index c42fe68d..1e84e946 100644 --- a/src/output.rs +++ b/src/output.rs @@ -10,6 +10,15 @@ use crate::paging::PagingMode; #[cfg(feature = "paging")] use crate::wrapping::WrappingMode; + +#[cfg(feature = "paging")] +#[derive(Debug)] +enum SingleScreenAction { + Quit, + Nothing, +} + + #[derive(Debug)] pub enum OutputType { #[cfg(feature = "paging")] @@ -21,10 +30,9 @@ impl OutputType { #[cfg(feature = "paging")] pub fn from_mode(paging_mode: PagingMode, wrapping_mode: WrappingMode, pager: Option<&str>) -> Result { use self::PagingMode::*; - use self::WrappingMode::*; Ok(match paging_mode { - Always => OutputType::try_pager(false, wrapping_mode == Character, pager)?, - QuitIfOneScreen => OutputType::try_pager(true, wrapping_mode == Character, pager)?, + Always => OutputType::try_pager(SingleScreenAction::Nothing, wrapping_mode, pager)?, + QuitIfOneScreen => OutputType::try_pager(SingleScreenAction::Quit, wrapping_mode, pager)?, _ => OutputType::stdout(), }) } @@ -32,8 +40,8 @@ impl OutputType { /// Try to launch the pager. Fall back to stdout in case of errors. #[cfg(feature = "paging")] fn try_pager( - quit_if_one_screen: bool, - line_wrap: bool, + single_screen_action: SingleScreenAction, + wrapping_mode: WrappingMode, pager_from_config: Option<&str> ) -> Result { use std::env; @@ -85,12 +93,12 @@ impl OutputType { let mut p = Command::new(&pager_path); if args.is_empty() || replace_arguments_to_less { p.arg("--RAW-CONTROL-CHARS"); - if quit_if_one_screen { + if let SingleScreenAction::Quit = single_screen_action { p.arg("--quit-if-one-screen"); } - if !line_wrap { - p.arg("-S"); + if let WrappingMode::NoWrapping = wrapping_mode { + p.arg("--chop-long-lines"); } // Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older From 6615eceb185abbcb40279a564f17f074eae68762 Mon Sep 17 00:00:00 2001 From: gahag Date: Wed, 7 Oct 2020 19:14:33 -0300 Subject: [PATCH 020/243] Code review: replace `if let` with equals operator --- src/output.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/output.rs b/src/output.rs index 1e84e946..8bbdbc61 100644 --- a/src/output.rs +++ b/src/output.rs @@ -12,7 +12,7 @@ use crate::wrapping::WrappingMode; #[cfg(feature = "paging")] -#[derive(Debug)] +#[derive(Debug, PartialEq)] enum SingleScreenAction { Quit, Nothing, @@ -93,11 +93,11 @@ impl OutputType { let mut p = Command::new(&pager_path); if args.is_empty() || replace_arguments_to_less { p.arg("--RAW-CONTROL-CHARS"); - if let SingleScreenAction::Quit = single_screen_action { + if single_screen_action == SingleScreenAction::Quit { p.arg("--quit-if-one-screen"); } - if let WrappingMode::NoWrapping = wrapping_mode { + if wrapping_mode == WrappingMode::NoWrapping { p.arg("--chop-long-lines"); } From 83ecc3d3ace271510e705bf5f58bf186e46a6e9d Mon Sep 17 00:00:00 2001 From: gahag Date: Thu, 8 Oct 2020 10:58:57 -0300 Subject: [PATCH 021/243] Update changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ac3cd4e..b181ff3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ## Features +- Adjust pager configuration to comply with `--wrap=never`, see #1255 (@gahag) + ## Bugfixes ## Other From 4064b8ff145521c06989f122d9491385ad7dbb6f Mon Sep 17 00:00:00 2001 From: Jacky Hui Date: Thu, 8 Oct 2020 23:09:49 +0100 Subject: [PATCH 022/243] Added test file for Erlang. --- .../highlighted/Erlang/bat_erlang.erl | 72 +++++++++++++++++++ .../syntax-tests/source/Erlang/bat_erlang.erl | 72 +++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Erlang/bat_erlang.erl create mode 100644 tests/syntax-tests/source/Erlang/bat_erlang.erl diff --git a/tests/syntax-tests/highlighted/Erlang/bat_erlang.erl b/tests/syntax-tests/highlighted/Erlang/bat_erlang.erl new file mode 100644 index 00000000..ccf7817d --- /dev/null +++ b/tests/syntax-tests/highlighted/Erlang/bat_erlang.erl @@ -0,0 +1,72 @@ +-module(bat_erlang). + +-export([main/0]). + +-record(test, { + name :: list(), + data :: binary() +}). + +-define(TESTMACRO, "testmacro"). + +-spec main() -> ok. +main() -> + %% Handling Lists and Numbers + List = [1, 2, 3, 4, $6, 2#00111], + _Sum = lists:sum(List), + _ = [(N * N) + N / N - N || N <- List, N > 2], + [_Head, _SecondHead | _Tail] = List, + _ = [1, atom, [list], <<"binary">>, {tuple, tuple}, #{map => key}, #test{name = "record"}], + + %% Handling Binaries  + BinHelloWorld = <<"Hello World">>, + <<X || <<X:1/binary>> <= BinHelloWorld >>, + <<0,0,0,0,0,0,0,151>> = <<151:64/signed-integer>>, + + %% Handling Boolean and Atoms + true = true andalso true, + true = false orelse true, + _ = true =:= true, + _ = false =/= true, + _ = 'HELLO' /= hello, + _ = hello == world, + + %% Handling Maps and Records + TestMap = #{a => 1, b => 2, c => 3}, + #{a := _Value, c := _} = TestMap, + _ = TestMap#{d => 4}, + Record = #test{name = ?TESTMACRO}, + _ = Record#test.name, + + %% Conditionals + case TestMap of + #{b := B} -> + B; + _ -> + ok + end, + if + erlang:is_map(TestMap) -> + map; + true -> + test_function(1) + end, + + %% Messaging + Self = erlang:self(), + Self ! hello_world, + receive + hello_world -> + ok; + _ -> + io:format("unknown message") + after 1000 -> + timeout + end, + ok. + +test_function(N) when erlang:is_integer(N) -> integer; +test_function([_|_]) -> list; +test_function(<<_/binary>>) -> binary; +test_function(_) -> + undefined. diff --git a/tests/syntax-tests/source/Erlang/bat_erlang.erl b/tests/syntax-tests/source/Erlang/bat_erlang.erl new file mode 100644 index 00000000..77d3fffb --- /dev/null +++ b/tests/syntax-tests/source/Erlang/bat_erlang.erl @@ -0,0 +1,72 @@ +-module(bat_erlang). + +-export([main/0]). + +-record(test, { + name :: list(), + data :: binary() +}). + +-define(TESTMACRO, "testmacro"). + +-spec main() -> ok. +main() -> + %% Handling Lists and Numbers + List = [1, 2, 3, 4, $6, 2#00111], + _Sum = lists:sum(List), + _ = [(N * N) + N / N - N || N <- List, N > 2], + [_Head, _SecondHead | _Tail] = List, + _ = [1, atom, [list], <<"binary">>, {tuple, tuple}, #{map => key}, #test{name = "record"}], + + %% Handling Binaries + BinHelloWorld = <<"Hello World">>, + <> <= BinHelloWorld >>, + <<0,0,0,0,0,0,0,151>> = <<151:64/signed-integer>>, + + %% Handling Boolean and Atoms + true = true andalso true, + true = false orelse true, + _ = true =:= true, + _ = false =/= true, + _ = 'HELLO' /= hello, + _ = hello == world, + + %% Handling Maps and Records + TestMap = #{a => 1, b => 2, c => 3}, + #{a := _Value, c := _} = TestMap, + _ = TestMap#{d => 4}, + Record = #test{name = ?TESTMACRO}, + _ = Record#test.name, + + %% Conditionals + case TestMap of + #{b := B} -> + B; + _ -> + ok + end, + if + erlang:is_map(TestMap) -> + map; + true -> + test_function(1) + end, + + %% Messaging + Self = erlang:self(), + Self ! hello_world, + receive + hello_world -> + ok; + _ -> + io:format("unknown message") + after 1000 -> + timeout + end, + ok. + +test_function(N) when erlang:is_integer(N) -> integer; +test_function([_|_]) -> list; +test_function(<<_/binary>>) -> binary; +test_function(_) -> + undefined. From 06d0c8f0565f8ad9bd4d78df1a33500e1178abf4 Mon Sep 17 00:00:00 2001 From: Daniel Wolbach Date: Fri, 9 Oct 2020 21:47:02 +0200 Subject: [PATCH 023/243] add CMake syntax highlighting test --- .../highlighted/CMake/CMakeLists.txt | 16 ++++++++++++++++ tests/syntax-tests/source/CMake/CMakeLists.txt | 16 ++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 tests/syntax-tests/highlighted/CMake/CMakeLists.txt create mode 100644 tests/syntax-tests/source/CMake/CMakeLists.txt diff --git a/tests/syntax-tests/highlighted/CMake/CMakeLists.txt b/tests/syntax-tests/highlighted/CMake/CMakeLists.txt new file mode 100644 index 00000000..e4f9e4cc --- /dev/null +++ b/tests/syntax-tests/highlighted/CMake/CMakeLists.txt @@ -0,0 +1,16 @@ +# This is a file for testing syntax highlighting. +cmake_minimum_required(VERSION 3.13) +project(hello-bat VERSION 0.0.1 LANGUAGES C) + +set(SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/src/") +file(GLOB_RECURSE SOURCES "${SOURCE_DIR}/*.c") + +add_executable(hello-bat SOURCES) + +find_package(assimp CONFIG) +target_link_libraries(hello-bat assimp) + +option("ENABLE_TESTS" OFF) +if(ENABLE_TESTS) + add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/tests/") +endif() diff --git a/tests/syntax-tests/source/CMake/CMakeLists.txt b/tests/syntax-tests/source/CMake/CMakeLists.txt new file mode 100644 index 00000000..ff894ede --- /dev/null +++ b/tests/syntax-tests/source/CMake/CMakeLists.txt @@ -0,0 +1,16 @@ +# This is a file for testing syntax highlighting. +cmake_minimum_required(VERSION 3.13) +project(hello-bat VERSION 0.0.1 LANGUAGES C) + +set(SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/src/") +file(GLOB_RECURSE SOURCES "${SOURCE_DIR}/*.c") + +add_executable(hello-bat SOURCES) + +find_package(assimp CONFIG) +target_link_libraries(hello-bat assimp) + +option("ENABLE_TESTS" OFF) +if(ENABLE_TESTS) + add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/tests/") +endif() From e7a3f34959f9c20344c44469581488784d3153b3 Mon Sep 17 00:00:00 2001 From: Akshat Gadhwal Date: Tue, 6 Oct 2020 20:16:49 +0530 Subject: [PATCH 024/243] ADDED test file for R --- tests/syntax-tests/highlighted/R/test.r | 170 ++++++++++++++++++++++++ tests/syntax-tests/source/R/test.r | 170 ++++++++++++++++++++++++ 2 files changed, 340 insertions(+) create mode 100644 tests/syntax-tests/highlighted/R/test.r create mode 100644 tests/syntax-tests/source/R/test.r diff --git a/tests/syntax-tests/highlighted/R/test.r b/tests/syntax-tests/highlighted/R/test.r new file mode 100644 index 00000000..16209b47 --- /dev/null +++ b/tests/syntax-tests/highlighted/R/test.r @@ -0,0 +1,170 @@ +# take input from the user +num = as.integer(readline(prompt="Enter a number: ")) +factorial = 1 +# check is the number is negative, positive or zero +if(num < 0) { +print("Sorry, factorial does not exist for negative numbers") +} else if(num == 0) { +print("The factorial of 0 is 1") +} else { +for(i in 1:num) { +factorial = factorial * i +} +print(paste("The factorial of", num ,"is",factorial)) +} + +x <- 0 +if (x < 0) { +print("Negative number") +} else if (x > 0) { +print("Positive number") +} else +print("Zero") + +x <- 1:5 +for (val in x) { +if (val == 3){ +next +} +print(val) +} + +x <- 1 +repeat { +print(x) +x = x+1 +if (x == 6){ +break +} +} + +`%divisible%` <- function(x,y) +{ +if (x%%y ==0) return (TRUE) +else return (FALSE) +} + +switch("length", "color" = "red", "shape" = "square", "length" = 5) +[1] 5 + +recursive.factorial <- function(x) { +if (x == 0) return (1) +else return (x * recursive.factorial(x-1)) +} + +pow <- function(x, y) { +# function to print x raised to the power y +result <- x^y +print(paste(x,"raised to the power", y, "is", result)) +} + +A <- read.table("x.data", sep=",", + col.names=c("year", "my1", "my2")) +nrow(A) # Count the rows in A + +summary(A$year)  + +A$newcol <- A$my1 + A$my2 # Makes a new +newvar <- A$my1 - A$my2 # Makes a  +A$my1 <- NULL # Removes  +str(A) +summary(A) +library(Hmisc)  +contents(A) +describe(A) + +set.seed(102) # This yields a good illustration. +x <- sample(1:3, 15, replace=TRUE) +education <- factor(x, labels=c("None", "School", "College")) +x <- sample(1:2, 15, replace=TRUE) +gender <- factor(x, labels=c("Male", "Female")) +age <- runif(15, min=20,max=60) + +D <- data.frame(age, gender, education) +rm(x,age,gender,education) +print(D) + +# Table about education +table(D$education) + +# Table about education and gender -- +table(D$gender, D$education) +# Joint distribution of education and gender -- +table(D$gender, D$education)/nrow(D) + +# Add in the marginal distributions also +addmargins(table(D$gender, D$education)) +addmargins(table(D$gender, D$education))/nrow(D) + +# Generate a good LaTeX table out of it -- +library(xtable) +xtable(addmargins(table(D$gender, D$education))/nrow(D), + digits=c(0,2,2,2,2))  + +by(D$age, D$gender, mean) +by(D$age, D$gender, sd) +by(D$age, D$gender, summary) + +a <- matrix(by(D$age, list(D$gender, D$education), mean), nrow=2) +rownames(a) <- levels(D$gender) +colnames(a) <- levels(D$education) +print(a) +print(xtable(a)) + +dat <- read.csv(file = "files/dataset-2013-01.csv", header = TRUE) +interim_object <- data.frame(rep(1:100, 10), + rep(101:200, 10), + rep(201:300, 10)) +object.size(interim_object)  +rm("interim_object")  +ls()  +rm(list = ls()) + +vector1 <- c(5,9,3) +vector2 <- c(10,11,12,13,14,15) +array1 <- array(c(vector1,vector2),dim = c(3,3,2)) +vector3 <- c(9,1,0) +vector4 <- c(6,0,11,3,14,1,2,6,9) +array2 <- array(c(vector1,vector2),dim = c(3,3,2)) +matrix1 <- array1[,,2] +matrix2 <- array2[,,2] +result <- matrix1+matrix2 +print(result) + +column.names <- c("COL1","COL2","COL3") +row.names <- c("ROW1","ROW2","ROW3") +matrix.names <- c("Matrix1","Matrix2") +result <- array(c(vector1,vector2),dim = c(3,3,2),dimnames = list(row.names, + column.names, matrix.names)) +print(result[3,,2]) +print(result[1,3,1]) +print(result[,,2]) + +# Load the package required to read JSON files. +library("rjson") +result <- fromJSON(file = "input.json") +print(result) + +x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131) +y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48) +relation <- lm(y~x) +print(relation) + +relation <- lm(y~x) +png(file = "linearregression.png") +plot(y,x,col = "blue",main = "Height & Weight Regression", +abline(lm(x~y)),cex = 1.3,pch = 16,xlab = "Weight in Kg",ylab = "Height in cm") +dev.off() + +data <- c("East","West","East","North","North","East","West","West","West","East","North") +print(data) +print(is.factor(data)) +factor_data <- factor(data) +print(factor_data) +print(is.factor(factor_data)) + +v <- c(7,12,28,3,41) + +# Give the chart file a name. +png(file = "line_chart_label_colored.jpg") +plot(v,type = "o", col = "red", xlab = "Month", ylab = "Rain fall", main = "Rain fall chart") diff --git a/tests/syntax-tests/source/R/test.r b/tests/syntax-tests/source/R/test.r new file mode 100644 index 00000000..2d67992b --- /dev/null +++ b/tests/syntax-tests/source/R/test.r @@ -0,0 +1,170 @@ +# take input from the user +num = as.integer(readline(prompt="Enter a number: ")) +factorial = 1 +# check is the number is negative, positive or zero +if(num < 0) { +print("Sorry, factorial does not exist for negative numbers") +} else if(num == 0) { +print("The factorial of 0 is 1") +} else { +for(i in 1:num) { +factorial = factorial * i +} +print(paste("The factorial of", num ,"is",factorial)) +} + +x <- 0 +if (x < 0) { +print("Negative number") +} else if (x > 0) { +print("Positive number") +} else +print("Zero") + +x <- 1:5 +for (val in x) { +if (val == 3){ +next +} +print(val) +} + +x <- 1 +repeat { +print(x) +x = x+1 +if (x == 6){ +break +} +} + +`%divisible%` <- function(x,y) +{ +if (x%%y ==0) return (TRUE) +else return (FALSE) +} + +switch("length", "color" = "red", "shape" = "square", "length" = 5) +[1] 5 + +recursive.factorial <- function(x) { +if (x == 0) return (1) +else return (x * recursive.factorial(x-1)) +} + +pow <- function(x, y) { +# function to print x raised to the power y +result <- x^y +print(paste(x,"raised to the power", y, "is", result)) +} + +A <- read.table("x.data", sep=",", + col.names=c("year", "my1", "my2")) +nrow(A) # Count the rows in A + +summary(A$year) + +A$newcol <- A$my1 + A$my2 # Makes a new +newvar <- A$my1 - A$my2 # Makes a +A$my1 <- NULL # Removes +str(A) +summary(A) +library(Hmisc) +contents(A) +describe(A) + +set.seed(102) # This yields a good illustration. +x <- sample(1:3, 15, replace=TRUE) +education <- factor(x, labels=c("None", "School", "College")) +x <- sample(1:2, 15, replace=TRUE) +gender <- factor(x, labels=c("Male", "Female")) +age <- runif(15, min=20,max=60) + +D <- data.frame(age, gender, education) +rm(x,age,gender,education) +print(D) + +# Table about education +table(D$education) + +# Table about education and gender -- +table(D$gender, D$education) +# Joint distribution of education and gender -- +table(D$gender, D$education)/nrow(D) + +# Add in the marginal distributions also +addmargins(table(D$gender, D$education)) +addmargins(table(D$gender, D$education))/nrow(D) + +# Generate a good LaTeX table out of it -- +library(xtable) +xtable(addmargins(table(D$gender, D$education))/nrow(D), + digits=c(0,2,2,2,2)) + +by(D$age, D$gender, mean) +by(D$age, D$gender, sd) +by(D$age, D$gender, summary) + +a <- matrix(by(D$age, list(D$gender, D$education), mean), nrow=2) +rownames(a) <- levels(D$gender) +colnames(a) <- levels(D$education) +print(a) +print(xtable(a)) + +dat <- read.csv(file = "files/dataset-2013-01.csv", header = TRUE) +interim_object <- data.frame(rep(1:100, 10), + rep(101:200, 10), + rep(201:300, 10)) +object.size(interim_object) +rm("interim_object") +ls() +rm(list = ls()) + +vector1 <- c(5,9,3) +vector2 <- c(10,11,12,13,14,15) +array1 <- array(c(vector1,vector2),dim = c(3,3,2)) +vector3 <- c(9,1,0) +vector4 <- c(6,0,11,3,14,1,2,6,9) +array2 <- array(c(vector1,vector2),dim = c(3,3,2)) +matrix1 <- array1[,,2] +matrix2 <- array2[,,2] +result <- matrix1+matrix2 +print(result) + +column.names <- c("COL1","COL2","COL3") +row.names <- c("ROW1","ROW2","ROW3") +matrix.names <- c("Matrix1","Matrix2") +result <- array(c(vector1,vector2),dim = c(3,3,2),dimnames = list(row.names, + column.names, matrix.names)) +print(result[3,,2]) +print(result[1,3,1]) +print(result[,,2]) + +# Load the package required to read JSON files. +library("rjson") +result <- fromJSON(file = "input.json") +print(result) + +x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131) +y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48) +relation <- lm(y~x) +print(relation) + +relation <- lm(y~x) +png(file = "linearregression.png") +plot(y,x,col = "blue",main = "Height & Weight Regression", +abline(lm(x~y)),cex = 1.3,pch = 16,xlab = "Weight in Kg",ylab = "Height in cm") +dev.off() + +data <- c("East","West","East","North","North","East","West","West","West","East","North") +print(data) +print(is.factor(data)) +factor_data <- factor(data) +print(factor_data) +print(is.factor(factor_data)) + +v <- c(7,12,28,3,41) + +# Give the chart file a name. +png(file = "line_chart_label_colored.jpg") +plot(v,type = "o", col = "red", xlab = "Month", ylab = "Rain fall", main = "Rain fall chart") From 5b095ed6f38bd54aa9d49403232bffa9918f82c1 Mon Sep 17 00:00:00 2001 From: sharkdp Date: Fri, 9 Oct 2020 22:54:45 +0200 Subject: [PATCH 025/243] Fix line endings --- tests/syntax-tests/highlighted/R/test.r | 292 ++++++++++++------------ 1 file changed, 146 insertions(+), 146 deletions(-) diff --git a/tests/syntax-tests/highlighted/R/test.r b/tests/syntax-tests/highlighted/R/test.r index 16209b47..2196edef 100644 --- a/tests/syntax-tests/highlighted/R/test.r +++ b/tests/syntax-tests/highlighted/R/test.r @@ -1,170 +1,170 @@ # take input from the user -num = as.integer(readline(prompt="Enter a number: ")) -factorial = 1 +num = as.integer(readline(prompt="Enter a number: ")) +factorial = 1 # check is the number is negative, positive or zero -if(num < 0) { -print("Sorry, factorial does not exist for negative numbers") -} else if(num == 0) { -print("The factorial of 0 is 1") -} else { -for(i in 1:num) { +if(num < 0) { +print("Sorry, factorial does not exist for negative numbers") +} else if(num == 0) { +print("The factorial of 0 is 1") +} else { +for(i in 1:num) { factorial = factorial * i -} -print(paste("The factorial of", num ,"is",factorial)) -} - -x <- 0 -if (x < 0) { -print("Negative number") -} else if (x > 0) { -print("Positive number") -} else -print("Zero") - -x <- 1:5 -for (val in x) { -if (val == 3){ -next -} -print(val) -} - -x <- 1 -repeat { -print(x) -x = x+1 -if (x == 6){ -break -} -} - -`%divisible%` <- function(x,y) -{ -if (x%%y ==0) return (TRUE) -else return (FALSE) -} - -switch("length", "color" = "red", "shape" = "square", "length" = 5) -[1] 5 - -recursive.factorial <- function(x) { -if (x == 0) return (1) -else return (x * recursive.factorial(x-1)) -} - -pow <- function(x, y) { +} +print(paste("The factorial of", num ,"is",factorial)) +} + +x <- 0 +if (x < 0) { +print("Negative number") +} else if (x > 0) { +print("Positive number") +} else +print("Zero") + +x <- 1:5 +for (val in x) { +if (val == 3){ +next +} +print(val) +} + +x <- 1 +repeat { +print(x) +x = x+1 +if (x == 6){ +break +} +} + +`%divisible%` <- function(x,y) +{ +if (x%%y ==0) return (TRUE) +else return (FALSE) +} + +switch("length", "color" = "red", "shape" = "square", "length" = 5) +[1] 5 + +recursive.factorial <- function(x) { +if (x == 0) return (1) +else return (x * recursive.factorial(x-1)) +} + +pow <- function(x, y) { # function to print x raised to the power y result <- x^y -print(paste(x,"raised to the power", y, "is", result)) -} - -A <- read.table("x.data", sep=",", - col.names=c("year", "my1", "my2")) +print(paste(x,"raised to the power", y, "is", result)) +} + +A <- read.table("x.data", sep=",", + col.names=c("year", "my1", "my2")) nrow(A) # Count the rows in A - + summary(A$year)  - + A$newcol <- A$my1 + A$my2 # Makes a new newvar <- A$my1 - A$my2 # Makes a  A$my1 <- NULL # Removes  -str(A) -summary(A) +str(A) +summary(A) library(Hmisc)  -contents(A) -describe(A) - +contents(A) +describe(A) + set.seed(102) # This yields a good illustration. -x <- sample(1:3, 15, replace=TRUE) -education <- factor(x, labels=c("None", "School", "College")) -x <- sample(1:2, 15, replace=TRUE) -gender <- factor(x, labels=c("Male", "Female")) -age <- runif(15, min=20,max=60) - -D <- data.frame(age, gender, education) -rm(x,age,gender,education) -print(D) - +x <- sample(1:3, 15, replace=TRUE) +education <- factor(x, labels=c("None", "School", "College")) +x <- sample(1:2, 15, replace=TRUE) +gender <- factor(x, labels=c("Male", "Female")) +age <- runif(15, min=20,max=60) + +D <- data.frame(age, gender, education) +rm(x,age,gender,education) +print(D) + # Table about education -table(D$education) - +table(D$education) + # Table about education and gender -- -table(D$gender, D$education) +table(D$gender, D$education) # Joint distribution of education and gender -- -table(D$gender, D$education)/nrow(D) - +table(D$gender, D$education)/nrow(D) + # Add in the marginal distributions also -addmargins(table(D$gender, D$education)) -addmargins(table(D$gender, D$education))/nrow(D) - +addmargins(table(D$gender, D$education)) +addmargins(table(D$gender, D$education))/nrow(D) + # Generate a good LaTeX table out of it -- -library(xtable) -xtable(addmargins(table(D$gender, D$education))/nrow(D), +library(xtable) +xtable(addmargins(table(D$gender, D$education))/nrow(D),  digits=c(0,2,2,2,2))  - -by(D$age, D$gender, mean) -by(D$age, D$gender, sd) -by(D$age, D$gender, summary) - -a <- matrix(by(D$age, list(D$gender, D$education), mean), nrow=2) -rownames(a) <- levels(D$gender) -colnames(a) <- levels(D$education) -print(a) -print(xtable(a)) - -dat <- read.csv(file = "files/dataset-2013-01.csv", header = TRUE) -interim_object <- data.frame(rep(1:100, 10), - rep(101:200, 10), - rep(201:300, 10)) + +by(D$age, D$gender, mean) +by(D$age, D$gender, sd) +by(D$age, D$gender, summary) + +a <- matrix(by(D$age, list(D$gender, D$education), mean), nrow=2) +rownames(a) <- levels(D$gender) +colnames(a) <- levels(D$education) +print(a) +print(xtable(a)) + +dat <- read.csv(file = "files/dataset-2013-01.csv", header = TRUE) +interim_object <- data.frame(rep(1:100, 10), + rep(101:200, 10), + rep(201:300, 10)) object.size(interim_object)  rm("interim_object")  ls()  -rm(list = ls()) - -vector1 <- c(5,9,3) -vector2 <- c(10,11,12,13,14,15) -array1 <- array(c(vector1,vector2),dim = c(3,3,2)) -vector3 <- c(9,1,0) -vector4 <- c(6,0,11,3,14,1,2,6,9) -array2 <- array(c(vector1,vector2),dim = c(3,3,2)) -matrix1 <- array1[,,2] -matrix2 <- array2[,,2] +rm(list = ls()) + +vector1 <- c(5,9,3) +vector2 <- c(10,11,12,13,14,15) +array1 <- array(c(vector1,vector2),dim = c(3,3,2)) +vector3 <- c(9,1,0) +vector4 <- c(6,0,11,3,14,1,2,6,9) +array2 <- array(c(vector1,vector2),dim = c(3,3,2)) +matrix1 <- array1[,,2] +matrix2 <- array2[,,2] result <- matrix1+matrix2 -print(result) - -column.names <- c("COL1","COL2","COL3") -row.names <- c("ROW1","ROW2","ROW3") -matrix.names <- c("Matrix1","Matrix2") -result <- array(c(vector1,vector2),dim = c(3,3,2),dimnames = list(row.names, - column.names, matrix.names)) -print(result[3,,2]) -print(result[1,3,1]) -print(result[,,2]) - +print(result) + +column.names <- c("COL1","COL2","COL3") +row.names <- c("ROW1","ROW2","ROW3") +matrix.names <- c("Matrix1","Matrix2") +result <- array(c(vector1,vector2),dim = c(3,3,2),dimnames = list(row.names, + column.names, matrix.names)) +print(result[3,,2]) +print(result[1,3,1]) +print(result[,,2]) + # Load the package required to read JSON files. -library("rjson") -result <- fromJSON(file = "input.json") -print(result) - -x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131) -y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48) -relation <- lm(y~x) -print(relation) - -relation <- lm(y~x) -png(file = "linearregression.png") -plot(y,x,col = "blue",main = "Height & Weight Regression", -abline(lm(x~y)),cex = 1.3,pch = 16,xlab = "Weight in Kg",ylab = "Height in cm") -dev.off() - -data <- c("East","West","East","North","North","East","West","West","West","East","North") -print(data) -print(is.factor(data)) -factor_data <- factor(data) -print(factor_data) -print(is.factor(factor_data)) - -v <- c(7,12,28,3,41) - +library("rjson") +result <- fromJSON(file = "input.json") +print(result) + +x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131) +y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48) +relation <- lm(y~x) +print(relation) + +relation <- lm(y~x) +png(file = "linearregression.png") +plot(y,x,col = "blue",main = "Height & Weight Regression", +abline(lm(x~y)),cex = 1.3,pch = 16,xlab = "Weight in Kg",ylab = "Height in cm") +dev.off() + +data <- c("East","West","East","North","North","East","West","West","West","East","North") +print(data) +print(is.factor(data)) +factor_data <- factor(data) +print(factor_data) +print(is.factor(factor_data)) + +v <- c(7,12,28,3,41) + # Give the chart file a name. -png(file = "line_chart_label_colored.jpg") -plot(v,type = "o", col = "red", xlab = "Month", ylab = "Rain fall", main = "Rain fall chart") +png(file = "line_chart_label_colored.jpg") +plot(v,type = "o", col = "red", xlab = "Month", ylab = "Rain fall", main = "Rain fall chart") From fd01f0a0ee275e39569ce4aed2a7e2377b148d69 Mon Sep 17 00:00:00 2001 From: Akshat Gadhwal Date: Tue, 6 Oct 2020 16:53:25 +0530 Subject: [PATCH 026/243] ADDED swift test file for syntax highlighting --- .../syntax-tests/highlighted/Swift/test.swift | 268 ++++++++++++++++++ tests/syntax-tests/source/Swift/test.swift | 268 ++++++++++++++++++ 2 files changed, 536 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Swift/test.swift create mode 100644 tests/syntax-tests/source/Swift/test.swift diff --git a/tests/syntax-tests/highlighted/Swift/test.swift b/tests/syntax-tests/highlighted/Swift/test.swift new file mode 100644 index 00000000..8c414b45 --- /dev/null +++ b/tests/syntax-tests/highlighted/Swift/test.swift @@ -0,0 +1,268 @@ +class Person { +// We can define class property here  +var age = 25 +// Implement Class initializer. Initializers are called when a new object of this class is created  +init() {  + print(“A new instance of this class Person is created.”)  + }  +}  +// We can now create an instance of class Person - an object - by putting parentheses after the class name  +let personObj = Person() +// Once an instance of Person class is created we can access its properties using the dot “.” syntax.  +print(“This person age is \(personObj.age)”) + +import Foundation +class Friend : Comparable { + let name : String + let age : Int +  + init(name : String, age: Int) { + self.name = name + self.age = age + } +} +func < (lhs: Friend, rhs: Friend) -> Bool { + return lhs.age < rhs.age } func > (lhs: Friend, rhs: Friend) -> Bool { + return lhs.age > rhs.age +} +func == (lhs: Friend, rhs: Friend) -> Bool { + var returnValue = false + if (lhs.name == rhs.name) && (lhs.age == rhs.age) + { + returnValue = true + } + return returnValue +} + + let friend1 = Friend(name: "Sergey", age: 35) + let friend2 = Friend(name: "Sergey", age: 30) +  + print("\Compare Friend object. Same person? (friend1 == friend2)") + +func sayHelloWorld() { + print("Hello World") +} +// Call function  +sayHelloWorld() + +func printOutFriendNames(names: String...) { +  + for name in names { +  + print(name) + } +  +} +// Call the printOutFriendNames with two parameters  +printOutFriendNames("Sergey", "Bill") +// Call the function with more parameters  +printOutFriendNames("Sergey", "Bill", "Max") + +let simpleClosure = { + print("From a simpleClosure") +} +// Call closure  +simpleClosure()  + +let fullName = { (firstName:String, lastName:String)->String in + return firstName + " " + lastName +} +// Call Closure  +let myFullName = fullName("Sergey", "Kargopolov") +print("My full name is \(myFullName)") + +let myDictionary = [String:String]() +// Another way to create an empty dictionary  +let myDictionary2:[String:String] = [:] +// Keys in dictionary can also be of type Int  +let myDictionary3 = [Int:String]() + +var myDictionary = ["first_name": "Sergey", "last_name": "Kargopolov"] +// print to preview  +print(myDictionary) +// Add a new key with a value  +myDictionary["user_id"] = "f5h7ru0tJurY8f7g5s6fd" +// We should now have 3 key value pairs printed  +print(myDictionary) + +var myDictionary = ["first_name": "Sergey", "last_name": "Kargopolov"] +// Loop through dictionary keys and print values  +for (key,value) in myDictionary { + print("\(key) = \(value)") +} + class Friend { + let name : String + let age : Int +  + init(name : String, age: Int) { + self.name = name + self.age = age + } +} + + var friends:[Friend] = [] +  + let friend1 = Friend(name: "Sergey", age: 30) + let friend2 = Friend(name: "Bill", age: 35) + let friend3 = Friend(name: "Michael", age: 21) +  + friends.append(friend1) + friends.append(friend2) + friends.append(friend3) +  + printFriends(friends: friends) +  + // Get sorted array in descending order (largest to the smallest number)  + let sortedFriends = friends.sorted(by: { $0.age > $1.age }) + printFriends(friends: sortedFriends) +  + // Get sorted array in ascending order (smallest to the largest number)  + let sortedFriendsAscendingOrder = friends.sorted(by: { $0.age < $1.age }) + printFriends(friends: sortedFriendsAscendingOrder) + + + func printFriends(friends: [Friend]) + { + for friendEntry in friends { + print("Name: \(friendEntry.name), age: \(friendEntry.age)") + } + } + +import UIKit +class ViewController: UIViewController { +override func viewDidLoad() { + super.viewDidLoad() +} +override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) +  + // Create destination URL   + let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL! + let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg") +  + //Create URL to the source file you want to download  + let fileURL = URL(string: "https://s3.amazonaws.com/learn-swift/IMG_0001.JPG") +  + let sessionConfig = URLSessionConfiguration.default + let session = URLSession(configuration: sessionConfig) +  + let request = URLRequest(url:fileURL!) +  + let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in + if let tempLocalUrl = tempLocalUrl, error == nil { + // Success  + if let statusCode = (response as? HTTPURLResponse)?.statusCode { + print("Successfully downloaded. Status code: \(statusCode)") + } +  + do { + try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl) + } catch (let writeError) { + print("Error creating a file \(destinationFileUrl) : \(writeError)") + } +  + } else { + print("Error took place while downloading a file. Error description: %@", error?.localizedDescription); + } + } + task.resume() +  + } +} + + do { +  + // Convert JSON Object received from server side into Swift NSArray.  + // Note the use "try"  + if let convertedJsonIntoArray = try JSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray { + } +  + } catch let error as NSError { + print(error.localizedDescription) + } + +DispatchQueue.global(qos: .userInitiated).async { + // Do some time consuming task in this background thread  + // Mobile app will remain to be responsive to user actions  +  + print("Performing time consuming task in this background thread") +  + DispatchQueue.main.async { + // Task consuming task has completed  + // Update UI from this block of code  + print("Time consuming task has completed. From here we are allowed to update user interface.") + } + } + +import UIKit +class ViewController: UIViewController { +  + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib.  +  + let button = UIButton(type: UIButtonType.system) as UIButton +  + let xPostion:CGFloat = 50 + let yPostion:CGFloat = 100 + let buttonWidth:CGFloat = 150 + let buttonHeight:CGFloat = 45 +  + button.frame = CGRect(x:xPostion, y:yPostion, width:buttonWidth, height:buttonHeight) +  + button.backgroundColor = UIColor.lightGray + button.setTitle("Tap me", for: UIControlState.normal) + button.tintColor = UIColor.black + button.addTarget(self, action: #selector(ViewController.buttonAction(_:)), for: .touchUpInside) +  + self.view.addSubview(button) + } +  + func buttonAction(_ sender:UIButton!) + { + print("Button tapped") + } +  + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated.  + } +  +  +} + +import UIKit +class ViewController: UIViewController { +  + override func viewDidLoad() { + super.viewDidLoad() +  + //Create Activity Indicator  + let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray) +  + // Position Activity Indicator in the center of the main view  + myActivityIndicator.center = view.center +  + // If needed, you can prevent Acivity Indicator from hiding when stopAnimating() is called  + myActivityIndicator.hidesWhenStopped = false +  + // Start Activity Indicator  + myActivityIndicator.startAnimating() +  + // Call stopAnimating() when need to stop activity indicator  + //myActivityIndicator.stopAnimating()  +  +  + view.addSubview(myActivityIndicator) + } +  + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + } +  +} + + + + + diff --git a/tests/syntax-tests/source/Swift/test.swift b/tests/syntax-tests/source/Swift/test.swift new file mode 100644 index 00000000..db7ac439 --- /dev/null +++ b/tests/syntax-tests/source/Swift/test.swift @@ -0,0 +1,268 @@ +class Person { +// We can define class property here +var age = 25 +// Implement Class initializer. Initializers are called when a new object of this class is created +init() { + print(“A new instance of this class Person is created.”) + } +} +// We can now create an instance of class Person - an object - by putting parentheses after the class name +let personObj = Person() +// Once an instance of Person class is created we can access its properties using the dot “.” syntax. +print(“This person age is \(personObj.age)”) + +import Foundation +class Friend : Comparable { + let name : String + let age : Int + + init(name : String, age: Int) { + self.name = name + self.age = age + } +} +func < (lhs: Friend, rhs: Friend) -> Bool { + return lhs.age < rhs.age } func > (lhs: Friend, rhs: Friend) -> Bool { + return lhs.age > rhs.age +} +func == (lhs: Friend, rhs: Friend) -> Bool { + var returnValue = false + if (lhs.name == rhs.name) && (lhs.age == rhs.age) + { + returnValue = true + } + return returnValue +} + + let friend1 = Friend(name: "Sergey", age: 35) + let friend2 = Friend(name: "Sergey", age: 30) + + print("\Compare Friend object. Same person? (friend1 == friend2)") + +func sayHelloWorld() { + print("Hello World") +} +// Call function +sayHelloWorld() + +func printOutFriendNames(names: String...) { + + for name in names { + + print(name) + } + +} +// Call the printOutFriendNames with two parameters +printOutFriendNames("Sergey", "Bill") +// Call the function with more parameters +printOutFriendNames("Sergey", "Bill", "Max") + +let simpleClosure = { + print("From a simpleClosure") +} +// Call closure +simpleClosure() + +let fullName = { (firstName:String, lastName:String)->String in + return firstName + " " + lastName +} +// Call Closure +let myFullName = fullName("Sergey", "Kargopolov") +print("My full name is \(myFullName)") + +let myDictionary = [String:String]() +// Another way to create an empty dictionary +let myDictionary2:[String:String] = [:] +// Keys in dictionary can also be of type Int +let myDictionary3 = [Int:String]() + +var myDictionary = ["first_name": "Sergey", "last_name": "Kargopolov"] +// print to preview +print(myDictionary) +// Add a new key with a value +myDictionary["user_id"] = "f5h7ru0tJurY8f7g5s6fd" +// We should now have 3 key value pairs printed +print(myDictionary) + +var myDictionary = ["first_name": "Sergey", "last_name": "Kargopolov"] +// Loop through dictionary keys and print values +for (key,value) in myDictionary { + print("\(key) = \(value)") +} + class Friend { + let name : String + let age : Int + + init(name : String, age: Int) { + self.name = name + self.age = age + } +} + + var friends:[Friend] = [] + + let friend1 = Friend(name: "Sergey", age: 30) + let friend2 = Friend(name: "Bill", age: 35) + let friend3 = Friend(name: "Michael", age: 21) + + friends.append(friend1) + friends.append(friend2) + friends.append(friend3) + + printFriends(friends: friends) + + // Get sorted array in descending order (largest to the smallest number) + let sortedFriends = friends.sorted(by: { $0.age > $1.age }) + printFriends(friends: sortedFriends) + + // Get sorted array in ascending order (smallest to the largest number) + let sortedFriendsAscendingOrder = friends.sorted(by: { $0.age < $1.age }) + printFriends(friends: sortedFriendsAscendingOrder) + + + func printFriends(friends: [Friend]) + { + for friendEntry in friends { + print("Name: \(friendEntry.name), age: \(friendEntry.age)") + } + } + +import UIKit +class ViewController: UIViewController { +override func viewDidLoad() { + super.viewDidLoad() +} +override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + + // Create destination URL + let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL! + let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg") + + //Create URL to the source file you want to download + let fileURL = URL(string: "https://s3.amazonaws.com/learn-swift/IMG_0001.JPG") + + let sessionConfig = URLSessionConfiguration.default + let session = URLSession(configuration: sessionConfig) + + let request = URLRequest(url:fileURL!) + + let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in + if let tempLocalUrl = tempLocalUrl, error == nil { + // Success + if let statusCode = (response as? HTTPURLResponse)?.statusCode { + print("Successfully downloaded. Status code: \(statusCode)") + } + + do { + try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl) + } catch (let writeError) { + print("Error creating a file \(destinationFileUrl) : \(writeError)") + } + + } else { + print("Error took place while downloading a file. Error description: %@", error?.localizedDescription); + } + } + task.resume() + + } +} + + do { + + // Convert JSON Object received from server side into Swift NSArray. + // Note the use "try" + if let convertedJsonIntoArray = try JSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray { + } + + } catch let error as NSError { + print(error.localizedDescription) + } + +DispatchQueue.global(qos: .userInitiated).async { + // Do some time consuming task in this background thread + // Mobile app will remain to be responsive to user actions + + print("Performing time consuming task in this background thread") + + DispatchQueue.main.async { + // Task consuming task has completed + // Update UI from this block of code + print("Time consuming task has completed. From here we are allowed to update user interface.") + } + } + +import UIKit +class ViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. + + let button = UIButton(type: UIButtonType.system) as UIButton + + let xPostion:CGFloat = 50 + let yPostion:CGFloat = 100 + let buttonWidth:CGFloat = 150 + let buttonHeight:CGFloat = 45 + + button.frame = CGRect(x:xPostion, y:yPostion, width:buttonWidth, height:buttonHeight) + + button.backgroundColor = UIColor.lightGray + button.setTitle("Tap me", for: UIControlState.normal) + button.tintColor = UIColor.black + button.addTarget(self, action: #selector(ViewController.buttonAction(_:)), for: .touchUpInside) + + self.view.addSubview(button) + } + + func buttonAction(_ sender:UIButton!) + { + print("Button tapped") + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + +} + +import UIKit +class ViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + //Create Activity Indicator + let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray) + + // Position Activity Indicator in the center of the main view + myActivityIndicator.center = view.center + + // If needed, you can prevent Acivity Indicator from hiding when stopAnimating() is called + myActivityIndicator.hidesWhenStopped = false + + // Start Activity Indicator + myActivityIndicator.startAnimating() + + // Call stopAnimating() when need to stop activity indicator + //myActivityIndicator.stopAnimating() + + + view.addSubview(myActivityIndicator) + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + } + +} + + + + + From fdef133d3dc78fb5926a6a7d28ac2d3150863ef9 Mon Sep 17 00:00:00 2001 From: Akshat Gadhwal Date: Tue, 6 Oct 2020 20:56:37 +0530 Subject: [PATCH 027/243] Update test.swift --- tests/syntax-tests/source/Swift/test.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/syntax-tests/source/Swift/test.swift b/tests/syntax-tests/source/Swift/test.swift index db7ac439..b27d36ba 100644 --- a/tests/syntax-tests/source/Swift/test.swift +++ b/tests/syntax-tests/source/Swift/test.swift @@ -22,7 +22,7 @@ class Friend : Comparable { } } func < (lhs: Friend, rhs: Friend) -> Bool { - return lhs.age < rhs.age } func > (lhs: Friend, rhs: Friend) -> Bool { + return lhs.age < rhs.age }; func > (lhs: Friend, rhs: Friend) -> Bool { return lhs.age > rhs.age } func == (lhs: Friend, rhs: Friend) -> Bool { @@ -37,7 +37,7 @@ func == (lhs: Friend, rhs: Friend) -> Bool { let friend1 = Friend(name: "Sergey", age: 35) let friend2 = Friend(name: "Sergey", age: 30) - print("\Compare Friend object. Same person? (friend1 == friend2)") + print("Compare Friend object. Same person? (friend1 == friend2)") func sayHelloWorld() { print("Hello World") From a81254ed2a5066483ef4705c4d2a32ade7d5464e Mon Sep 17 00:00:00 2001 From: sharkdp Date: Fri, 9 Oct 2020 22:55:16 +0200 Subject: [PATCH 028/243] Fix line endings --- .../syntax-tests/highlighted/Swift/test.swift | 536 +++++++++--------- 1 file changed, 268 insertions(+), 268 deletions(-) diff --git a/tests/syntax-tests/highlighted/Swift/test.swift b/tests/syntax-tests/highlighted/Swift/test.swift index 8c414b45..e31eb16a 100644 --- a/tests/syntax-tests/highlighted/Swift/test.swift +++ b/tests/syntax-tests/highlighted/Swift/test.swift @@ -1,268 +1,268 @@ -class Person { -// We can define class property here  -var age = 25 -// Implement Class initializer. Initializers are called when a new object of this class is created  -init() {  - print(“A new instance of this class Person is created.”)  - }  -}  -// We can now create an instance of class Person - an object - by putting parentheses after the class name  -let personObj = Person() -// Once an instance of Person class is created we can access its properties using the dot “.” syntax.  -print(“This person age is \(personObj.age)”) - -import Foundation -class Friend : Comparable { - let name : String - let age : Int -  - init(name : String, age: Int) { - self.name = name - self.age = age - } -} -func < (lhs: Friend, rhs: Friend) -> Bool { - return lhs.age < rhs.age } func > (lhs: Friend, rhs: Friend) -> Bool { - return lhs.age > rhs.age -} -func == (lhs: Friend, rhs: Friend) -> Bool { - var returnValue = false - if (lhs.name == rhs.name) && (lhs.age == rhs.age) - { - returnValue = true - } - return returnValue -} - - let friend1 = Friend(name: "Sergey", age: 35) - let friend2 = Friend(name: "Sergey", age: 30) -  - print("\Compare Friend object. Same person? (friend1 == friend2)") - -func sayHelloWorld() { - print("Hello World") -} -// Call function  -sayHelloWorld() - -func printOutFriendNames(names: String...) { -  - for name in names { -  - print(name) - } -  -} -// Call the printOutFriendNames with two parameters  -printOutFriendNames("Sergey", "Bill") -// Call the function with more parameters  -printOutFriendNames("Sergey", "Bill", "Max") - -let simpleClosure = { - print("From a simpleClosure") -} -// Call closure  -simpleClosure()  - -let fullName = { (firstName:String, lastName:String)->String in - return firstName + " " + lastName -} -// Call Closure  -let myFullName = fullName("Sergey", "Kargopolov") -print("My full name is \(myFullName)") - -let myDictionary = [String:String]() -// Another way to create an empty dictionary  -let myDictionary2:[String:String] = [:] -// Keys in dictionary can also be of type Int  -let myDictionary3 = [Int:String]() - -var myDictionary = ["first_name": "Sergey", "last_name": "Kargopolov"] -// print to preview  -print(myDictionary) -// Add a new key with a value  -myDictionary["user_id"] = "f5h7ru0tJurY8f7g5s6fd" -// We should now have 3 key value pairs printed  -print(myDictionary) - -var myDictionary = ["first_name": "Sergey", "last_name": "Kargopolov"] -// Loop through dictionary keys and print values  -for (key,value) in myDictionary { - print("\(key) = \(value)") -} - class Friend { - let name : String - let age : Int -  - init(name : String, age: Int) { - self.name = name - self.age = age - } -} - - var friends:[Friend] = [] -  - let friend1 = Friend(name: "Sergey", age: 30) - let friend2 = Friend(name: "Bill", age: 35) - let friend3 = Friend(name: "Michael", age: 21) -  - friends.append(friend1) - friends.append(friend2) - friends.append(friend3) -  - printFriends(friends: friends) -  - // Get sorted array in descending order (largest to the smallest number)  - let sortedFriends = friends.sorted(by: { $0.age > $1.age }) - printFriends(friends: sortedFriends) -  - // Get sorted array in ascending order (smallest to the largest number)  - let sortedFriendsAscendingOrder = friends.sorted(by: { $0.age < $1.age }) - printFriends(friends: sortedFriendsAscendingOrder) - - - func printFriends(friends: [Friend]) - { - for friendEntry in friends { - print("Name: \(friendEntry.name), age: \(friendEntry.age)") - } - } - -import UIKit -class ViewController: UIViewController { -override func viewDidLoad() { - super.viewDidLoad() -} -override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) -  - // Create destination URL   - let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL! - let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg") -  - //Create URL to the source file you want to download  - let fileURL = URL(string: "https://s3.amazonaws.com/learn-swift/IMG_0001.JPG") -  - let sessionConfig = URLSessionConfiguration.default - let session = URLSession(configuration: sessionConfig) -  - let request = URLRequest(url:fileURL!) -  - let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in - if let tempLocalUrl = tempLocalUrl, error == nil { - // Success  - if let statusCode = (response as? HTTPURLResponse)?.statusCode { - print("Successfully downloaded. Status code: \(statusCode)") - } -  - do { - try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl) - } catch (let writeError) { - print("Error creating a file \(destinationFileUrl) : \(writeError)") - } -  - } else { - print("Error took place while downloading a file. Error description: %@", error?.localizedDescription); - } - } - task.resume() -  - } -} - - do { -  - // Convert JSON Object received from server side into Swift NSArray.  - // Note the use "try"  - if let convertedJsonIntoArray = try JSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray { - } -  - } catch let error as NSError { - print(error.localizedDescription) - } - -DispatchQueue.global(qos: .userInitiated).async { - // Do some time consuming task in this background thread  - // Mobile app will remain to be responsive to user actions  -  - print("Performing time consuming task in this background thread") -  - DispatchQueue.main.async { - // Task consuming task has completed  - // Update UI from this block of code  - print("Time consuming task has completed. From here we are allowed to update user interface.") - } - } - -import UIKit -class ViewController: UIViewController { -  - override func viewDidLoad() { - super.viewDidLoad() - // Do any additional setup after loading the view, typically from a nib.  -  - let button = UIButton(type: UIButtonType.system) as UIButton -  - let xPostion:CGFloat = 50 - let yPostion:CGFloat = 100 - let buttonWidth:CGFloat = 150 - let buttonHeight:CGFloat = 45 -  - button.frame = CGRect(x:xPostion, y:yPostion, width:buttonWidth, height:buttonHeight) -  - button.backgroundColor = UIColor.lightGray - button.setTitle("Tap me", for: UIControlState.normal) - button.tintColor = UIColor.black - button.addTarget(self, action: #selector(ViewController.buttonAction(_:)), for: .touchUpInside) -  - self.view.addSubview(button) - } -  - func buttonAction(_ sender:UIButton!) - { - print("Button tapped") - } -  - override func didReceiveMemoryWarning() { - super.didReceiveMemoryWarning() - // Dispose of any resources that can be recreated.  - } -  -  -} - -import UIKit -class ViewController: UIViewController { -  - override func viewDidLoad() { - super.viewDidLoad() -  - //Create Activity Indicator  - let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray) -  - // Position Activity Indicator in the center of the main view  - myActivityIndicator.center = view.center -  - // If needed, you can prevent Acivity Indicator from hiding when stopAnimating() is called  - myActivityIndicator.hidesWhenStopped = false -  - // Start Activity Indicator  - myActivityIndicator.startAnimating() -  - // Call stopAnimating() when need to stop activity indicator  - //myActivityIndicator.stopAnimating()  -  -  - view.addSubview(myActivityIndicator) - } -  - override func didReceiveMemoryWarning() { - super.didReceiveMemoryWarning() - } -  -} - - - - - +class Person { +// We can define class property here +var age = 25 +// Implement Class initializer. Initializers are called when a new object of this class is created +init() {  + print(“A new instance of this class Person is created.”)  + }  +}  +// We can now create an instance of class Person - an object - by putting parentheses after the class name +let personObj = Person() +// Once an instance of Person class is created we can access its properties using the dot “.” syntax. +print(“This person age is \(personObj.age)”) + +import Foundation +class Friend : Comparable { + let name : String + let age : Int +  + init(name : String, age: Int) { + self.name = name + self.age = age + } +} +func < (lhs: Friend, rhs: Friend) -> Bool { + return lhs.age < rhs.age }; func > (lhs: Friend, rhs: Friend) -> Bool { + return lhs.age > rhs.age +} +func == (lhs: Friend, rhs: Friend) -> Bool { + var returnValue = false + if (lhs.name == rhs.name) && (lhs.age == rhs.age) + { + returnValue = true + } + return returnValue +} + + let friend1 = Friend(name: "Sergey", age: 35) + let friend2 = Friend(name: "Sergey", age: 30) +  + print("Compare Friend object. Same person? (friend1 == friend2)") + +func sayHelloWorld() { + print("Hello World") +} +// Call function +sayHelloWorld() + +func printOutFriendNames(names: String...) { +  + for name in names { +  + print(name) + } +  +} +// Call the printOutFriendNames with two parameters +printOutFriendNames("Sergey", "Bill") +// Call the function with more parameters +printOutFriendNames("Sergey", "Bill", "Max") + +let simpleClosure = { + print("From a simpleClosure") +} +// Call closure +simpleClosure()  + +let fullName = { (firstName:String, lastName:String)->String in + return firstName + " " + lastName +} +// Call Closure +let myFullName = fullName("Sergey", "Kargopolov") +print("My full name is \(myFullName)") + +let myDictionary = [String:String]() +// Another way to create an empty dictionary +let myDictionary2:[String:String] = [:] +// Keys in dictionary can also be of type Int +let myDictionary3 = [Int:String]() + +var myDictionary = ["first_name": "Sergey", "last_name": "Kargopolov"] +// print to preview +print(myDictionary) +// Add a new key with a value +myDictionary["user_id"] = "f5h7ru0tJurY8f7g5s6fd" +// We should now have 3 key value pairs printed +print(myDictionary) + +var myDictionary = ["first_name": "Sergey", "last_name": "Kargopolov"] +// Loop through dictionary keys and print values +for (key,value) in myDictionary { + print("\(key) = \(value)") +} + class Friend { + let name : String + let age : Int +  + init(name : String, age: Int) { + self.name = name + self.age = age + } +} + + var friends:[Friend] = [] +  + let friend1 = Friend(name: "Sergey", age: 30) + let friend2 = Friend(name: "Bill", age: 35) + let friend3 = Friend(name: "Michael", age: 21) +  + friends.append(friend1) + friends.append(friend2) + friends.append(friend3) +  + printFriends(friends: friends) +  + // Get sorted array in descending order (largest to the smallest number) + let sortedFriends = friends.sorted(by: { $0.age > $1.age }) + printFriends(friends: sortedFriends) +  + // Get sorted array in ascending order (smallest to the largest number) + let sortedFriendsAscendingOrder = friends.sorted(by: { $0.age < $1.age }) + printFriends(friends: sortedFriendsAscendingOrder) + + + func printFriends(friends: [Friend]) + { + for friendEntry in friends { + print("Name: \(friendEntry.name), age: \(friendEntry.age)") + } + } + +import UIKit +class ViewController: UIViewController { +override func viewDidLoad() { + super.viewDidLoad() +} +override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) +  + // Create destination URL  + let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL! + let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg") +  + //Create URL to the source file you want to download + let fileURL = URL(string: "https://s3.amazonaws.com/learn-swift/IMG_0001.JPG") +  + let sessionConfig = URLSessionConfiguration.default + let session = URLSession(configuration: sessionConfig) +  + let request = URLRequest(url:fileURL!) +  + let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in + if let tempLocalUrl = tempLocalUrl, error == nil { + // Success + if let statusCode = (response as? HTTPURLResponse)?.statusCode { + print("Successfully downloaded. Status code: \(statusCode)") + } +  + do { + try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl) + } catch (let writeError) { + print("Error creating a file \(destinationFileUrl) : \(writeError)") + } +  + } else { + print("Error took place while downloading a file. Error description: %@", error?.localizedDescription); + } + } + task.resume() +  + } +} + + do { +  + // Convert JSON Object received from server side into Swift NSArray. + // Note the use "try" + if let convertedJsonIntoArray = try JSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray { + } +  + } catch let error as NSError { + print(error.localizedDescription) + } + +DispatchQueue.global(qos: .userInitiated).async { + // Do some time consuming task in this background thread + // Mobile app will remain to be responsive to user actions +  + print("Performing time consuming task in this background thread") +  + DispatchQueue.main.async { + // Task consuming task has completed + // Update UI from this block of code + print("Time consuming task has completed. From here we are allowed to update user interface.") + } + } + +import UIKit +class ViewController: UIViewController { +  + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. +  + let button = UIButton(type: UIButtonType.system) as UIButton +  + let xPostion:CGFloat = 50 + let yPostion:CGFloat = 100 + let buttonWidth:CGFloat = 150 + let buttonHeight:CGFloat = 45 +  + button.frame = CGRect(x:xPostion, y:yPostion, width:buttonWidth, height:buttonHeight) +  + button.backgroundColor = UIColor.lightGray + button.setTitle("Tap me", for: UIControlState.normal) + button.tintColor = UIColor.black + button.addTarget(self, action: #selector(ViewController.buttonAction(_:)), for: .touchUpInside) +  + self.view.addSubview(button) + } +  + func buttonAction(_ sender:UIButton!) + { + print("Button tapped") + } +  + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } +  +  +} + +import UIKit +class ViewController: UIViewController { +  + override func viewDidLoad() { + super.viewDidLoad() +  + //Create Activity Indicator + let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray) +  + // Position Activity Indicator in the center of the main view + myActivityIndicator.center = view.center +  + // If needed, you can prevent Acivity Indicator from hiding when stopAnimating() is called + myActivityIndicator.hidesWhenStopped = false +  + // Start Activity Indicator + myActivityIndicator.startAnimating() +  + // Call stopAnimating() when need to stop activity indicator + //myActivityIndicator.stopAnimating() +  +  + view.addSubview(myActivityIndicator) + } +  + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + } +  +} + + + + + From 2d5cf1d3cff272c3edf82f546a4a54dcc3010a20 Mon Sep 17 00:00:00 2001 From: Benjamin Neff Date: Fri, 9 Oct 2020 01:23:48 +0200 Subject: [PATCH 029/243] Remove gitattributes for .bat/.cmd files to make all testfiles eol=lf --- tests/.gitattributes | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tests/.gitattributes b/tests/.gitattributes index 5e4f025b..cd9cbfc3 100644 --- a/tests/.gitattributes +++ b/tests/.gitattributes @@ -4,10 +4,6 @@ snapshots/** text=auto eol=lf syntax-tests/source/** text=auto eol=lf syntax-tests/highlighted/** text=auto eol=lf -# BAT/CMD files always need CRLF EOLs -*.[Bb][Aa][Tt] text eol=crlf -*.[Cc][Mm][Dd] text eol=crlf - examples/* linguist-vendored snapshots/* linguist-vendored benchmarks/* linguist-vendored From 1f0e53a44d1729cf3ce4ff397c7fd56e3d28fb6a Mon Sep 17 00:00:00 2001 From: venky Date: Sun, 11 Oct 2020 00:54:56 +0530 Subject: [PATCH 030/243] Added BibTeX syntax tests --- tests/syntax-tests/highlighted/BibTeX/test.bib | 18 ++++++++++++++++++ tests/syntax-tests/source/BibTeX/test.bib | 18 ++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 tests/syntax-tests/highlighted/BibTeX/test.bib create mode 100644 tests/syntax-tests/source/BibTeX/test.bib diff --git a/tests/syntax-tests/highlighted/BibTeX/test.bib b/tests/syntax-tests/highlighted/BibTeX/test.bib new file mode 100644 index 00000000..4756f514 --- /dev/null +++ b/tests/syntax-tests/highlighted/BibTeX/test.bib @@ -0,0 +1,18 @@ +@book{knuth1997art, + title={The art of computer programming}, + author={Knuth, Donald Ervin}, + volume={3}, + year={1997}, + publisher={Pearson Education} +} + +@article{egholm1993pna, + title={PNA hybridizes to complementary oligonucleotides obeying the Watson--Crick hydrogen-bonding rules}, + author={Egholm, Michael and Buchardt, Ole and Christensen, Leif and Behrens, Carsten and Freier, Susan M and Driver, David A and Berg, Rolf H and Kim, Seog K and Norden, Bengt and Nielsen, Peter E}, + journal={Nature}, + volume={365}, + number={6446}, + pages={566--568}, + year={1993}, + publisher={Springer} +} diff --git a/tests/syntax-tests/source/BibTeX/test.bib b/tests/syntax-tests/source/BibTeX/test.bib new file mode 100644 index 00000000..54a1c96d --- /dev/null +++ b/tests/syntax-tests/source/BibTeX/test.bib @@ -0,0 +1,18 @@ +@book{knuth1997art, + title={The art of computer programming}, + author={Knuth, Donald Ervin}, + volume={3}, + year={1997}, + publisher={Pearson Education} +} + +@article{egholm1993pna, + title={PNA hybridizes to complementary oligonucleotides obeying the Watson--Crick hydrogen-bonding rules}, + author={Egholm, Michael and Buchardt, Ole and Christensen, Leif and Behrens, Carsten and Freier, Susan M and Driver, David A and Berg, Rolf H and Kim, Seog K and Norden, Bengt and Nielsen, Peter E}, + journal={Nature}, + volume={365}, + number={6446}, + pages={566--568}, + year={1993}, + publisher={Springer} +} From 3bcb5452aa91e527d04cbfc33f81395618db4959 Mon Sep 17 00:00:00 2001 From: "Zachary J. Rollyson" Date: Sat, 10 Oct 2020 11:23:07 -0400 Subject: [PATCH 031/243] Add HTML syntax test sample --- tests/syntax-tests/highlighted/HTML/test.html | 115 ++++++++++++++++++ tests/syntax-tests/source/HTML/test.html | 115 ++++++++++++++++++ 2 files changed, 230 insertions(+) create mode 100644 tests/syntax-tests/highlighted/HTML/test.html create mode 100644 tests/syntax-tests/source/HTML/test.html diff --git a/tests/syntax-tests/highlighted/HTML/test.html b/tests/syntax-tests/highlighted/HTML/test.html new file mode 100644 index 00000000..3df49d03 --- /dev/null +++ b/tests/syntax-tests/highlighted/HTML/test.html @@ -0,0 +1,115 @@ + +<html> +  + <head> + <title>Bat Syntax Test + <meta charset="utf-8">  + <script> + const x = 'world'; + function logGreeting() { + console.log(`Hello, ${x}`); + } +  +  + <body> + <div> + <h1>Here find some simple tags + <br /> + <p center style="color: rebeccapurple;"> + Lorem <strong>ipsum dolor sit amet consectetur adipisicing + elit. A quo, autem quaerat explicabo impedit mollitia amet molestiae + nulla cum architecto ducimus itaque sit blanditiis quasi animi optio ab + facilis nihil? +  + <p> + Here are some escaped characters: &amp; (ampersand), &agrave; (a with grave), &#8470; (numero sign). +  +  + <div> + <h1>This is a form that demonstrates loose attribute formatting + <form action="POST"> + <input + disabled + type="text" + name="text input" + id="specificTextInput" + value="yes" + /> +  +  + <div> + <h1>A table with normal closing tags + <table> + <caption> + Pet Features +  + <colgroup> + <col /> + <col /> + <col /> +  + <thead> + <tr> + <th>Feature + <th>Cat + <th>Dog +  +  + <tbody> + <tr> + <td>Tail + <td>✔ + <td>✔ +  + <tr> + <td>Eyes + <td>✔ + <td>✔ +  + <tr> + <td>Ears + <td>✔ + <td>✔ +  + <tr> + <td>Barking + <td> + <td>✔ +  + <tr> + <td>Litter Box + <td>✔ + <td> +  +  +  +  + <div> + <h1>A table without closing tags + <table> + <caption>Pet Features + <colgroup><col><col><col> + <thead> + <tr> <th>Feature <th>Cat <th>Dog + <tbody> + <tr> <td>Tail <td>✔ <td>✔ + <tr> <td>Eyes <td>✔ <td>✔ + <tr> <td>Ears <td>✔ <td>✔ + <tr> <td>Barking <td> <td>✔ + <tr> <td>Litter Box <td>✔ <td> +  +  +  + <div> + <h1>A math section with CDATA + <p>You can add a string to a number, but this stringifies the number: + <math> + <ms> + <mo>- + <mn>7 + <mo>= + <ms> +  +  +  + diff --git a/tests/syntax-tests/source/HTML/test.html b/tests/syntax-tests/source/HTML/test.html new file mode 100644 index 00000000..ccddb797 --- /dev/null +++ b/tests/syntax-tests/source/HTML/test.html @@ -0,0 +1,115 @@ + + + + + Bat Syntax Test + + + + +
+

Here find some simple tags

+
+

+ Lorem ipsum dolor sit amet consectetur adipisicing + elit. A quo, autem quaerat explicabo impedit mollitia amet molestiae + nulla cum architecto ducimus itaque sit blanditiis quasi animi optio ab + facilis nihil? +

+

+ Here are some escaped characters: & (ampersand), à (a with grave), № (numero sign). +

+
+
+

This is a form that demonstrates loose attribute formatting

+
+ +
+
+
+

A table with normal closing tags

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Pet Features +
FeatureCatDog
Tail
Eyes
Ears
Barking
Litter Box
+
+
+

A table without closing tags

+ + + + + +
Pet Features +
Feature Cat Dog +
Tail ✔ +
Eyes ✔ +
Ears ✔ +
Barking ✔ +
Litter Box +
+
+
+

A math section with CDATA

+

You can add a string to a number, but this stringifies the number:

+ + a / b + - + 7 + = + a / b - 7 + +
+ + From 457ab84065416e3d9c0ff7dc4ea7f8902fb09eb6 Mon Sep 17 00:00:00 2001 From: grg121 Date: Sat, 10 Oct 2020 21:43:11 +0200 Subject: [PATCH 032/243] Add basic Dockerfile syntax highlighting test files --- .../highlighted/Dockerfile/Dockerfile | 19 +++++++++++++++++++ .../syntax-tests/source/Dockerfile/Dockerfile | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Dockerfile/Dockerfile create mode 100644 tests/syntax-tests/source/Dockerfile/Dockerfile diff --git a/tests/syntax-tests/highlighted/Dockerfile/Dockerfile b/tests/syntax-tests/highlighted/Dockerfile/Dockerfile new file mode 100644 index 00000000..fcbe51c1 --- /dev/null +++ b/tests/syntax-tests/highlighted/Dockerfile/Dockerfile @@ -0,0 +1,19 @@ +ARG architecture=amd64 +FROM $architecture/centos:7 +LABEL com.example.version="0.2.1-beta" +ARG architecture + +ENV INTERESTING_PATH /usr/bin/interesting-software + + +COPY entrypoint.sh /usr/bin/entrypoint.sh + +RUN if [ "$architecture" = "i386" ]; then echo "Building i386 docker image" && \ + linux32 yum update -y && linux32 yum install -y mysql ; \ + else yum update -y && yum install -y mysql + +EXPOSE 80/tcp + +VOLUME [/var/lib/mysql/data] + +ENTRYPOINT ["/usr/bin/entrypoint.sh"] diff --git a/tests/syntax-tests/source/Dockerfile/Dockerfile b/tests/syntax-tests/source/Dockerfile/Dockerfile new file mode 100644 index 00000000..54a3b2c8 --- /dev/null +++ b/tests/syntax-tests/source/Dockerfile/Dockerfile @@ -0,0 +1,19 @@ +ARG architecture=amd64 +FROM $architecture/centos:7 +LABEL com.example.version="0.2.1-beta" +ARG architecture + +ENV INTERESTING_PATH /usr/bin/interesting-software + + +COPY entrypoint.sh /usr/bin/entrypoint.sh + +RUN if [ "$architecture" = "i386" ]; then echo "Building i386 docker image" && \ + linux32 yum update -y && linux32 yum install -y mysql ; \ + else yum update -y && yum install -y mysql + +EXPOSE 80/tcp + +VOLUME [/var/lib/mysql/data] + +ENTRYPOINT ["/usr/bin/entrypoint.sh"] \ No newline at end of file From f10c8ce25ea6ee40c587a4d0e1527f4846880058 Mon Sep 17 00:00:00 2001 From: "Zachary J. Rollyson" Date: Sat, 10 Oct 2020 14:41:00 -0400 Subject: [PATCH 033/243] Add GraphQl syntax test sample --- .../highlighted/GraphQL/test.graphql | 145 ++++++++++++++++++ .../syntax-tests/source/GraphQL/test.graphql | 145 ++++++++++++++++++ 2 files changed, 290 insertions(+) create mode 100644 tests/syntax-tests/highlighted/GraphQL/test.graphql create mode 100644 tests/syntax-tests/source/GraphQL/test.graphql diff --git a/tests/syntax-tests/highlighted/GraphQL/test.graphql b/tests/syntax-tests/highlighted/GraphQL/test.graphql new file mode 100644 index 00000000..28670a98 --- /dev/null +++ b/tests/syntax-tests/highlighted/GraphQL/test.graphql @@ -0,0 +1,145 @@ +# Token:: +# Punctuator +# Name +# IntValue +# FloatValue +# StringValue + +# Punctuator:: one of +# ! $ ( ) ... : = @ [ ] { | } + +# Name:: +# /[_A-Za-z][_0-9A-Za-z]*/ + +# Document : +# Definition (list) + +# Definition : +# ExecutableDefinition +# TypeSystemDefinition +# TypeSystemExtension + +# ExecutableDefinition : +# FragmentDefinition +# OperationDefintion + +# FragmentDefinition + +type someType { + id: ID +} + +fragment subsriberFields on someType { + id + name + fooInt(int: 1234, negInt: -56789, zero: 0) + fooFloat( + float: 1.1 + floatExp: 1.4e10 + floatExpSign1: 1.4e+10 + floatExpSign2: 1.5e-40 + floatExpBigE: 1.5E10 + ) + fooBool(x: true, y: false) + fooString(str: "hello", strUni: "\u2116", strEscWs: "\t") + fooLongStr( + lStr: """ + Hello Reader, + This is a long string block. + Best, + Writer + """ + ) + fooNull(nullThing: null) + fooList(numList: [1, 2, 3], strList: ["a", "b", "c"]) + fooObj(someObj: { str: "hi", int: 2 }) +} + +# OperationDefintion + +query _A1 { + getThings(strArg: "string") { + id # commas here are ignored but valid + name + } +} + +query _A2($x: String) { + someFn(episode: $x) { + name + } +} + +mutation B1 { + changeThings(intArg: 123) { + parent { + nestedField1 + nestedField2 + } + } +} + +subscription C1_Hello { + subsribePlease(floatArg: 1.4) { + id + ...subsriberFields + } +} + +# TypeSystemDefinition : +# SchemaDefinition +# TypeDefinition + +schema { + query: Query + mutation: Mutation +} + +type Query { + """ + Can provide documentation this way. + """ + scalars: Scalars + someList: SomeLists + fooBar: FooBar +} + +interface Thing { + id: ID! +} + +type Scalars implements Thing { + id: ID! + int: Int! + float: Float! + str: String! @deprecated(reason: "Need to test a directive") + bool: Boolean + type: StringTypes +} + +type SomeLists { + ints: [Int!]! +} + +type Foo { + fooVal: String +} + +type Bar { + barVal: String +} + +union FooBar = Foo | Bar + +enum StringTypes { + ONE + TWO +} + +input Xyz { + id: ID! +} + +type Mutation { + createXyz(input: xyz!): Xyz! +} diff --git a/tests/syntax-tests/source/GraphQL/test.graphql b/tests/syntax-tests/source/GraphQL/test.graphql new file mode 100644 index 00000000..6b2f63c0 --- /dev/null +++ b/tests/syntax-tests/source/GraphQL/test.graphql @@ -0,0 +1,145 @@ +# Token:: +# Punctuator +# Name +# IntValue +# FloatValue +# StringValue + +# Punctuator:: one of +# ! $ ( ) ... : = @ [ ] { | } + +# Name:: +# /[_A-Za-z][_0-9A-Za-z]*/ + +# Document : +# Definition (list) + +# Definition : +# ExecutableDefinition +# TypeSystemDefinition +# TypeSystemExtension + +# ExecutableDefinition : +# FragmentDefinition +# OperationDefintion + +# FragmentDefinition + +type someType { + id: ID +} + +fragment subsriberFields on someType { + id + name + fooInt(int: 1234, negInt: -56789, zero: 0) + fooFloat( + float: 1.1 + floatExp: 1.4e10 + floatExpSign1: 1.4e+10 + floatExpSign2: 1.5e-40 + floatExpBigE: 1.5E10 + ) + fooBool(x: true, y: false) + fooString(str: "hello", strUni: "\u2116", strEscWs: "\t") + fooLongStr( + lStr: """ + Hello Reader, + This is a long string block. + Best, + Writer + """ + ) + fooNull(nullThing: null) + fooList(numList: [1, 2, 3], strList: ["a", "b", "c"]) + fooObj(someObj: { str: "hi", int: 2 }) +} + +# OperationDefintion + +query _A1 { + getThings(strArg: "string") { + id # commas here are ignored but valid + name + } +} + +query _A2($x: String) { + someFn(episode: $x) { + name + } +} + +mutation B1 { + changeThings(intArg: 123) { + parent { + nestedField1 + nestedField2 + } + } +} + +subscription C1_Hello { + subsribePlease(floatArg: 1.4) { + id + ...subsriberFields + } +} + +# TypeSystemDefinition : +# SchemaDefinition +# TypeDefinition + +schema { + query: Query + mutation: Mutation +} + +type Query { + """ + Can provide documentation this way. + """ + scalars: Scalars + someList: SomeLists + fooBar: FooBar +} + +interface Thing { + id: ID! +} + +type Scalars implements Thing { + id: ID! + int: Int! + float: Float! + str: String! @deprecated(reason: "Need to test a directive") + bool: Boolean + type: StringTypes +} + +type SomeLists { + ints: [Int!]! +} + +type Foo { + fooVal: String +} + +type Bar { + barVal: String +} + +union FooBar = Foo | Bar + +enum StringTypes { + ONE + TWO +} + +input Xyz { + id: ID! +} + +type Mutation { + createXyz(input: xyz!): Xyz! +} From 46004001cb366a8a3f06df882eb1ce015148b1c6 Mon Sep 17 00:00:00 2001 From: Felipe Garcia Date: Sat, 10 Oct 2020 14:28:31 -0300 Subject: [PATCH 034/243] Add Clojure syntax test. --- .../syntax-tests/highlighted/Clojure/test.clj | 58 +++++++++++++++++++ tests/syntax-tests/source/Clojure/test.clj | 58 +++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Clojure/test.clj create mode 100644 tests/syntax-tests/source/Clojure/test.clj diff --git a/tests/syntax-tests/highlighted/Clojure/test.clj b/tests/syntax-tests/highlighted/Clojure/test.clj new file mode 100644 index 00000000..32903fe7 --- /dev/null +++ b/tests/syntax-tests/highlighted/Clojure/test.clj @@ -0,0 +1,58 @@ +(ns clojure-sample.core + (:gen-class)) +  + (require '[clj-time.core :as t]) + (require '[clj-time.format :as f]) +  + ;; Product record + (defrecord Product [id name available price]) +  + ;; Positional constructor + (def product1 (->Product "1" "T-Shirt 1" true 15.00)) +  + ;; Map constructor + (def product2 (map->Product + {:id "2" + :name "T-Shirt 2" + :available true + :price 20.00})) +  + ;; Nested + (def product3 {:id "1" + :name "Product 1" + :available true + :sellers [{:id "1" + :name "Seller 1" + :stock 3}, + {:id 2 + :name "Seller 2" + :stock 5}]}) +  + ;; Set + (def categories #{"shirts" "shoes" "belts"}) +  + ;; List + (def wishlist '(1 2)) +  + ;; Recursion + (defn factorial [value] (cond + (<= value 1) 1 + :else (* value (factorial (- value 1))))) +  + (def basic-formatter (f/formatter "YYYY-MM-dd hh:mm:ss")) + (defn now [] (f/unparse basic-formatter (t/now))) + (defn log + ([] (println (now) "No message")) + ([message] (println (now) message))) +  + (defn -main + [& args] + (println (:id product1)) + (println (:name product2)) + (println (:name (get (:sellers product3) 0))) + (println (first categories)) + (println wishlist) + (println (factorial 5)) + (log) + (log "Message")) +  diff --git a/tests/syntax-tests/source/Clojure/test.clj b/tests/syntax-tests/source/Clojure/test.clj new file mode 100644 index 00000000..ea24e822 --- /dev/null +++ b/tests/syntax-tests/source/Clojure/test.clj @@ -0,0 +1,58 @@ +(ns clojure-sample.core + (:gen-class)) + + (require '[clj-time.core :as t]) + (require '[clj-time.format :as f]) + + ;; Product record + (defrecord Product [id name available price]) + + ;; Positional constructor + (def product1 (->Product "1" "T-Shirt 1" true 15.00)) + + ;; Map constructor + (def product2 (map->Product + {:id "2" + :name "T-Shirt 2" + :available true + :price 20.00})) + + ;; Nested + (def product3 {:id "1" + :name "Product 1" + :available true + :sellers [{:id "1" + :name "Seller 1" + :stock 3}, + {:id 2 + :name "Seller 2" + :stock 5}]}) + + ;; Set + (def categories #{"shirts" "shoes" "belts"}) + + ;; List + (def wishlist '(1 2)) + + ;; Recursion + (defn factorial [value] (cond + (<= value 1) 1 + :else (* value (factorial (- value 1))))) + + (def basic-formatter (f/formatter "YYYY-MM-dd hh:mm:ss")) + (defn now [] (f/unparse basic-formatter (t/now))) + (defn log + ([] (println (now) "No message")) + ([message] (println (now) message))) + + (defn -main + [& args] + (println (:id product1)) + (println (:name product2)) + (println (:name (get (:sellers product3) 0))) + (println (first categories)) + (println wishlist) + (println (factorial 5)) + (log) + (log "Message")) + \ No newline at end of file From b6c1ec3a2457096e06f404425d146d23a102d175 Mon Sep 17 00:00:00 2001 From: "M. Olcay TERCANLI" Date: Sun, 11 Oct 2020 19:18:53 +0300 Subject: [PATCH 035/243] Add CpuInfo syntax test --- .../highlighted/CpuInfo/test.CpuInfo | 45 +++++++++++++++++++ .../syntax-tests/source/CpuInfo/test.CpuInfo | 45 +++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 tests/syntax-tests/highlighted/CpuInfo/test.CpuInfo create mode 100644 tests/syntax-tests/source/CpuInfo/test.CpuInfo diff --git a/tests/syntax-tests/highlighted/CpuInfo/test.CpuInfo b/tests/syntax-tests/highlighted/CpuInfo/test.CpuInfo new file mode 100644 index 00000000..993fa002 --- /dev/null +++ b/tests/syntax-tests/highlighted/CpuInfo/test.CpuInfo @@ -0,0 +1,45 @@ +processor : 0 +model name : ARMv7 Processor rev 3 (v7l) +BogoMIPS : 270.00 +Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 +CPU implementer : 0x41 +CPU architecture: 7 +CPU variant : 0x0 +CPU part : 0xd08 +CPU revision : 3 + +processor : 1 +model name : ARMv7 Processor rev 3 (v7l) +BogoMIPS : 270.00 +Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 +CPU implementer : 0x41 +CPU architecture: 7 +CPU variant : 0x0 +CPU part : 0xd08 +CPU revision : 3 + +processor : 2 +model name : ARMv7 Processor rev 3 (v7l) +BogoMIPS : 270.00 +Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 +CPU implementer : 0x41 +CPU architecture: 7 +CPU variant : 0x0 +CPU part : 0xd08 +CPU revision : 3 + +processor : 3 +model name : ARMv7 Processor rev 3 (v7l) +BogoMIPS : 270.00 +Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 +CPU implementer : 0x41 +CPU architecture: 7 +CPU variant : 0x0 +CPU part : 0xd08 +CPU revision : 3 + +Hardware : BCM2711 +Revision : b03111 +Serial : 1000000095fd9fc5 +Model : Raspberry Pi 4 Model B Rev 1.1 + diff --git a/tests/syntax-tests/source/CpuInfo/test.CpuInfo b/tests/syntax-tests/source/CpuInfo/test.CpuInfo new file mode 100644 index 00000000..120da39f --- /dev/null +++ b/tests/syntax-tests/source/CpuInfo/test.CpuInfo @@ -0,0 +1,45 @@ +processor : 0 +model name : ARMv7 Processor rev 3 (v7l) +BogoMIPS : 270.00 +Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 +CPU implementer : 0x41 +CPU architecture: 7 +CPU variant : 0x0 +CPU part : 0xd08 +CPU revision : 3 + +processor : 1 +model name : ARMv7 Processor rev 3 (v7l) +BogoMIPS : 270.00 +Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 +CPU implementer : 0x41 +CPU architecture: 7 +CPU variant : 0x0 +CPU part : 0xd08 +CPU revision : 3 + +processor : 2 +model name : ARMv7 Processor rev 3 (v7l) +BogoMIPS : 270.00 +Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 +CPU implementer : 0x41 +CPU architecture: 7 +CPU variant : 0x0 +CPU part : 0xd08 +CPU revision : 3 + +processor : 3 +model name : ARMv7 Processor rev 3 (v7l) +BogoMIPS : 270.00 +Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 +CPU implementer : 0x41 +CPU architecture: 7 +CPU variant : 0x0 +CPU part : 0xd08 +CPU revision : 3 + +Hardware : BCM2711 +Revision : b03111 +Serial : 1000000095fd9fc5 +Model : Raspberry Pi 4 Model B Rev 1.1 + From 51036ced9d2dfe8dd63e4d103560ac21e9352aaa Mon Sep 17 00:00:00 2001 From: "M. Olcay TERCANLI" Date: Sun, 11 Oct 2020 19:19:11 +0300 Subject: [PATCH 036/243] Add MemInfo syntax test --- .../highlighted/MemInfo/test.MemInfo | 53 +++++++++++++++++++ .../syntax-tests/source/MemInfo/test.MemInfo | 53 +++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 tests/syntax-tests/highlighted/MemInfo/test.MemInfo create mode 100644 tests/syntax-tests/source/MemInfo/test.MemInfo diff --git a/tests/syntax-tests/highlighted/MemInfo/test.MemInfo b/tests/syntax-tests/highlighted/MemInfo/test.MemInfo new file mode 100644 index 00000000..7360ad65 --- /dev/null +++ b/tests/syntax-tests/highlighted/MemInfo/test.MemInfo @@ -0,0 +1,53 @@ +MemTotal: 1004892 kB +MemFree: 109424 kB +MemAvailable: 498032 kB +Buffers: 66360 kB +Cached: 448344 kB +SwapCached: 0 kB +Active: 547076 kB +Inactive: 196864 kB +Active(anon): 249956 kB +Inactive(anon): 7328 kB +Active(file): 297120 kB +Inactive(file): 189536 kB +Unevictable: 18516 kB +Mlocked: 18516 kB +SwapTotal: 0 kB +SwapFree: 0 kB +Dirty: 276 kB +Writeback: 0 kB +AnonPages: 247780 kB +Mapped: 168472 kB +Shmem: 19860 kB +KReclaimable: 59128 kB +Slab: 108616 kB +SReclaimable: 59128 kB +SUnreclaim: 49488 kB +KernelStack: 2060 kB +PageTables: 4232 kB +NFS_Unstable: 0 kB +Bounce: 0 kB +WritebackTmp: 0 kB +CommitLimit: 502444 kB +Committed_AS: 678300 kB +VmallocTotal: 34359738367 kB +VmallocUsed: 10756 kB +VmallocChunk: 0 kB +Percpu: 784 kB +HardwareCorrupted: 0 kB +AnonHugePages: 0 kB +ShmemHugePages: 0 kB +ShmemPmdMapped: 0 kB +FileHugePages: 0 kB +FilePmdMapped: 0 kB +CmaTotal: 0 kB +CmaFree: 0 kB +HugePages_Total: 0 +HugePages_Free: 0 +HugePages_Rsvd: 0 +HugePages_Surp: 0 +Hugepagesize: 2048 kB +Hugetlb: 0 kB +DirectMap4k: 118764 kB +DirectMap2M: 929792 kB +DirectMap1G: 0 kB diff --git a/tests/syntax-tests/source/MemInfo/test.MemInfo b/tests/syntax-tests/source/MemInfo/test.MemInfo new file mode 100644 index 00000000..dc944792 --- /dev/null +++ b/tests/syntax-tests/source/MemInfo/test.MemInfo @@ -0,0 +1,53 @@ +MemTotal: 1004892 kB +MemFree: 109424 kB +MemAvailable: 498032 kB +Buffers: 66360 kB +Cached: 448344 kB +SwapCached: 0 kB +Active: 547076 kB +Inactive: 196864 kB +Active(anon): 249956 kB +Inactive(anon): 7328 kB +Active(file): 297120 kB +Inactive(file): 189536 kB +Unevictable: 18516 kB +Mlocked: 18516 kB +SwapTotal: 0 kB +SwapFree: 0 kB +Dirty: 276 kB +Writeback: 0 kB +AnonPages: 247780 kB +Mapped: 168472 kB +Shmem: 19860 kB +KReclaimable: 59128 kB +Slab: 108616 kB +SReclaimable: 59128 kB +SUnreclaim: 49488 kB +KernelStack: 2060 kB +PageTables: 4232 kB +NFS_Unstable: 0 kB +Bounce: 0 kB +WritebackTmp: 0 kB +CommitLimit: 502444 kB +Committed_AS: 678300 kB +VmallocTotal: 34359738367 kB +VmallocUsed: 10756 kB +VmallocChunk: 0 kB +Percpu: 784 kB +HardwareCorrupted: 0 kB +AnonHugePages: 0 kB +ShmemHugePages: 0 kB +ShmemPmdMapped: 0 kB +FileHugePages: 0 kB +FilePmdMapped: 0 kB +CmaTotal: 0 kB +CmaFree: 0 kB +HugePages_Total: 0 +HugePages_Free: 0 +HugePages_Rsvd: 0 +HugePages_Surp: 0 +Hugepagesize: 2048 kB +Hugetlb: 0 kB +DirectMap4k: 118764 kB +DirectMap2M: 929792 kB +DirectMap1G: 0 kB From ecde418abbf869201ab83523cf9b52f859b456a1 Mon Sep 17 00:00:00 2001 From: okezieuc <53785400+okezieuc@users.noreply.github.com> Date: Sun, 11 Oct 2020 18:48:29 +0100 Subject: [PATCH 037/243] added php test file I added a sample test.php file that covers a lot of python syntax --- assets/syntaxes/02_Extra/Vue | 2 +- tests/syntax-tests/highlighted/PHP/test.php | 111 ++++++++++++++++++++ tests/syntax-tests/source/PHP/test.php | 111 ++++++++++++++++++++ 3 files changed, 223 insertions(+), 1 deletion(-) create mode 100644 tests/syntax-tests/highlighted/PHP/test.php create mode 100644 tests/syntax-tests/source/PHP/test.php diff --git a/assets/syntaxes/02_Extra/Vue b/assets/syntaxes/02_Extra/Vue index 6eb71bc6..6d405948 160000 --- a/assets/syntaxes/02_Extra/Vue +++ b/assets/syntaxes/02_Extra/Vue @@ -1 +1 @@ -Subproject commit 6eb71bc6bba5e6a284b6d1d3154484da6f366e21 +Subproject commit 6d405948df4a112eb7a4db2ed72bbfe76dd9f419 diff --git a/tests/syntax-tests/highlighted/PHP/test.php b/tests/syntax-tests/highlighted/PHP/test.php new file mode 100644 index 00000000..e5dbb353 --- /dev/null +++ b/tests/syntax-tests/highlighted/PHP/test.php @@ -0,0 +1,111 @@ += 3 || $numberone <=2) && $numberone != 2.5){ + echo "what a number!!!"; +} +if($numberone >= 3 and $numberone <=2 and $numberone != 2.5){ + echo "something is wrong, this is supposed to be impossible"; +} + + +if ($number < 3){ + $languages = array("HTML", "CSS", "JS"); + print_r($languages); + echo $languages[2]; + print $languages[$number]; +} +elseif ($number == 3 ){ + function favMovie() { + echo "JUMAJI"; + return true; + } + favMovie(); +} +else { + switch ($number) { + case 4: + echo "fours"; + break; + default: + echo "I dont know you"; + } +} + +while($number <= 6 ){ + echo $number; + $number++; + $number += 1; +} + +do { + $number++; +} while ($number < 10); + +for ($houses = 0; $houses <= 5; $housees++){ + break; + echo "getting more houses"; +} + + +class Person { + public $name; + public $age; +  + function __construct($name){ + $this->name = $name; + } +  + function __destruct(){ + echo "On my way out"; + } +  + function setName($name) { + $this->name = $name; + } +} + +$doe = new Person("John Do"); +$doe->setName('John Doe'); + + + + + +$ending = 2 > 3 ? "yep" : "nah"; + +?> diff --git a/tests/syntax-tests/source/PHP/test.php b/tests/syntax-tests/source/PHP/test.php new file mode 100644 index 00000000..26413597 --- /dev/null +++ b/tests/syntax-tests/source/PHP/test.php @@ -0,0 +1,111 @@ += 3 || $numberone <=2) && $numberone != 2.5){ + echo "what a number!!!"; +} +if($numberone >= 3 and $numberone <=2 and $numberone != 2.5){ + echo "something is wrong, this is supposed to be impossible"; +} + + +if ($number < 3){ + $languages = array("HTML", "CSS", "JS"); + print_r($languages); + echo $languages[2]; + print $languages[$number]; +} +elseif ($number == 3 ){ + function favMovie() { + echo "JUMAJI"; + return true; + } + favMovie(); +} +else { + switch ($number) { + case 4: + echo "fours"; + break; + default: + echo "I dont know you"; + } +} + +while($number <= 6 ){ + echo $number; + $number++; + $number += 1; +} + +do { + $number++; +} while ($number < 10); + +for ($houses = 0; $houses <= 5; $housees++){ + break; + echo "getting more houses"; +} + + +class Person { + public $name; + public $age; + + function __construct($name){ + $this->name = $name; + } + + function __destruct(){ + echo "On my way out"; + } + + function setName($name) { + $this->name = $name; + } +} + +$doe = new Person("John Do"); +$doe->setName('John Doe'); + + + + + +$ending = 2 > 3 ? "yep" : "nah"; + +?> \ No newline at end of file From b7271a2a6d1a4618d64178707f1c00c2f4d8f6e9 Mon Sep 17 00:00:00 2001 From: okezieuc <53785400+okezieuc@users.noreply.github.com> Date: Sun, 11 Oct 2020 19:53:36 +0100 Subject: [PATCH 038/243] Revert "added php test file" This reverts commit ecde418abbf869201ab83523cf9b52f859b456a1. --- assets/syntaxes/02_Extra/Vue | 2 +- tests/syntax-tests/highlighted/PHP/test.php | 111 -------------------- tests/syntax-tests/source/PHP/test.php | 111 -------------------- 3 files changed, 1 insertion(+), 223 deletions(-) delete mode 100644 tests/syntax-tests/highlighted/PHP/test.php delete mode 100644 tests/syntax-tests/source/PHP/test.php diff --git a/assets/syntaxes/02_Extra/Vue b/assets/syntaxes/02_Extra/Vue index 6d405948..6eb71bc6 160000 --- a/assets/syntaxes/02_Extra/Vue +++ b/assets/syntaxes/02_Extra/Vue @@ -1 +1 @@ -Subproject commit 6d405948df4a112eb7a4db2ed72bbfe76dd9f419 +Subproject commit 6eb71bc6bba5e6a284b6d1d3154484da6f366e21 diff --git a/tests/syntax-tests/highlighted/PHP/test.php b/tests/syntax-tests/highlighted/PHP/test.php deleted file mode 100644 index e5dbb353..00000000 --- a/tests/syntax-tests/highlighted/PHP/test.php +++ /dev/null @@ -1,111 +0,0 @@ -= 3 || $numberone <=2) && $numberone != 2.5){ - echo "what a number!!!"; -} -if($numberone >= 3 and $numberone <=2 and $numberone != 2.5){ - echo "something is wrong, this is supposed to be impossible"; -} - - -if ($number < 3){ - $languages = array("HTML", "CSS", "JS"); - print_r($languages); - echo $languages[2]; - print $languages[$number]; -} -elseif ($number == 3 ){ - function favMovie() { - echo "JUMAJI"; - return true; - } - favMovie(); -} -else { - switch ($number) { - case 4: - echo "fours"; - break; - default: - echo "I dont know you"; - } -} - -while($number <= 6 ){ - echo $number; - $number++; - $number += 1; -} - -do { - $number++; -} while ($number < 10); - -for ($houses = 0; $houses <= 5; $housees++){ - break; - echo "getting more houses"; -} - - -class Person { - public $name; - public $age; -  - function __construct($name){ - $this->name = $name; - } -  - function __destruct(){ - echo "On my way out"; - } -  - function setName($name) { - $this->name = $name; - } -} - -$doe = new Person("John Do"); -$doe->setName('John Doe'); - - - - - -$ending = 2 > 3 ? "yep" : "nah"; - -?> diff --git a/tests/syntax-tests/source/PHP/test.php b/tests/syntax-tests/source/PHP/test.php deleted file mode 100644 index 26413597..00000000 --- a/tests/syntax-tests/source/PHP/test.php +++ /dev/null @@ -1,111 +0,0 @@ -= 3 || $numberone <=2) && $numberone != 2.5){ - echo "what a number!!!"; -} -if($numberone >= 3 and $numberone <=2 and $numberone != 2.5){ - echo "something is wrong, this is supposed to be impossible"; -} - - -if ($number < 3){ - $languages = array("HTML", "CSS", "JS"); - print_r($languages); - echo $languages[2]; - print $languages[$number]; -} -elseif ($number == 3 ){ - function favMovie() { - echo "JUMAJI"; - return true; - } - favMovie(); -} -else { - switch ($number) { - case 4: - echo "fours"; - break; - default: - echo "I dont know you"; - } -} - -while($number <= 6 ){ - echo $number; - $number++; - $number += 1; -} - -do { - $number++; -} while ($number < 10); - -for ($houses = 0; $houses <= 5; $housees++){ - break; - echo "getting more houses"; -} - - -class Person { - public $name; - public $age; - - function __construct($name){ - $this->name = $name; - } - - function __destruct(){ - echo "On my way out"; - } - - function setName($name) { - $this->name = $name; - } -} - -$doe = new Person("John Do"); -$doe->setName('John Doe'); - - - - - -$ending = 2 > 3 ? "yep" : "nah"; - -?> \ No newline at end of file From 7bd19640a2bcb6e1eefbe8e48a373762099d4268 Mon Sep 17 00:00:00 2001 From: henil Date: Sat, 3 Oct 2020 22:51:33 +0530 Subject: [PATCH 039/243] add new --map-syntax example --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index b6d558b7..9f2f86ee 100644 --- a/README.md +++ b/README.md @@ -529,6 +529,9 @@ Example configuration file: # Use ".gitignore"-style highlighting for ".ignore" files --map-syntax ".ignore:Git Ignore" + +# Use INI syntax for .conf files +--map-syntax "*.conf:INI" ``` ## Using `bat` on Windows From bb7fae72c9f1a23ced3581edb447d4099d28f155 Mon Sep 17 00:00:00 2001 From: henil Date: Sun, 4 Oct 2020 00:16:39 +0530 Subject: [PATCH 040/243] add a new syntax section --- README.md | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9f2f86ee..37678011 100644 --- a/README.md +++ b/README.md @@ -526,12 +526,19 @@ Example configuration file: # Use C++ syntax for .ino files --map-syntax "*.ino:C++" +``` + +### Syntax of a file + +`bat` can be configured to change the default syntax of the file using `--map-syntax`. For example not all `.conf` file's have `INI` syntax(some do) so it cannot be default. But you can configure it if you want. + +For example: +```bash +# Use INI syntax for .conf files +--map-syntax "*.conf:INI" # Use ".gitignore"-style highlighting for ".ignore" files --map-syntax ".ignore:Git Ignore" - -# Use INI syntax for .conf files ---map-syntax "*.conf:INI" ``` ## Using `bat` on Windows From aa00e0a6b0d31072a5a6eea54d663d64ec48bb14 Mon Sep 17 00:00:00 2001 From: henil Date: Sun, 4 Oct 2020 01:20:19 +0530 Subject: [PATCH 041/243] fix section --- README.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 37678011..1e551df0 100644 --- a/README.md +++ b/README.md @@ -490,6 +490,19 @@ and the `GitHub` theme when in the _light mode_. alias cat="bat --theme=\$(defaults read -globalDomain AppleInterfaceStyle &> /dev/null && echo default || echo GitHub)" ``` +### Syntax of a file + +You can configure `bat` to change the default syntax of the file using `--map-syntax`. + +For example: +```bash +# Use INI syntax for .conf files +--map-syntax "*.conf:INI" + +# Use ".gitignore"-style highlighting for ".ignore" files +--map-syntax ".ignore:Git Ignore" +``` + ## Configuration file `bat` can also be customized with a configuration file. The location of the file is dependent @@ -528,19 +541,6 @@ Example configuration file: --map-syntax "*.ino:C++" ``` -### Syntax of a file - -`bat` can be configured to change the default syntax of the file using `--map-syntax`. For example not all `.conf` file's have `INI` syntax(some do) so it cannot be default. But you can configure it if you want. - -For example: -```bash -# Use INI syntax for .conf files ---map-syntax "*.conf:INI" - -# Use ".gitignore"-style highlighting for ".ignore" files ---map-syntax ".ignore:Git Ignore" -``` - ## Using `bat` on Windows `bat` mostly works out-of-the-box on Windows, but a few features may need extra configuration. From 4ec6075f81270a2f9d559aa12fcdd7ea0de03f44 Mon Sep 17 00:00:00 2001 From: henil Date: Sun, 4 Oct 2020 10:04:03 +0530 Subject: [PATCH 042/243] minor update to specify pattern matching on --map-syntax supports glob matching --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1e551df0..96e2f982 100644 --- a/README.md +++ b/README.md @@ -492,7 +492,7 @@ alias cat="bat --theme=\$(defaults read -globalDomain AppleInterfaceStyle &> /de ### Syntax of a file -You can configure `bat` to change the default syntax of the file using `--map-syntax`. +You can configure `bat` to change the default syntax of the file using `--map-syntax`. Use glob pattern to match exact filename. For example: ```bash From 4be32cf746630e91ef291751cbf1590dd75fc97c Mon Sep 17 00:00:00 2001 From: henil Date: Mon, 5 Oct 2020 22:20:26 +0530 Subject: [PATCH 043/243] add new section for sytax of file in README.md --- README.md | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 96e2f982..85214eab 100644 --- a/README.md +++ b/README.md @@ -492,17 +492,26 @@ alias cat="bat --theme=\$(defaults read -globalDomain AppleInterfaceStyle &> /de ### Syntax of a file -You can configure `bat` to change the default syntax of the file using `--map-syntax`. Use glob pattern to match exact filename. +You can change the default syntax highlighting of the file using `--map-syntax` option. +It uses glob pattern matching and is matched on full path and filename. + +Use it like this: + +```bash +bat --map-syntax='PATTERN:SYNTAX' file-name +``` For example: ```bash -# Use INI syntax for .conf files ---map-syntax "*.conf:INI" +# Using `INI` file syntax highligting when opening a file with extension `.conf`. +bat --map-syntax='*.conf:INI' file.conf -# Use ".gitignore"-style highlighting for ".ignore" files ---map-syntax ".ignore:Git Ignore" +# Using `Git Ignore` file syntax highlighting for ".ignore" files +bat --map-syntax='.ignore:Git Ignore' .ignore ``` +You can use `bat --list-languages` to see all the file syntax types available. + ## Configuration file `bat` can also be customized with a configuration file. The location of the file is dependent From 206d3e7b914a6ee4d3d9c53ccd71e74859ae111e Mon Sep 17 00:00:00 2001 From: henil Date: Tue, 6 Oct 2020 10:58:24 +0530 Subject: [PATCH 044/243] fix a typo --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 85214eab..b42af453 100644 --- a/README.md +++ b/README.md @@ -492,7 +492,7 @@ alias cat="bat --theme=\$(defaults read -globalDomain AppleInterfaceStyle &> /de ### Syntax of a file -You can change the default syntax highlighting of the file using `--map-syntax` option. +You can change the default syntax highlighting of the file using the `--map-syntax` option. It uses glob pattern matching and is matched on full path and filename. Use it like this: @@ -503,7 +503,7 @@ bat --map-syntax='PATTERN:SYNTAX' file-name For example: ```bash -# Using `INI` file syntax highligting when opening a file with extension `.conf`. +# Using `INI` file syntax highlighting when opening a file with extension `.conf`. bat --map-syntax='*.conf:INI' file.conf # Using `Git Ignore` file syntax highlighting for ".ignore" files From bce304a800e4f46eec9e202dc40036041193c63e Mon Sep 17 00:00:00 2001 From: henil Date: Wed, 7 Oct 2020 19:36:01 +0530 Subject: [PATCH 045/243] made requested changes --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b42af453..24239ded 100644 --- a/README.md +++ b/README.md @@ -492,10 +492,10 @@ alias cat="bat --theme=\$(defaults read -globalDomain AppleInterfaceStyle &> /de ### Syntax of a file -You can change the default syntax highlighting of the file using the `--map-syntax` option. -It uses glob pattern matching and is matched on full path and filename. +You can change the default syntax association of the file using the `--map-syntax` option. +It supports glob pattern matching and is matched on full path and filename. -Use it like this: +You can use it like this: ```bash bat --map-syntax='PATTERN:SYNTAX' file-name From 8bd078caeb6a6376834009d4570f0b7f4fc1d714 Mon Sep 17 00:00:00 2001 From: okezieuc <53785400+okezieuc@users.noreply.github.com> Date: Sun, 11 Oct 2020 19:58:53 +0100 Subject: [PATCH 046/243] updated the php commit I reverted the commit and prevented the vue submodules from being affected --- tests/syntax-tests/highlighted/PHP/test.php | 111 ++++++++++++++++++++ tests/syntax-tests/source/PHP/test.php | 111 ++++++++++++++++++++ 2 files changed, 222 insertions(+) create mode 100644 tests/syntax-tests/highlighted/PHP/test.php create mode 100644 tests/syntax-tests/source/PHP/test.php diff --git a/tests/syntax-tests/highlighted/PHP/test.php b/tests/syntax-tests/highlighted/PHP/test.php new file mode 100644 index 00000000..e5dbb353 --- /dev/null +++ b/tests/syntax-tests/highlighted/PHP/test.php @@ -0,0 +1,111 @@ += 3 || $numberone <=2) && $numberone != 2.5){ + echo "what a number!!!"; +} +if($numberone >= 3 and $numberone <=2 and $numberone != 2.5){ + echo "something is wrong, this is supposed to be impossible"; +} + + +if ($number < 3){ + $languages = array("HTML", "CSS", "JS"); + print_r($languages); + echo $languages[2]; + print $languages[$number]; +} +elseif ($number == 3 ){ + function favMovie() { + echo "JUMAJI"; + return true; + } + favMovie(); +} +else { + switch ($number) { + case 4: + echo "fours"; + break; + default: + echo "I dont know you"; + } +} + +while($number <= 6 ){ + echo $number; + $number++; + $number += 1; +} + +do { + $number++; +} while ($number < 10); + +for ($houses = 0; $houses <= 5; $housees++){ + break; + echo "getting more houses"; +} + + +class Person { + public $name; + public $age; +  + function __construct($name){ + $this->name = $name; + } +  + function __destruct(){ + echo "On my way out"; + } +  + function setName($name) { + $this->name = $name; + } +} + +$doe = new Person("John Do"); +$doe->setName('John Doe'); + + + + + +$ending = 2 > 3 ? "yep" : "nah"; + +?> diff --git a/tests/syntax-tests/source/PHP/test.php b/tests/syntax-tests/source/PHP/test.php new file mode 100644 index 00000000..26413597 --- /dev/null +++ b/tests/syntax-tests/source/PHP/test.php @@ -0,0 +1,111 @@ += 3 || $numberone <=2) && $numberone != 2.5){ + echo "what a number!!!"; +} +if($numberone >= 3 and $numberone <=2 and $numberone != 2.5){ + echo "something is wrong, this is supposed to be impossible"; +} + + +if ($number < 3){ + $languages = array("HTML", "CSS", "JS"); + print_r($languages); + echo $languages[2]; + print $languages[$number]; +} +elseif ($number == 3 ){ + function favMovie() { + echo "JUMAJI"; + return true; + } + favMovie(); +} +else { + switch ($number) { + case 4: + echo "fours"; + break; + default: + echo "I dont know you"; + } +} + +while($number <= 6 ){ + echo $number; + $number++; + $number += 1; +} + +do { + $number++; +} while ($number < 10); + +for ($houses = 0; $houses <= 5; $housees++){ + break; + echo "getting more houses"; +} + + +class Person { + public $name; + public $age; + + function __construct($name){ + $this->name = $name; + } + + function __destruct(){ + echo "On my way out"; + } + + function setName($name) { + $this->name = $name; + } +} + +$doe = new Person("John Do"); +$doe->setName('John Doe'); + + + + + +$ending = 2 > 3 ? "yep" : "nah"; + +?> \ No newline at end of file From 0a28da0cd018f2602677dcb04f8abef9aaabf523 Mon Sep 17 00:00:00 2001 From: David Peter Date: Sun, 11 Oct 2020 21:07:56 +0200 Subject: [PATCH 047/243] Small improvement to the syntax mapping section --- README.md | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 24239ded..d42ea473 100644 --- a/README.md +++ b/README.md @@ -490,27 +490,32 @@ and the `GitHub` theme when in the _light mode_. alias cat="bat --theme=\$(defaults read -globalDomain AppleInterfaceStyle &> /dev/null && echo default || echo GitHub)" ``` -### Syntax of a file +### Adapting file type associations -You can change the default syntax association of the file using the `--map-syntax` option. -It supports glob pattern matching and is matched on full path and filename. +You can add new (or change existing) file name patterns using the +`--map-syntax` option. The option takes an argument of the form `pattern:syntax`. +`pattern` is a glob pattern that is matched against the file name and +the absolute file path. `syntax` is the *name* of a supported language +(use `bat --list-languages` for an overview). -You can use it like this: +This option is most useful in combination with the `bat` configuration file (see below). +Example: To use "INI" syntax highlighting for all files with a `.conf` file extension, use ```bash -bat --map-syntax='PATTERN:SYNTAX' file-name +--map-syntax='*.conf:INI' ``` -For example: +Example: To open all files called `.ignore` (exact match) with the "Git Ignore" syntax, use: ```bash -# Using `INI` file syntax highlighting when opening a file with extension `.conf`. -bat --map-syntax='*.conf:INI' file.conf - -# Using `Git Ignore` file syntax highlighting for ".ignore" files -bat --map-syntax='.ignore:Git Ignore' .ignore +--map-syntax='.ignore:Git Ignore' +``` + +Example: To open all `.conf` files in subfolders of `/etc/apache2` with the "Apache Conf" +syntax, use (this mapping is already built in): +```bash +-map-syntax='/etc/apache2/**/*.conf:Apache Conf' ``` -You can use `bat --list-languages` to see all the file syntax types available. ## Configuration file From de6680bdf2b01e30acd3d1720551868d5c051baf Mon Sep 17 00:00:00 2001 From: sharkdp Date: Sun, 11 Oct 2020 21:11:26 +0200 Subject: [PATCH 048/243] Move syntax mapping section --- README.md | 53 +++++++++++++++++++++++++++-------------------------- 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index d42ea473..d4703245 100644 --- a/README.md +++ b/README.md @@ -439,6 +439,33 @@ bat cache --build Finally, use `bat --list-themes` to check if the new themes are available. +### Adding or changing file type associations + +You can add new (or change existing) file name patterns using the `--map-syntax` +command line option. The option takes an argument of the form `pattern:syntax` where +`pattern` is a glob pattern that is matched against the file name and +the absolute file path. The `syntax` part is the full name of a supported language +(use `bat --list-languages` for an overview)full . + +Note: You probably want to use this option as an entry in `bat`s configuration file instead +of passing it on the command line (see below). + +Example: To use "INI" syntax highlighting for all files with a `.conf` file extension, use +```bash +--map-syntax='*.conf:INI' +``` + +Example: To open all files called `.ignore` (exact match) with the "Git Ignore" syntax, use: +```bash +--map-syntax='.ignore:Git Ignore' +``` + +Example: To open all `.conf` files in subfolders of `/etc/apache2` with the "Apache Conf" +syntax, use (this mapping is already built in): +```bash +-map-syntax='/etc/apache2/**/*.conf:Apache Conf' +``` + ### Using a different pager `bat` uses the pager that is specified in the `PAGER` environment variable. If this variable is not @@ -490,32 +517,6 @@ and the `GitHub` theme when in the _light mode_. alias cat="bat --theme=\$(defaults read -globalDomain AppleInterfaceStyle &> /dev/null && echo default || echo GitHub)" ``` -### Adapting file type associations - -You can add new (or change existing) file name patterns using the -`--map-syntax` option. The option takes an argument of the form `pattern:syntax`. -`pattern` is a glob pattern that is matched against the file name and -the absolute file path. `syntax` is the *name* of a supported language -(use `bat --list-languages` for an overview). - -This option is most useful in combination with the `bat` configuration file (see below). - -Example: To use "INI" syntax highlighting for all files with a `.conf` file extension, use -```bash ---map-syntax='*.conf:INI' -``` - -Example: To open all files called `.ignore` (exact match) with the "Git Ignore" syntax, use: -```bash ---map-syntax='.ignore:Git Ignore' -``` - -Example: To open all `.conf` files in subfolders of `/etc/apache2` with the "Apache Conf" -syntax, use (this mapping is already built in): -```bash --map-syntax='/etc/apache2/**/*.conf:Apache Conf' -``` - ## Configuration file From f3c760c25f5270424ded2fd55765da3d20d167ba Mon Sep 17 00:00:00 2001 From: Logan Saso Date: Sun, 4 Oct 2020 15:29:20 -0700 Subject: [PATCH 049/243] #1244 Use [].copy and path.exists instead of more cumbersome solutions #1244 Slightly optimized create_highlighted_versions.py so that it won't walk the source path when it should be skipping the file #1244 Updated README.md in plaintext source folder #1244 Added extra option loading from `bat_options` file in directory and significantly reduced size of plaintext source #1244 Updated create_highlighted_versions.py to ignore README.md files and use the --show-all option for manually-defined binary files #1244 Updated plaintext file with command bat -A --no-config --style=plain --color=always --theme='1337' --italic-text=always src/Plaintext/plaintext.txt > highlighted/Plaintext/plaintext.txt #1244 Added example plaintext file --- .../create_highlighted_versions.py | 30 ++- .../highlighted/Plaintext/plaintext.txt | 178 ++++++++++++++++++ tests/syntax-tests/source/Plaintext/README.md | 10 + .../syntax-tests/source/Plaintext/bat_options | 1 + .../source/Plaintext/plaintext.txt | Bin 0 -> 436 bytes 5 files changed, 213 insertions(+), 6 deletions(-) create mode 100644 tests/syntax-tests/highlighted/Plaintext/plaintext.txt create mode 100644 tests/syntax-tests/source/Plaintext/README.md create mode 100644 tests/syntax-tests/source/Plaintext/bat_options create mode 100644 tests/syntax-tests/source/Plaintext/plaintext.txt diff --git a/tests/syntax-tests/create_highlighted_versions.py b/tests/syntax-tests/create_highlighted_versions.py index c03a0742..b82cc8cd 100755 --- a/tests/syntax-tests/create_highlighted_versions.py +++ b/tests/syntax-tests/create_highlighted_versions.py @@ -16,6 +16,17 @@ BAT_OPTIONS = [ "--italic-text=always", ] +SKIP_FILENAMES = [ + "LICENSE.md", + "README.md", + "bat_options", +] + + +def get_extra_options(source): + with open(path.join(source, "bat_options"), "r") as f: + return list(map(lambda x: x.rstrip(), f.readlines())) + def create_highlighted_versions(output_basepath): root = os.path.dirname(os.path.abspath(__file__)) @@ -31,16 +42,23 @@ def create_highlighted_versions(output_basepath): env.pop("BAT_TABS", None) env["COLORTERM"] = "truecolor" # make sure to output 24bit colors - bat_output = subprocess.check_output( - ["bat"] + BAT_OPTIONS + [source], stderr=subprocess.PIPE, env=env, - ) - - source_dirname = path.basename(path.dirname(source)) + source_dirpath = path.dirname(source) + source_dirname = path.basename(source_dirpath) source_filename = path.basename(source) - if source_filename == "LICENSE.md": + if source_filename in SKIP_FILENAMES: continue + options = BAT_OPTIONS.copy() + # If a directory is empty, `files` could possibly be 0-length + if path.exists(path.join(source_dirpath, "bat_options")): + options += get_extra_options(source_dirpath) + + bat_output = subprocess.check_output( + ["bat"] + options + [source], + stderr=subprocess.PIPE, env=env, + ) + output_dir = path.join(output_basepath, source_dirname) output_path = path.join(output_dir, source_filename) diff --git a/tests/syntax-tests/highlighted/Plaintext/plaintext.txt b/tests/syntax-tests/highlighted/Plaintext/plaintext.txt new file mode 100644 index 00000000..807728e1 --- /dev/null +++ b/tests/syntax-tests/highlighted/Plaintext/plaintext.txt @@ -0,0 +1,178 @@ +␀␊ +\u{1}␊ +\u{2}␊ +\u{3}␊ +\u{4}␊ +\u{5}␊ +\u{6}␊ +␇␊ +␈␊ +├──┤␊ +␊ +␊ +\u{b}␊ +\u{c}␊ +␊ +\u{e}␊ +\u{f}␊ +\u{10}␊ +\u{11}␊ +\u{12}␊ +\u{13}␊ +\u{14}␊ +\u{15}␊ +\u{16}␊ +\u{17}␊ +\u{18}␊ +\u{19}␊ +\u{1a}␊ +␛␊ +\u{1c}␊ +\u{1d}␊ +\u{1e}␊ +\u{1f}␊ +·␊ +!␊ +"␊ +#␊ +$␊ +%␊ +&␊ +'␊ +(␊ +)␊ +*␊ ++␊ +,␊ +-␊ +.␊ +/␊ +0␊ +1␊ +2␊ +3␊ +4␊ +5␊ +6␊ +7␊ +8␊ +9␊ +:␊ +;␊ +<␊ +=␊ +>␊ +?␊ +@␊ +A␊ +B␊ +C␊ +D␊ +E␊ +F␊ +G␊ +H␊ +I␊ +J␊ +K␊ +L␊ +M␊ +N␊ +O␊ +P␊ +Q␊ +R␊ +S␊ +T␊ +U␊ +V␊ +W␊ +X␊ +Y␊ +Z␊ +[␊ +\␊ +]␊ +^␊ +_␊ +`␊ +a␊ +b␊ +c␊ +d␊ +e␊ +f␊ +g␊ +h␊ +i␊ +j␊ +k␊ +l␊ +m␊ +n␊ +o␊ +p␊ +q␊ +r␊ +s␊ +t␊ +u␊ +v␊ +w␊ +x␊ +y␊ +z␊ +{␊ +|␊ +}␊ +~␊ +\u{7f}␊ +\u{80}␊ +\u{81}␊ +\u{82}␊ +\u{83}␊ +\u{84}␊ +\u{85}␊ +\u{86}␊ +\u{87}␊ +\u{88}␊ +\u{89}␊ +\u{8a}␊ +\u{8b}␊ +\u{8c}␊ +\u{8d}␊ +\u{8e}␊ +\u{8f}␊ +\u{90}␊ +\u{91}␊ +\u{92}␊ +\u{93}␊ +\u{94}␊ +\u{95}␊ +\u{96}␊ +\u{97}␊ +\u{98}␊ +\u{99}␊ +\u{9a}␊ +\u{9b}␊ +\u{9c}␊ +\u{9d}␊ +\u{9e}␊ +\u{9f}␊ +\u{a0}␊ +\u{a1}␊ +\u{a2}␊ +\u{a3}␊ +\u{a4}␊ +\u{a5}␊ +\u{a6}␊ +\u{a7}␊ +\u{a8}␊ +\u{a9}␊ +\u{aa}␊ +\u{ab}␊ +\u{ac}␊ +\u{ad}␊ +\u{ae}␊ +␊ +Here's·a·line·with·multiple·characters. diff --git a/tests/syntax-tests/source/Plaintext/README.md b/tests/syntax-tests/source/Plaintext/README.md new file mode 100644 index 00000000..95679324 --- /dev/null +++ b/tests/syntax-tests/source/Plaintext/README.md @@ -0,0 +1,10 @@ +This text file was generated with the following script. Certain invalid characters were removed manually: + +```python +with open("plaintext.txt", "w"): + for i in range(0x10FFFF): + try: + f.write(chr(i) + "\n") + except: + pass +``` diff --git a/tests/syntax-tests/source/Plaintext/bat_options b/tests/syntax-tests/source/Plaintext/bat_options new file mode 100644 index 00000000..e5dd9b4e --- /dev/null +++ b/tests/syntax-tests/source/Plaintext/bat_options @@ -0,0 +1 @@ +--show-all diff --git a/tests/syntax-tests/source/Plaintext/plaintext.txt b/tests/syntax-tests/source/Plaintext/plaintext.txt new file mode 100644 index 0000000000000000000000000000000000000000..42da1207d3c89516d0bc2968d328f229d1f5eb79 GIT binary patch literal 436 zcmV~$g<4Yq7ywW^j(&FMH8H{NPVDZ$Ij?Ry5Vs)~c6WCt=0p5X<~c32)Jkh@wAD^~ z9dtw|o#~>hZo2ECr(SyNqpyDY8(^S81{-3i#4y8+Fw!WaRTyKeamJfqqDoaJnQV%w zrkQSrnP!=7j=AQUZ-IptS!{`=mRW9vm8z|>+8S%Ev)%?9ZL--GTWz!54m<6#+a7!E zvtNw^G7ic*Bz4#kIeAANQ&6kUarI6pDk*DlQlnE&JL9Z#nw)n*TojkYWpPDZ71zXd zaYNh`x5RC6N8A5uf%KdM!Xg8#C!2Ud=#I=XYoaR z72m{n@k2C=pW>JJE&hnV;vdy%F|8;inWT`fOOwWYIhWKn6w3MfLYicAnPMhePK%|= E|0=(9C;$Ke literal 0 HcmV?d00001 From 6c68198d19f833abf283c812f0f268a31e5b7329 Mon Sep 17 00:00:00 2001 From: Logan Saso Date: Sat, 10 Oct 2020 12:24:21 -0700 Subject: [PATCH 050/243] Updated creation script and README to match generation script --- .../create_highlighted_versions.py | 21 +++++++++---------- tests/syntax-tests/source/Plaintext/README.md | 6 ++++-- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/tests/syntax-tests/create_highlighted_versions.py b/tests/syntax-tests/create_highlighted_versions.py index b82cc8cd..75278197 100755 --- a/tests/syntax-tests/create_highlighted_versions.py +++ b/tests/syntax-tests/create_highlighted_versions.py @@ -23,9 +23,14 @@ SKIP_FILENAMES = [ ] -def get_extra_options(source): - with open(path.join(source, "bat_options"), "r") as f: - return list(map(lambda x: x.rstrip(), f.readlines())) +def get_options(source): + source_dirpath = path.dirname(source) + options = BAT_OPTIONS.copy() + if path.exists(path.join(source_dirpath, "bat_options")): + with open(path.join(source, "bat_options"), "r") as f: + options += list(map(lambda x: x.rstrip(), f.readlines())) + return options + def create_highlighted_versions(output_basepath): @@ -42,20 +47,14 @@ def create_highlighted_versions(output_basepath): env.pop("BAT_TABS", None) env["COLORTERM"] = "truecolor" # make sure to output 24bit colors - source_dirpath = path.dirname(source) - source_dirname = path.basename(source_dirpath) + source_dirname = path.basename(path.dirname(source)) source_filename = path.basename(source) if source_filename in SKIP_FILENAMES: continue - options = BAT_OPTIONS.copy() - # If a directory is empty, `files` could possibly be 0-length - if path.exists(path.join(source_dirpath, "bat_options")): - options += get_extra_options(source_dirpath) - bat_output = subprocess.check_output( - ["bat"] + options + [source], + ["bat"] + get_options(source) + [source], stderr=subprocess.PIPE, env=env, ) diff --git a/tests/syntax-tests/source/Plaintext/README.md b/tests/syntax-tests/source/Plaintext/README.md index 95679324..59c0065e 100644 --- a/tests/syntax-tests/source/Plaintext/README.md +++ b/tests/syntax-tests/source/Plaintext/README.md @@ -1,10 +1,12 @@ -This text file was generated with the following script. Certain invalid characters were removed manually: +This text file was generated with the following script. ```python with open("plaintext.txt", "w"): - for i in range(0x10FFFF): + for i in range(176): try: f.write(chr(i) + "\n") except: pass + f.write("\n") + f.write("Here is a line with multiple characters") ``` From 19b55706ee20cb0325304b6db37570c6614089ad Mon Sep 17 00:00:00 2001 From: Logan Saso Date: Sat, 10 Oct 2020 12:25:45 -0700 Subject: [PATCH 051/243] Fixed file location in creation script --- tests/syntax-tests/create_highlighted_versions.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/syntax-tests/create_highlighted_versions.py b/tests/syntax-tests/create_highlighted_versions.py index 75278197..2802991f 100755 --- a/tests/syntax-tests/create_highlighted_versions.py +++ b/tests/syntax-tests/create_highlighted_versions.py @@ -26,8 +26,9 @@ SKIP_FILENAMES = [ def get_options(source): source_dirpath = path.dirname(source) options = BAT_OPTIONS.copy() - if path.exists(path.join(source_dirpath, "bat_options")): - with open(path.join(source, "bat_options"), "r") as f: + options_file = path.join(source_dirpath, "bat_options") + if path.exists(options_file): + with open(options_file, "r") as f: options += list(map(lambda x: x.rstrip(), f.readlines())) return options From de47bd2323d2b4a2e551022430c28e52274856d8 Mon Sep 17 00:00:00 2001 From: Logan Saso Date: Sat, 10 Oct 2020 12:31:12 -0700 Subject: [PATCH 052/243] Added newline to multicharacter line of plaintext generation script --- tests/syntax-tests/source/Plaintext/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/syntax-tests/source/Plaintext/README.md b/tests/syntax-tests/source/Plaintext/README.md index 59c0065e..2a379aed 100644 --- a/tests/syntax-tests/source/Plaintext/README.md +++ b/tests/syntax-tests/source/Plaintext/README.md @@ -8,5 +8,5 @@ with open("plaintext.txt", "w"): except: pass f.write("\n") - f.write("Here is a line with multiple characters") + f.write("Here is a line with multiple characters\n") ``` From b3903175c8b5d72c0a9dc428d77bec01bdc349fa Mon Sep 17 00:00:00 2001 From: sharkdp Date: Sun, 11 Oct 2020 21:57:12 +0200 Subject: [PATCH 053/243] Auto-format Rust code --- src/bin/bat/config.rs | 3 +-- src/output.rs | 14 +++++++++----- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/bin/bat/config.rs b/src/bin/bat/config.rs index c7ce08d5..1f20a6f0 100644 --- a/src/bin/bat/config.rs +++ b/src/bin/bat/config.rs @@ -44,8 +44,7 @@ pub fn generate_config_file() -> bat::error::Result<()> { } } - let default_config = - r#"# This is `bat`s configuration file. Each line either contains a comment or + let default_config = r#"# This is `bat`s configuration file. Each line either contains a comment or # a command-line option that you want to pass to `bat` by default. You can # run `bat --help` to get a list of all possible configuration options. diff --git a/src/output.rs b/src/output.rs index 8bbdbc61..b0d5974e 100644 --- a/src/output.rs +++ b/src/output.rs @@ -10,7 +10,6 @@ use crate::paging::PagingMode; #[cfg(feature = "paging")] use crate::wrapping::WrappingMode; - #[cfg(feature = "paging")] #[derive(Debug, PartialEq)] enum SingleScreenAction { @@ -18,7 +17,6 @@ enum SingleScreenAction { Nothing, } - #[derive(Debug)] pub enum OutputType { #[cfg(feature = "paging")] @@ -28,11 +26,17 @@ pub enum OutputType { impl OutputType { #[cfg(feature = "paging")] - pub fn from_mode(paging_mode: PagingMode, wrapping_mode: WrappingMode, pager: Option<&str>) -> Result { + pub fn from_mode( + paging_mode: PagingMode, + wrapping_mode: WrappingMode, + pager: Option<&str>, + ) -> Result { use self::PagingMode::*; Ok(match paging_mode { Always => OutputType::try_pager(SingleScreenAction::Nothing, wrapping_mode, pager)?, - QuitIfOneScreen => OutputType::try_pager(SingleScreenAction::Quit, wrapping_mode, pager)?, + QuitIfOneScreen => { + OutputType::try_pager(SingleScreenAction::Quit, wrapping_mode, pager)? + } _ => OutputType::stdout(), }) } @@ -42,7 +46,7 @@ impl OutputType { fn try_pager( single_screen_action: SingleScreenAction, wrapping_mode: WrappingMode, - pager_from_config: Option<&str> + pager_from_config: Option<&str>, ) -> Result { use std::env; use std::ffi::OsString; From 62e715ff5b9640d8811c82c2198bf8257a397242 Mon Sep 17 00:00:00 2001 From: sharkdp Date: Sun, 11 Oct 2020 21:33:37 +0200 Subject: [PATCH 054/243] Formatting --- tests/syntax-tests/create_highlighted_versions.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/syntax-tests/create_highlighted_versions.py b/tests/syntax-tests/create_highlighted_versions.py index 2802991f..e7a37fdf 100755 --- a/tests/syntax-tests/create_highlighted_versions.py +++ b/tests/syntax-tests/create_highlighted_versions.py @@ -33,7 +33,6 @@ def get_options(source): return options - def create_highlighted_versions(output_basepath): root = os.path.dirname(os.path.abspath(__file__)) @@ -56,7 +55,8 @@ def create_highlighted_versions(output_basepath): bat_output = subprocess.check_output( ["bat"] + get_options(source) + [source], - stderr=subprocess.PIPE, env=env, + stderr=subprocess.PIPE, + env=env, ) output_dir = path.join(output_basepath, source_dirname) @@ -83,7 +83,10 @@ def create_highlighted_versions(output_basepath): ) sys.exit(1) except FileNotFoundError: - print("Error: Could not execute 'bat'. Please make sure that the executable is available on the PATH.") + print( + "Error: Could not execute 'bat'. Please make sure that the executable " + "is available on the PATH." + ) sys.exit(1) From bf87f37039c03fdb3be2bfd3e8286d0260023a49 Mon Sep 17 00:00:00 2001 From: sharkdp Date: Sun, 11 Oct 2020 21:36:42 +0200 Subject: [PATCH 055/243] Better ask forgiveness than permission --- tests/syntax-tests/create_highlighted_versions.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/syntax-tests/create_highlighted_versions.py b/tests/syntax-tests/create_highlighted_versions.py index e7a37fdf..70e5048a 100755 --- a/tests/syntax-tests/create_highlighted_versions.py +++ b/tests/syntax-tests/create_highlighted_versions.py @@ -24,12 +24,15 @@ SKIP_FILENAMES = [ def get_options(source): - source_dirpath = path.dirname(source) options = BAT_OPTIONS.copy() + + source_dirpath = path.dirname(source) options_file = path.join(source_dirpath, "bat_options") - if path.exists(options_file): + try: with open(options_file, "r") as f: options += list(map(lambda x: x.rstrip(), f.readlines())) + except FileNotFoundError: + pass return options From 33128d75f22a7c029df17b1ee595865933551469 Mon Sep 17 00:00:00 2001 From: sharkdp Date: Sun, 11 Oct 2020 21:37:25 +0200 Subject: [PATCH 056/243] =?UTF-8?q?Use=20list.extend(=E2=80=A6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/syntax-tests/create_highlighted_versions.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/syntax-tests/create_highlighted_versions.py b/tests/syntax-tests/create_highlighted_versions.py index 70e5048a..a8d0bc78 100755 --- a/tests/syntax-tests/create_highlighted_versions.py +++ b/tests/syntax-tests/create_highlighted_versions.py @@ -30,9 +30,10 @@ def get_options(source): options_file = path.join(source_dirpath, "bat_options") try: with open(options_file, "r") as f: - options += list(map(lambda x: x.rstrip(), f.readlines())) + options.extend(map(lambda x: x.rstrip(), f.readlines())) except FileNotFoundError: pass + return options From aa4000cb0de7db2ad5fcf642e53627c4f53d46f9 Mon Sep 17 00:00:00 2001 From: Tom Milligan Date: Tue, 6 Oct 2020 16:57:47 +0100 Subject: [PATCH 057/243] style: add component 'rule' for horizontal file delimiter --- src/bin/bat/clap_app.rs | 5 ++-- src/pretty_printer.rs | 10 +++++++ src/printer.rs | 24 ++++++++++++----- src/style.rs | 7 +++++ tests/integration_tests.rs | 12 +++++++++ tests/snapshot_tests.rs | 10 +++++++ tests/snapshots/generate_snapshots.py | 2 +- ...nges_grid_header_numbers_rule.snapshot.txt | 26 +++++++++++++++++++ .../changes_grid_header_rule.snapshot.txt | 26 +++++++++++++++++++ .../changes_grid_numbers_rule.snapshot.txt | 24 +++++++++++++++++ .../output/changes_grid_rule.snapshot.txt | 24 +++++++++++++++++ .../changes_header_numbers_rule.snapshot.txt | 23 ++++++++++++++++ .../output/changes_header_rule.snapshot.txt | 23 ++++++++++++++++ .../output/changes_numbers_rule.snapshot.txt | 22 ++++++++++++++++ .../output/changes_rule.snapshot.txt | 22 ++++++++++++++++ .../grid_header_numbers_rule.snapshot.txt | 26 +++++++++++++++++++ .../output/grid_header_rule.snapshot.txt | 26 +++++++++++++++++++ .../output/grid_numbers_rule.snapshot.txt | 24 +++++++++++++++++ tests/snapshots/output/grid_rule.snapshot.txt | 24 +++++++++++++++++ .../output/header_numbers_rule.snapshot.txt | 23 ++++++++++++++++ .../snapshots/output/header_rule.snapshot.txt | 23 ++++++++++++++++ .../output/numbers_rule.snapshot.txt | 22 ++++++++++++++++ tests/snapshots/output/rule.snapshot.txt | 22 ++++++++++++++++ 23 files changed, 441 insertions(+), 9 deletions(-) create mode 100644 tests/snapshots/output/changes_grid_header_numbers_rule.snapshot.txt create mode 100644 tests/snapshots/output/changes_grid_header_rule.snapshot.txt create mode 100644 tests/snapshots/output/changes_grid_numbers_rule.snapshot.txt create mode 100644 tests/snapshots/output/changes_grid_rule.snapshot.txt create mode 100644 tests/snapshots/output/changes_header_numbers_rule.snapshot.txt create mode 100644 tests/snapshots/output/changes_header_rule.snapshot.txt create mode 100644 tests/snapshots/output/changes_numbers_rule.snapshot.txt create mode 100644 tests/snapshots/output/changes_rule.snapshot.txt create mode 100644 tests/snapshots/output/grid_header_numbers_rule.snapshot.txt create mode 100644 tests/snapshots/output/grid_header_rule.snapshot.txt create mode 100644 tests/snapshots/output/grid_numbers_rule.snapshot.txt create mode 100644 tests/snapshots/output/grid_rule.snapshot.txt create mode 100644 tests/snapshots/output/header_numbers_rule.snapshot.txt create mode 100644 tests/snapshots/output/header_rule.snapshot.txt create mode 100644 tests/snapshots/output/numbers_rule.snapshot.txt create mode 100644 tests/snapshots/output/rule.snapshot.txt diff --git a/src/bin/bat/clap_app.rs b/src/bin/bat/clap_app.rs index d04abd8a..4e642760 100644 --- a/src/bin/bat/clap_app.rs +++ b/src/bin/bat/clap_app.rs @@ -367,7 +367,7 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> { .validator(|val| { let mut invalid_vals = val.split(',').filter(|style| { !&[ - "auto", "full", "plain", "header", "grid", "numbers", "snip", + "auto", "full", "plain", "header", "grid", "rule", "numbers", "snip", #[cfg(feature = "git")] "changes", ] @@ -382,7 +382,7 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> { }) .help( "Comma-separated list of style elements to display \ - (*auto*, full, plain, changes, header, grid, numbers, snip).", + (*auto*, full, plain, changes, header, grid, rule, numbers, snip).", ) .long_help( "Configure which elements (line numbers, file headers, grid \ @@ -400,6 +400,7 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> { * header: show filenames before the content.\n \ * grid: vertical/horizontal lines to separate side bar\n \ and the header from the content.\n \ + * rule: horizontal lines to delimit files.\n \ * numbers: show line numbers in the side bar.\n \ * snip: draw separation lines between distinct line ranges.", ), diff --git a/src/pretty_printer.rs b/src/pretty_printer.rs index c9530bf4..89745eec 100644 --- a/src/pretty_printer.rs +++ b/src/pretty_printer.rs @@ -23,6 +23,7 @@ struct ActiveStyleComponents { header: bool, vcs_modification_markers: bool, grid: bool, + rule: bool, line_numbers: bool, snip: bool, } @@ -179,6 +180,12 @@ impl<'a> PrettyPrinter<'a> { self } + /// Whether to paint a horizontal rule to delimit files + pub fn rule(&mut self, yes: bool) -> &mut Self { + self.active_style_components.rule = yes; + self + } + /// Whether to show modification markers for VCS changes. This has no effect if /// the `git` feature is not activated. #[cfg_attr( @@ -285,6 +292,9 @@ impl<'a> PrettyPrinter<'a> { if self.active_style_components.grid { style_components.push(StyleComponent::Grid); } + if self.active_style_components.rule { + style_components.push(StyleComponent::Rule); + } if self.active_style_components.header { style_components.push(StyleComponent::Header); } diff --git a/src/printer.rs b/src/printer.rs index 71bf78ee..e0829874 100644 --- a/src/printer.rs +++ b/src/printer.rs @@ -200,13 +200,18 @@ impl<'a> InteractivePrinter<'a> { }) } + fn print_horizontal_line_term(&mut self, handle: &mut dyn Write, style: Style) -> Result<()> { + writeln!( + handle, + "{}", + style.paint("─".repeat(self.config.term_width)) + )?; + Ok(()) + } + fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> { if self.panel_width == 0 { - writeln!( - handle, - "{}", - self.colors.grid.paint("─".repeat(self.config.term_width)) - )?; + self.print_horizontal_line_term(handle, self.colors.grid)?; } else { let hline = "─".repeat(self.config.term_width - (self.panel_width + 1)); let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline); @@ -251,6 +256,10 @@ impl<'a> Printer for InteractivePrinter<'a> { input: &OpenedInput, add_header_padding: bool, ) -> Result<()> { + if add_header_padding && self.config.style_components.rule() { + self.print_horizontal_line_term(handle, self.colors.rule)?; + } + if !self.config.style_components.header() { if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable { writeln!( @@ -279,7 +288,8 @@ impl<'a> Printer for InteractivePrinter<'a> { .paint(if self.panel_width > 0 { "│ " } else { "" }), )?; } else { - if add_header_padding { + // Only pad space between files, if we haven't already drawn a horizontal rule + if add_header_padding && !self.config.style_components.rule() { writeln!(handle)?; } write!(handle, "{}", " ".repeat(self.panel_width))?; @@ -603,6 +613,7 @@ const DEFAULT_GUTTER_COLOR: u8 = 238; #[derive(Debug, Default)] pub struct Colors { pub grid: Style, + pub rule: Style, pub filename: Style, pub git_added: Style, pub git_removed: Style, @@ -624,6 +635,7 @@ impl Colors { Colors { grid: gutter_color.normal(), + rule: gutter_color.normal(), filename: Style::new().bold(), git_added: Green.normal(), git_removed: Red.normal(), diff --git a/src/style.rs b/src/style.rs index 8d51cbde..65414206 100644 --- a/src/style.rs +++ b/src/style.rs @@ -9,6 +9,7 @@ pub enum StyleComponent { #[cfg(feature = "git")] Changes, Grid, + Rule, Header, LineNumbers, Snip, @@ -29,6 +30,7 @@ impl StyleComponent { #[cfg(feature = "git")] StyleComponent::Changes => &[StyleComponent::Changes], StyleComponent::Grid => &[StyleComponent::Grid], + StyleComponent::Rule => &[StyleComponent::Rule], StyleComponent::Header => &[StyleComponent::Header], StyleComponent::LineNumbers => &[StyleComponent::LineNumbers], StyleComponent::Snip => &[StyleComponent::Snip], @@ -54,6 +56,7 @@ impl FromStr for StyleComponent { #[cfg(feature = "git")] "changes" => Ok(StyleComponent::Changes), "grid" => Ok(StyleComponent::Grid), + "rule" => Ok(StyleComponent::Rule), "header" => Ok(StyleComponent::Header), "numbers" => Ok(StyleComponent::LineNumbers), "snip" => Ok(StyleComponent::Snip), @@ -81,6 +84,10 @@ impl StyleComponents { self.0.contains(&StyleComponent::Grid) } + pub fn rule(&self) -> bool { + self.0.contains(&StyleComponent::Rule) + } + pub fn header(&self) -> bool { self.0.contains(&StyleComponent::Header) } diff --git a/tests/integration_tests.rs b/tests/integration_tests.rs index da0690ef..9dfa8067 100644 --- a/tests/integration_tests.rs +++ b/tests/integration_tests.rs @@ -570,6 +570,18 @@ fn empty_file_leads_to_empty_output_with_grid_enabled() { .stdout(""); } +#[test] +fn empty_file_leads_to_empty_output_with_rule_enabled() { + bat() + .arg("empty.txt") + .arg("--style=rule") + .arg("--decorations=always") + .arg("--terminal-width=80") + .assert() + .success() + .stdout(""); +} + #[test] fn filename_basic() { bat() diff --git a/tests/snapshot_tests.rs b/tests/snapshot_tests.rs index ad41edb2..8abb8414 100644 --- a/tests/snapshot_tests.rs +++ b/tests/snapshot_tests.rs @@ -19,17 +19,27 @@ snapshot_tests! { grid: "grid", header: "header", numbers: "numbers", + rule: "rule", changes_grid: "changes,grid", changes_header: "changes,header", changes_numbers: "changes,numbers", + changes_rule: "changes,rule", grid_header: "grid,header", grid_numbers: "grid,numbers", + grid_rule: "grid,rule", header_numbers: "header,numbers", + header_rule: "header,rule", changes_grid_header: "changes,grid,header", changes_grid_numbers: "changes,grid,numbers", + changes_grid_rule: "changes,grid,rule", changes_header_numbers: "changes,header,numbers", + changes_header_rule: "changes,header,rule", grid_header_numbers: "grid,header,numbers", + grid_header_rule: "grid,header,rule", + header_numbers_rule: "header,numbers,rule", changes_grid_header_numbers: "changes,grid,header,numbers", + changes_grid_header_rule: "changes,grid,header,rule", + changes_grid_header_numbers_rule: "changes,grid,header,numbers,rule", full: "full", plain: "plain", } diff --git a/tests/snapshots/generate_snapshots.py b/tests/snapshots/generate_snapshots.py index fd17b285..bb7d69ba 100755 --- a/tests/snapshots/generate_snapshots.py +++ b/tests/snapshots/generate_snapshots.py @@ -7,7 +7,7 @@ import shutil def generate_snapshots(): - single_styles = ["changes", "grid", "header", "numbers"] + single_styles = ["changes", "grid", "header", "numbers", "rule"] collective_styles = ["full", "plain"] for num in range(len(single_styles)): diff --git a/tests/snapshots/output/changes_grid_header_numbers_rule.snapshot.txt b/tests/snapshots/output/changes_grid_header_numbers_rule.snapshot.txt new file mode 100644 index 00000000..cee4737f --- /dev/null +++ b/tests/snapshots/output/changes_grid_header_numbers_rule.snapshot.txt @@ -0,0 +1,26 @@ +───────┬──────────────────────────────────────────────────────────────────────── + │ File: sample.rs +───────┼──────────────────────────────────────────────────────────────────────── + 1 │ struct Rectangle { + 2 │ width: u32, + 3 │ height: u32, + 4 │ } + 5 │ + 6 _ │ fn main() { + 7 │ let rect1 = Rectangle { width: 30, height: 50 }; + 8 │ + 9 │ println!( + 10 ~ │ "The perimeter of the rectangle is {} pixels.", + 11 ~ │ perimeter(&rect1) + 12 │ ); + 13 + │ println!(r#"This line contains invalid utf8: "�����"#; + 14 │ } + 15 │ + 16 │ fn area(rectangle: &Rectangle) -> u32 { + 17 │ rectangle.width * rectangle.height + 18 │ } + 19 + │ + 20 + │ fn perimeter(rectangle: &Rectangle) -> u32 { + 21 + │ (rectangle.width + rectangle.height) * 2 + 22 + │ } +───────┴──────────────────────────────────────────────────────────────────────── diff --git a/tests/snapshots/output/changes_grid_header_rule.snapshot.txt b/tests/snapshots/output/changes_grid_header_rule.snapshot.txt new file mode 100644 index 00000000..655b6e24 --- /dev/null +++ b/tests/snapshots/output/changes_grid_header_rule.snapshot.txt @@ -0,0 +1,26 @@ +──┬───────────────────────────────────────────────────────────────────────────── + │ File: sample.rs +──┼───────────────────────────────────────────────────────────────────────────── + │ struct Rectangle { + │ width: u32, + │ height: u32, + │ } + │ +_ │ fn main() { + │ let rect1 = Rectangle { width: 30, height: 50 }; + │ + │ println!( +~ │ "The perimeter of the rectangle is {} pixels.", +~ │ perimeter(&rect1) + │ ); ++ │ println!(r#"This line contains invalid utf8: "�����"#; + │ } + │ + │ fn area(rectangle: &Rectangle) -> u32 { + │ rectangle.width * rectangle.height + │ } ++ │ ++ │ fn perimeter(rectangle: &Rectangle) -> u32 { ++ │ (rectangle.width + rectangle.height) * 2 ++ │ } +──┴───────────────────────────────────────────────────────────────────────────── diff --git a/tests/snapshots/output/changes_grid_numbers_rule.snapshot.txt b/tests/snapshots/output/changes_grid_numbers_rule.snapshot.txt new file mode 100644 index 00000000..7fe7cccf --- /dev/null +++ b/tests/snapshots/output/changes_grid_numbers_rule.snapshot.txt @@ -0,0 +1,24 @@ +───────┬──────────────────────────────────────────────────────────────────────── + 1 │ struct Rectangle { + 2 │ width: u32, + 3 │ height: u32, + 4 │ } + 5 │ + 6 _ │ fn main() { + 7 │ let rect1 = Rectangle { width: 30, height: 50 }; + 8 │ + 9 │ println!( + 10 ~ │ "The perimeter of the rectangle is {} pixels.", + 11 ~ │ perimeter(&rect1) + 12 │ ); + 13 + │ println!(r#"This line contains invalid utf8: "�����"#; + 14 │ } + 15 │ + 16 │ fn area(rectangle: &Rectangle) -> u32 { + 17 │ rectangle.width * rectangle.height + 18 │ } + 19 + │ + 20 + │ fn perimeter(rectangle: &Rectangle) -> u32 { + 21 + │ (rectangle.width + rectangle.height) * 2 + 22 + │ } +───────┴──────────────────────────────────────────────────────────────────────── diff --git a/tests/snapshots/output/changes_grid_rule.snapshot.txt b/tests/snapshots/output/changes_grid_rule.snapshot.txt new file mode 100644 index 00000000..04767b8b --- /dev/null +++ b/tests/snapshots/output/changes_grid_rule.snapshot.txt @@ -0,0 +1,24 @@ +──┬───────────────────────────────────────────────────────────────────────────── + │ struct Rectangle { + │ width: u32, + │ height: u32, + │ } + │ +_ │ fn main() { + │ let rect1 = Rectangle { width: 30, height: 50 }; + │ + │ println!( +~ │ "The perimeter of the rectangle is {} pixels.", +~ │ perimeter(&rect1) + │ ); ++ │ println!(r#"This line contains invalid utf8: "�����"#; + │ } + │ + │ fn area(rectangle: &Rectangle) -> u32 { + │ rectangle.width * rectangle.height + │ } ++ │ ++ │ fn perimeter(rectangle: &Rectangle) -> u32 { ++ │ (rectangle.width + rectangle.height) * 2 ++ │ } +──┴───────────────────────────────────────────────────────────────────────────── diff --git a/tests/snapshots/output/changes_header_numbers_rule.snapshot.txt b/tests/snapshots/output/changes_header_numbers_rule.snapshot.txt new file mode 100644 index 00000000..77145eb9 --- /dev/null +++ b/tests/snapshots/output/changes_header_numbers_rule.snapshot.txt @@ -0,0 +1,23 @@ + File: sample.rs + 1 struct Rectangle { + 2 width: u32, + 3 height: u32, + 4 } + 5 + 6 _ fn main() { + 7 let rect1 = Rectangle { width: 30, height: 50 }; + 8 + 9 println!( + 10 ~ "The perimeter of the rectangle is {} pixels.", + 11 ~ perimeter(&rect1) + 12 ); + 13 + println!(r#"This line contains invalid utf8: "�����"#; + 14 } + 15 + 16 fn area(rectangle: &Rectangle) -> u32 { + 17 rectangle.width * rectangle.height + 18 } + 19 + + 20 + fn perimeter(rectangle: &Rectangle) -> u32 { + 21 + (rectangle.width + rectangle.height) * 2 + 22 + } diff --git a/tests/snapshots/output/changes_header_rule.snapshot.txt b/tests/snapshots/output/changes_header_rule.snapshot.txt new file mode 100644 index 00000000..82fe8c47 --- /dev/null +++ b/tests/snapshots/output/changes_header_rule.snapshot.txt @@ -0,0 +1,23 @@ + File: sample.rs + struct Rectangle { + width: u32, + height: u32, + } + +_ fn main() { + let rect1 = Rectangle { width: 30, height: 50 }; + + println!( +~ "The perimeter of the rectangle is {} pixels.", +~ perimeter(&rect1) + ); ++ println!(r#"This line contains invalid utf8: "�����"#; + } + + fn area(rectangle: &Rectangle) -> u32 { + rectangle.width * rectangle.height + } ++ ++ fn perimeter(rectangle: &Rectangle) -> u32 { ++ (rectangle.width + rectangle.height) * 2 ++ } diff --git a/tests/snapshots/output/changes_numbers_rule.snapshot.txt b/tests/snapshots/output/changes_numbers_rule.snapshot.txt new file mode 100644 index 00000000..bdfe745b --- /dev/null +++ b/tests/snapshots/output/changes_numbers_rule.snapshot.txt @@ -0,0 +1,22 @@ + 1 struct Rectangle { + 2 width: u32, + 3 height: u32, + 4 } + 5 + 6 _ fn main() { + 7 let rect1 = Rectangle { width: 30, height: 50 }; + 8 + 9 println!( + 10 ~ "The perimeter of the rectangle is {} pixels.", + 11 ~ perimeter(&rect1) + 12 ); + 13 + println!(r#"This line contains invalid utf8: "�����"#; + 14 } + 15 + 16 fn area(rectangle: &Rectangle) -> u32 { + 17 rectangle.width * rectangle.height + 18 } + 19 + + 20 + fn perimeter(rectangle: &Rectangle) -> u32 { + 21 + (rectangle.width + rectangle.height) * 2 + 22 + } diff --git a/tests/snapshots/output/changes_rule.snapshot.txt b/tests/snapshots/output/changes_rule.snapshot.txt new file mode 100644 index 00000000..28d87201 --- /dev/null +++ b/tests/snapshots/output/changes_rule.snapshot.txt @@ -0,0 +1,22 @@ + struct Rectangle { + width: u32, + height: u32, + } + +_ fn main() { + let rect1 = Rectangle { width: 30, height: 50 }; + + println!( +~ "The perimeter of the rectangle is {} pixels.", +~ perimeter(&rect1) + ); ++ println!(r#"This line contains invalid utf8: "�����"#; + } + + fn area(rectangle: &Rectangle) -> u32 { + rectangle.width * rectangle.height + } ++ ++ fn perimeter(rectangle: &Rectangle) -> u32 { ++ (rectangle.width + rectangle.height) * 2 ++ } diff --git a/tests/snapshots/output/grid_header_numbers_rule.snapshot.txt b/tests/snapshots/output/grid_header_numbers_rule.snapshot.txt new file mode 100644 index 00000000..e9f1a9cf --- /dev/null +++ b/tests/snapshots/output/grid_header_numbers_rule.snapshot.txt @@ -0,0 +1,26 @@ +─────┬────────────────────────────────────────────────────────────────────────── + │ File: sample.rs +─────┼────────────────────────────────────────────────────────────────────────── + 1 │ struct Rectangle { + 2 │ width: u32, + 3 │ height: u32, + 4 │ } + 5 │ + 6 │ fn main() { + 7 │ let rect1 = Rectangle { width: 30, height: 50 }; + 8 │ + 9 │ println!( + 10 │ "The perimeter of the rectangle is {} pixels.", + 11 │ perimeter(&rect1) + 12 │ ); + 13 │ println!(r#"This line contains invalid utf8: "�����"#; + 14 │ } + 15 │ + 16 │ fn area(rectangle: &Rectangle) -> u32 { + 17 │ rectangle.width * rectangle.height + 18 │ } + 19 │ + 20 │ fn perimeter(rectangle: &Rectangle) -> u32 { + 21 │ (rectangle.width + rectangle.height) * 2 + 22 │ } +─────┴────────────────────────────────────────────────────────────────────────── diff --git a/tests/snapshots/output/grid_header_rule.snapshot.txt b/tests/snapshots/output/grid_header_rule.snapshot.txt new file mode 100644 index 00000000..50c16941 --- /dev/null +++ b/tests/snapshots/output/grid_header_rule.snapshot.txt @@ -0,0 +1,26 @@ +──────────────────────────────────────────────────────────────────────────────── +File: sample.rs +──────────────────────────────────────────────────────────────────────────────── +struct Rectangle { + width: u32, + height: u32, +} + +fn main() { + let rect1 = Rectangle { width: 30, height: 50 }; + + println!( + "The perimeter of the rectangle is {} pixels.", + perimeter(&rect1) + ); + println!(r#"This line contains invalid utf8: "�����"#; +} + +fn area(rectangle: &Rectangle) -> u32 { + rectangle.width * rectangle.height +} + +fn perimeter(rectangle: &Rectangle) -> u32 { + (rectangle.width + rectangle.height) * 2 +} +──────────────────────────────────────────────────────────────────────────────── diff --git a/tests/snapshots/output/grid_numbers_rule.snapshot.txt b/tests/snapshots/output/grid_numbers_rule.snapshot.txt new file mode 100644 index 00000000..09614667 --- /dev/null +++ b/tests/snapshots/output/grid_numbers_rule.snapshot.txt @@ -0,0 +1,24 @@ +─────┬────────────────────────────────────────────────────────────────────────── + 1 │ struct Rectangle { + 2 │ width: u32, + 3 │ height: u32, + 4 │ } + 5 │ + 6 │ fn main() { + 7 │ let rect1 = Rectangle { width: 30, height: 50 }; + 8 │ + 9 │ println!( + 10 │ "The perimeter of the rectangle is {} pixels.", + 11 │ perimeter(&rect1) + 12 │ ); + 13 │ println!(r#"This line contains invalid utf8: "�����"#; + 14 │ } + 15 │ + 16 │ fn area(rectangle: &Rectangle) -> u32 { + 17 │ rectangle.width * rectangle.height + 18 │ } + 19 │ + 20 │ fn perimeter(rectangle: &Rectangle) -> u32 { + 21 │ (rectangle.width + rectangle.height) * 2 + 22 │ } +─────┴────────────────────────────────────────────────────────────────────────── diff --git a/tests/snapshots/output/grid_rule.snapshot.txt b/tests/snapshots/output/grid_rule.snapshot.txt new file mode 100644 index 00000000..5b970581 --- /dev/null +++ b/tests/snapshots/output/grid_rule.snapshot.txt @@ -0,0 +1,24 @@ +──────────────────────────────────────────────────────────────────────────────── +struct Rectangle { + width: u32, + height: u32, +} + +fn main() { + let rect1 = Rectangle { width: 30, height: 50 }; + + println!( + "The perimeter of the rectangle is {} pixels.", + perimeter(&rect1) + ); + println!(r#"This line contains invalid utf8: "�����"#; +} + +fn area(rectangle: &Rectangle) -> u32 { + rectangle.width * rectangle.height +} + +fn perimeter(rectangle: &Rectangle) -> u32 { + (rectangle.width + rectangle.height) * 2 +} +──────────────────────────────────────────────────────────────────────────────── diff --git a/tests/snapshots/output/header_numbers_rule.snapshot.txt b/tests/snapshots/output/header_numbers_rule.snapshot.txt new file mode 100644 index 00000000..a681e6b4 --- /dev/null +++ b/tests/snapshots/output/header_numbers_rule.snapshot.txt @@ -0,0 +1,23 @@ + File: sample.rs + 1 struct Rectangle { + 2 width: u32, + 3 height: u32, + 4 } + 5 + 6 fn main() { + 7 let rect1 = Rectangle { width: 30, height: 50 }; + 8 + 9 println!( + 10 "The perimeter of the rectangle is {} pixels.", + 11 perimeter(&rect1) + 12 ); + 13 println!(r#"This line contains invalid utf8: "�����"#; + 14 } + 15 + 16 fn area(rectangle: &Rectangle) -> u32 { + 17 rectangle.width * rectangle.height + 18 } + 19 + 20 fn perimeter(rectangle: &Rectangle) -> u32 { + 21 (rectangle.width + rectangle.height) * 2 + 22 } diff --git a/tests/snapshots/output/header_rule.snapshot.txt b/tests/snapshots/output/header_rule.snapshot.txt new file mode 100644 index 00000000..0889edfd --- /dev/null +++ b/tests/snapshots/output/header_rule.snapshot.txt @@ -0,0 +1,23 @@ +File: sample.rs +struct Rectangle { + width: u32, + height: u32, +} + +fn main() { + let rect1 = Rectangle { width: 30, height: 50 }; + + println!( + "The perimeter of the rectangle is {} pixels.", + perimeter(&rect1) + ); + println!(r#"This line contains invalid utf8: "�����"#; +} + +fn area(rectangle: &Rectangle) -> u32 { + rectangle.width * rectangle.height +} + +fn perimeter(rectangle: &Rectangle) -> u32 { + (rectangle.width + rectangle.height) * 2 +} diff --git a/tests/snapshots/output/numbers_rule.snapshot.txt b/tests/snapshots/output/numbers_rule.snapshot.txt new file mode 100644 index 00000000..c1341d29 --- /dev/null +++ b/tests/snapshots/output/numbers_rule.snapshot.txt @@ -0,0 +1,22 @@ + 1 struct Rectangle { + 2 width: u32, + 3 height: u32, + 4 } + 5 + 6 fn main() { + 7 let rect1 = Rectangle { width: 30, height: 50 }; + 8 + 9 println!( + 10 "The perimeter of the rectangle is {} pixels.", + 11 perimeter(&rect1) + 12 ); + 13 println!(r#"This line contains invalid utf8: "�����"#; + 14 } + 15 + 16 fn area(rectangle: &Rectangle) -> u32 { + 17 rectangle.width * rectangle.height + 18 } + 19 + 20 fn perimeter(rectangle: &Rectangle) -> u32 { + 21 (rectangle.width + rectangle.height) * 2 + 22 } diff --git a/tests/snapshots/output/rule.snapshot.txt b/tests/snapshots/output/rule.snapshot.txt new file mode 100644 index 00000000..dbc49f9f --- /dev/null +++ b/tests/snapshots/output/rule.snapshot.txt @@ -0,0 +1,22 @@ +struct Rectangle { + width: u32, + height: u32, +} + +fn main() { + let rect1 = Rectangle { width: 30, height: 50 }; + + println!( + "The perimeter of the rectangle is {} pixels.", + perimeter(&rect1) + ); + println!(r#"This line contains invalid utf8: "�����"#; +} + +fn area(rectangle: &Rectangle) -> u32 { + rectangle.width * rectangle.height +} + +fn perimeter(rectangle: &Rectangle) -> u32 { + (rectangle.width + rectangle.height) * 2 +} From c1af6ff2e6f7c596b381a70da8d37c7a28f764f0 Mon Sep 17 00:00:00 2001 From: Tom Milligan Date: Thu, 8 Oct 2020 09:59:14 +0100 Subject: [PATCH 058/243] Add integration test for style rule --- tests/integration_tests.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/integration_tests.rs b/tests/integration_tests.rs index 9dfa8067..a55d081d 100644 --- a/tests/integration_tests.rs +++ b/tests/integration_tests.rs @@ -680,6 +680,26 @@ fn header_padding() { .stderr(""); } +#[test] +fn header_padding_rule() { + bat() + .arg("--decorations=always") + .arg("--style=header,rule") + .arg("--terminal-width=80") + .arg("test.txt") + .arg("single-line.txt") + .assert() + .stdout( + "File: test.txt +hello world +──────────────────────────────────────────────────────────────────────────────── +File: single-line.txt +Single Line +", + ) + .stderr(""); +} + #[cfg(target_os = "linux")] #[test] fn file_with_invalid_utf8_filename() { From d7da4f5f2b0206e6c36b14b54337751cd4c63f79 Mon Sep 17 00:00:00 2001 From: Tom Milligan Date: Mon, 12 Oct 2020 08:13:32 +0100 Subject: [PATCH 059/243] update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b181ff3a..2a549f93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ## Features - Adjust pager configuration to comply with `--wrap=never`, see #1255 (@gahag) +- Added a new `--style` value, `rule`, which adds a simple horizontal ruled line between files, see #1276 (@tommilligan) ## Bugfixes From 3015ebfba1c1e95f8fd664a7cd9c7cbbd7bc3dcf Mon Sep 17 00:00:00 2001 From: Tom Milligan Date: Mon, 12 Oct 2020 08:40:01 +0100 Subject: [PATCH 060/243] disable rule when grid enabled, and print warning --- src/bin/bat/app.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/bin/bat/app.rs b/src/bin/bat/app.rs index 8249e3c9..8d09618c 100644 --- a/src/bin/bat/app.rs +++ b/src/bin/bat/app.rs @@ -288,8 +288,8 @@ impl App { fn style_components(&self) -> Result { let matches = &self.matches; - Ok(StyleComponents( - if matches.value_of("decorations") == Some("never") { + let mut styled_components = + StyleComponents(if matches.value_of("decorations") == Some("never") { HashSet::new() } else if matches.is_present("number") { [StyleComponent::LineNumbers].iter().cloned().collect() @@ -323,7 +323,17 @@ impl App { acc.extend(components.iter().cloned()); acc }) - }, - )) + }); + + // If `grid` is set, remove `rule` as it is a subset of `grid`, and print a warning. + if styled_components.grid() && styled_components.0.remove(&StyleComponent::Rule) { + use ansi_term::Colour::Yellow; + eprintln!( + "{}: Style 'rule' is a subset of style 'grid', 'rule' will not be visible.", + Yellow.paint("[bat warning]"), + ); + } + + Ok(styled_components) } } From e293c58bb0d53c32b69b5fdcd9cc6a617bf75312 Mon Sep 17 00:00:00 2001 From: Tom Milligan Date: Mon, 12 Oct 2020 08:44:18 +0100 Subject: [PATCH 061/243] update man pages --- assets/manual/bat.1.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets/manual/bat.1.in b/assets/manual/bat.1.in index a6846b5d..65a17fe1 100644 --- a/assets/manual/bat.1.in +++ b/assets/manual/bat.1.in @@ -129,7 +129,7 @@ Configure which elements (line numbers, file headers, grid borders, Git modifica of components to display (e.g. 'numbers,changes,grid') or a pre\-defined style ('full'). To set a default style, add the '\-\-style=".."' option to the configuration file or export the BAT_STYLE environment variable (e.g.: export BAT_STYLE=".."). Possible -values: *auto*, full, plain, changes, header, grid, numbers, snip. +values: *auto*, full, plain, changes, header, grid, rule, numbers, snip. .HP \fB\-r\fR, \fB\-\-line\-range\fR ... .IP From 1614f80366a1fcc344df157d04bb5284ef09ee4c Mon Sep 17 00:00:00 2001 From: Tom Milligan Date: Mon, 12 Oct 2020 09:02:08 +0100 Subject: [PATCH 062/243] add integration test for grid overriding rule --- tests/integration_tests.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/integration_tests.rs b/tests/integration_tests.rs index a55d081d..f8ff60a5 100644 --- a/tests/integration_tests.rs +++ b/tests/integration_tests.rs @@ -700,6 +700,28 @@ Single Line .stderr(""); } +#[test] +fn grid_overrides_rule() { + bat() + .arg("--decorations=always") + .arg("--style=grid,rule") + .arg("--terminal-width=80") + .arg("test.txt") + .arg("single-line.txt") + .assert() + .stdout( + "\ +──────────────────────────────────────────────────────────────────────────────── +hello world +──────────────────────────────────────────────────────────────────────────────── +──────────────────────────────────────────────────────────────────────────────── +Single Line +──────────────────────────────────────────────────────────────────────────────── +", + ) + .stderr("\x1b[33m[bat warning]\x1b[0m: Style 'rule' is a subset of style 'grid', 'rule' will not be visible.\n"); +} + #[cfg(target_os = "linux")] #[test] fn file_with_invalid_utf8_filename() { From a39f1e0f9b63833b2d34ae96e0aa176338e0a0c7 Mon Sep 17 00:00:00 2001 From: okezieuc <53785400+okezieuc@users.noreply.github.com> Date: Mon, 12 Oct 2020 15:26:10 +0100 Subject: [PATCH 063/243] added new syntax highlighting files I added a sample etc/hosts file and a sample requirements.txt file. I didn't know there was already a sample YAML file because it wasn't ticked in the issue so I added some extra syntax that I had in my own to the previous example.yaml file. --- tests/syntax-tests/highlighted/Hosts/hosts | 8 ++++++++ .../RequirementsTXT/requirements.txt | 8 ++++++++ .../syntax-tests/highlighted/YAML/example.yaml | 16 ++++++++++++++++ tests/syntax-tests/source/Hosts/hosts | 8 ++++++++ .../source/RequirementsTXT/requirements.txt | 8 ++++++++ tests/syntax-tests/source/YAML/example.yaml | 18 +++++++++++++++++- 6 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 tests/syntax-tests/highlighted/Hosts/hosts create mode 100644 tests/syntax-tests/highlighted/RequirementsTXT/requirements.txt create mode 100644 tests/syntax-tests/source/Hosts/hosts create mode 100644 tests/syntax-tests/source/RequirementsTXT/requirements.txt diff --git a/tests/syntax-tests/highlighted/Hosts/hosts b/tests/syntax-tests/highlighted/Hosts/hosts new file mode 100644 index 00000000..8d322f00 --- /dev/null +++ b/tests/syntax-tests/highlighted/Hosts/hosts @@ -0,0 +1,8 @@ +#this is a comment in the hosts file +127.0.0.1  localhost + +192.168.0.1 sample.test #a comment +192.160.0.200 try.sample.test try #another comment +216.58.223.238 google.com + +::1 localhost.try ip6-localhost diff --git a/tests/syntax-tests/highlighted/RequirementsTXT/requirements.txt b/tests/syntax-tests/highlighted/RequirementsTXT/requirements.txt new file mode 100644 index 00000000..b7c5155f --- /dev/null +++ b/tests/syntax-tests/highlighted/RequirementsTXT/requirements.txt @@ -0,0 +1,8 @@ +#this is a sample requirements.txt file + +django==11.2.0 +pywheels>=12.4 #a whitespace followed by comments +Nuitka<0.6.8.4 +wxPython>=1.0, <=2.1 + +#this is another comment diff --git a/tests/syntax-tests/highlighted/YAML/example.yaml b/tests/syntax-tests/highlighted/YAML/example.yaml index a6e2c00c..23e50275 100644 --- a/tests/syntax-tests/highlighted/YAML/example.yaml +++ b/tests/syntax-tests/highlighted/YAML/example.yaml @@ -4,6 +4,9 @@ name: Test User username: "testuser" other_names: ['Bob', 'Bill', 'George'] +hexa: 0x11c3 #inline comment +octa: 021131 +lastseen: .NAN enabled: true locked: false groups:  @@ -13,6 +16,19 @@ address: >  123 Alphabet Way  San Francisco, CA +bio: | + I am a hardworking person + and a member of the + executive staff phone: null +email: ~ building_access: yes secure_access: no +bulb: On +fans: Off +emails: + executives: + - bob@example.com + - bill@example.com + supervisors: + - george@example.com diff --git a/tests/syntax-tests/source/Hosts/hosts b/tests/syntax-tests/source/Hosts/hosts new file mode 100644 index 00000000..d7d4307d --- /dev/null +++ b/tests/syntax-tests/source/Hosts/hosts @@ -0,0 +1,8 @@ +#this is a comment in the hosts file +127.0.0.1 localhost + +192.168.0.1 sample.test #a comment +192.160.0.200 try.sample.test try #another comment +216.58.223.238 google.com + +::1 localhost.try ip6-localhost \ No newline at end of file diff --git a/tests/syntax-tests/source/RequirementsTXT/requirements.txt b/tests/syntax-tests/source/RequirementsTXT/requirements.txt new file mode 100644 index 00000000..83a41dc8 --- /dev/null +++ b/tests/syntax-tests/source/RequirementsTXT/requirements.txt @@ -0,0 +1,8 @@ +#this is a sample requirements.txt file + +django==11.2.0 +pywheels>=12.4 #a whitespace followed by comments +Nuitka<0.6.8.4 +wxPython>=1.0, <=2.1 + +#this is another comment \ No newline at end of file diff --git a/tests/syntax-tests/source/YAML/example.yaml b/tests/syntax-tests/source/YAML/example.yaml index cc2f63e4..1b215705 100644 --- a/tests/syntax-tests/source/YAML/example.yaml +++ b/tests/syntax-tests/source/YAML/example.yaml @@ -4,6 +4,9 @@ id: 3595 name: Test User username: "testuser" other_names: ['Bob', 'Bill', 'George'] +hexa: 0x11c3 #inline comment +octa: 021131 +lastseen: .NAN enabled: true locked: false groups: @@ -13,6 +16,19 @@ groups: address: > 123 Alphabet Way San Francisco, CA +bio: | + I am a hardworking person + and a member of the + executive staff phone: null +email: ~ building_access: yes -secure_access: no \ No newline at end of file +secure_access: no +bulb: On +fans: Off +emails: + executives: + - bob@example.com + - bill@example.com + supervisors: + - george@example.com \ No newline at end of file From eeea53759bc3dfce932e901ee6eec18e9fae546e Mon Sep 17 00:00:00 2001 From: Sebastian Andersson Date: Tue, 13 Oct 2020 17:48:50 +0200 Subject: [PATCH 064/243] Add apache httpd.conf example --- .../highlighted/Apache/httpd.conf | 42 +++++++++++++++++++ tests/syntax-tests/source/Apache/httpd.conf | 42 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Apache/httpd.conf create mode 100644 tests/syntax-tests/source/Apache/httpd.conf diff --git a/tests/syntax-tests/highlighted/Apache/httpd.conf b/tests/syntax-tests/highlighted/Apache/httpd.conf new file mode 100644 index 00000000..80eb01ff --- /dev/null +++ b/tests/syntax-tests/highlighted/Apache/httpd.conf @@ -0,0 +1,42 @@ +# This is a comment +# +ServerRoot "" +Listen 80 +LoadModule mpm_event_module /usr/lib/apache2/modules/mod_mpm_event.so +<IfModule unixd_module> +User daemon +Group daemon + +ServerAdmin you@example.com +<Directory /> + AllowOverride none + Require all denied + +DocumentRoot "/usr/share/apache2/default-site/htdocs" +<Directory "/usr/share/apache2/default-site/htdocs"> + Options Indexes FollowSymLinks + AllowOverride None + Require all granted + +<Files ".ht*"> + Require all denied + +ErrorLog "/var/log/apache2/error_log" +LogLevel warn +<IfModule log_config_module> + LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined + CustomLog "/var/log/apache2/access_log" common + + +<IfModule alias_module> + ScriptAlias /cgi-bin/ "/usr/lib/cgi-bin/" + + +<IfModule mime_module> + TypesConfig /etc/apache2/mime.types + AddType application/x-compress .Z + AddOutputFilter INCLUDES .shtml + +<IfModule proxy_html_module> +Include /etc/apache2/extra/proxy-html.conf + diff --git a/tests/syntax-tests/source/Apache/httpd.conf b/tests/syntax-tests/source/Apache/httpd.conf new file mode 100644 index 00000000..66287352 --- /dev/null +++ b/tests/syntax-tests/source/Apache/httpd.conf @@ -0,0 +1,42 @@ +# This is a comment +# +ServerRoot "" +Listen 80 +LoadModule mpm_event_module /usr/lib/apache2/modules/mod_mpm_event.so + +User daemon +Group daemon + +ServerAdmin you@example.com + + AllowOverride none + Require all denied + +DocumentRoot "/usr/share/apache2/default-site/htdocs" + + Options Indexes FollowSymLinks + AllowOverride None + Require all granted + + + Require all denied + +ErrorLog "/var/log/apache2/error_log" +LogLevel warn + + LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined + CustomLog "/var/log/apache2/access_log" common + + + + ScriptAlias /cgi-bin/ "/usr/lib/cgi-bin/" + + + + TypesConfig /etc/apache2/mime.types + AddType application/x-compress .Z + AddOutputFilter INCLUDES .shtml + + +Include /etc/apache2/extra/proxy-html.conf + From bf07b0be58d4ae7d247de04c2f7a57a851664e7a Mon Sep 17 00:00:00 2001 From: Saul Blanco Tejero Date: Mon, 12 Oct 2020 13:21:43 +0200 Subject: [PATCH 065/243] Add Perl test file --- tests/syntax-tests/highlighted/Perl/test.pl | 157 ++++++++++++++++++++ tests/syntax-tests/source/Perl/test.pl | 157 ++++++++++++++++++++ 2 files changed, 314 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Perl/test.pl create mode 100644 tests/syntax-tests/source/Perl/test.pl diff --git a/tests/syntax-tests/highlighted/Perl/test.pl b/tests/syntax-tests/highlighted/Perl/test.pl new file mode 100644 index 00000000..eda26d1d --- /dev/null +++ b/tests/syntax-tests/highlighted/Perl/test.pl @@ -0,0 +1,157 @@ +# Perl Test +# By saul-bt +# PUBLIC DOMAIN + +use strict; +use warnings; + +## REFERENCES ## +my @colors = ("red", "green", "blue"); + +# '\' can be used to get a reference +my $colorsRef = \@colors; + +my %superHash = ( + "colors" => $colorsRef, + # Also you can create an anonymous + # array with '[]' ({} for hashes) + # that returns the reference + "numbers" => [1, 2, 3] +); + +# Now the hash stores something like +# this: ("colors", ARRAY(0x...), +# "numbers", ARRAY(0x...)) + +# And you can access these arrays with: +print qq(@{$superHash{"colors"}}\n); + +# To print an element: +print qq(${$superHash{"numbers"}}[0]\n); +print $superHash{"colors"} -> [0], "\n"; + +# Size of array: +print scalar @{$superHash{"colors"}}; + + +## ARRAYS ## +%meh1 = (num => 0, val => 4); +%meh2 = ( + num => 1, + val => 3 +); + +@mehs = (\%meh1, \%meh2); + +print $mehs[0]{val}; + + +## HANDLERS & HEREDOC ## +print "What's your name? "; +$name = <STDIN>; +chomp($name); + +print <<WELCOME; + +Hi $name, Where are you from? +WELCOME + +$place = <STDIN>; +chomp($place); + +print <<GOODBYE; + +Oh, you are $name from $place... +I hear that $place is a beautiful place. +It's nice meet people like you $name. +I hope to see you soon :) + +Bye $name. +GOODBYE + +open (content, "<", "file.txt"); + +for $line (<content>) { + print $line; +} + +print "What are you looking for? "; +$numResults = 0; +$word = <STDIN>; +chomp($word); + +for $line (<>) { + if ($line =~ m/\b$word\b/i) { + $numResults += 1; + print "[$word FOUND]> $line\n"; + next; + } + print $line; +} + +print "\n\n=== There are $numResults coincidences ==="; + + +## SCRIPT ARGUMENTS ## +$nargs = $#ARGV + 1; + +print "There are $nargs arguments:\n"; + +for $arg (@ARGV) { + print "- $arg\n"; +} + +## REGEX STUFF ## +$string = "Perl is cool"; + +if ($string =~ m/[Pp]erl/) { + print "Yeah"; +} +elsif ($string =~ m(perl)i) { + print "Sad"; +} +else { + print "MEH"; +} + +# From my dummy recreation of printf +sub checkTypes { + my @percents = @{scalar(shift)}; + my @args = @{scalar(shift)}; + my $size = scalar(@percents); + + foreach my $n (0..$size - 1) { + my $currArg = $args[$n]; + my $currFormat = substr($percents[$n],-1); +  + $currFormat eq 's' && $currArg =~ m/^\D+$/ || + $currFormat =~ m/[dx]/ && $currArg =~ m/^\d+$/ || + $currFormat eq 'f' && $currArg =~ m/^\d+(?:\.\d+)?$/ or + die "'$currArg' can't be formatted as '$currFormat'"; + } +} + +## WEIRD STUFF (JAPH) ## +# VMS <3 +not exp log srand xor s qq qx xor +s x x length uc ord and print chr +ord for qw q join use sub tied qx +xor eval xor print qq q q xor int +eval lc q m cos and print chr ord +for qw y abs ne open tied hex exp +ref y m xor scalar srand print qq +q q xor int eval lc qq y sqrt cos +and print chr ord for qw x printf +each return local x y or print qq +s s and eval q s undef or oct xor +time xor ref print chr int ord lc +foreach qw y hex alarm chdir kill +exec return y s gt sin sort split + +@P=split//,".URRUU\c8R";@d=split//,"\nrekcah xinU / lreP rehtona tsuJ";sub p{ +@p{"r$p","u$p"}=(P,P);pipe"r$p","u$p";++$p;($q*=2)+=$f=!fork;map{$P=$P[$f^ord +($p{$_})&6];$p{$_}=/ ^$P/ix?$P:close$_}keys%p}p;p;p;p;p;map{$p{$_}=~/^[P.]/&& +close$_}%p;wait until$?;map{/^r/&&<$_>}%p;$_=$d[$q];sleep rand(2)if/\S/;print + +''=~('(?{'.('-)@.)@_*([]@!@/)(@)@-@),@(@@+@)' +^'][)@]`}`]()`@.@]@%[`}%[@`@!#@%[').',"})') diff --git a/tests/syntax-tests/source/Perl/test.pl b/tests/syntax-tests/source/Perl/test.pl new file mode 100644 index 00000000..50128d9c --- /dev/null +++ b/tests/syntax-tests/source/Perl/test.pl @@ -0,0 +1,157 @@ +# Perl Test +# By saul-bt +# PUBLIC DOMAIN + +use strict; +use warnings; + +## REFERENCES ## +my @colors = ("red", "green", "blue"); + +# '\' can be used to get a reference +my $colorsRef = \@colors; + +my %superHash = ( + "colors" => $colorsRef, + # Also you can create an anonymous + # array with '[]' ({} for hashes) + # that returns the reference + "numbers" => [1, 2, 3] +); + +# Now the hash stores something like +# this: ("colors", ARRAY(0x...), +# "numbers", ARRAY(0x...)) + +# And you can access these arrays with: +print qq(@{$superHash{"colors"}}\n); + +# To print an element: +print qq(${$superHash{"numbers"}}[0]\n); +print $superHash{"colors"} -> [0], "\n"; + +# Size of array: +print scalar @{$superHash{"colors"}}; + + +## ARRAYS ## +%meh1 = (num => 0, val => 4); +%meh2 = ( + num => 1, + val => 3 +); + +@mehs = (\%meh1, \%meh2); + +print $mehs[0]{val}; + + +## HANDLERS & HEREDOC ## +print "What's your name? "; +$name = ; +chomp($name); + +print <; +chomp($place); + +print <) { + print $line; +} + +print "What are you looking for? "; +$numResults = 0; +$word = ; +chomp($word); + +for $line (<>) { + if ($line =~ m/\b$word\b/i) { + $numResults += 1; + print "[$word FOUND]> $line\n"; + next; + } + print $line; +} + +print "\n\n=== There are $numResults coincidences ==="; + + +## SCRIPT ARGUMENTS ## +$nargs = $#ARGV + 1; + +print "There are $nargs arguments:\n"; + +for $arg (@ARGV) { + print "- $arg\n"; +} + +## REGEX STUFF ## +$string = "Perl is cool"; + +if ($string =~ m/[Pp]erl/) { + print "Yeah"; +} +elsif ($string =~ m(perl)i) { + print "Sad"; +} +else { + print "MEH"; +} + +# From my dummy recreation of printf +sub checkTypes { + my @percents = @{scalar(shift)}; + my @args = @{scalar(shift)}; + my $size = scalar(@percents); + + foreach my $n (0..$size - 1) { + my $currArg = $args[$n]; + my $currFormat = substr($percents[$n],-1); + + $currFormat eq 's' && $currArg =~ m/^\D+$/ || + $currFormat =~ m/[dx]/ && $currArg =~ m/^\d+$/ || + $currFormat eq 'f' && $currArg =~ m/^\d+(?:\.\d+)?$/ or + die "'$currArg' can't be formatted as '$currFormat'"; + } +} + +## WEIRD STUFF (JAPH) ## +# VMS <3 +not exp log srand xor s qq qx xor +s x x length uc ord and print chr +ord for qw q join use sub tied qx +xor eval xor print qq q q xor int +eval lc q m cos and print chr ord +for qw y abs ne open tied hex exp +ref y m xor scalar srand print qq +q q xor int eval lc qq y sqrt cos +and print chr ord for qw x printf +each return local x y or print qq +s s and eval q s undef or oct xor +time xor ref print chr int ord lc +foreach qw y hex alarm chdir kill +exec return y s gt sin sort split + +@P=split//,".URRUU\c8R";@d=split//,"\nrekcah xinU / lreP rehtona tsuJ";sub p{ +@p{"r$p","u$p"}=(P,P);pipe"r$p","u$p";++$p;($q*=2)+=$f=!fork;map{$P=$P[$f^ord +($p{$_})&6];$p{$_}=/ ^$P/ix?$P:close$_}keys%p}p;p;p;p;p;map{$p{$_}=~/^[P.]/&& +close$_}%p;wait until$?;map{/^r/&&<$_>}%p;$_=$d[$q];sleep rand(2)if/\S/;print + +''=~('(?{'.('-)@.)@_*([]@!@/)(@)@-@),@(@@+@)' +^'][)@]`}`]()`@.@]@%[`}%[@`@!#@%[').',"})') From 5650624822cac9dc9ac40990d1c65b4f42182996 Mon Sep 17 00:00:00 2001 From: Benjamin Sinkula Date: Tue, 13 Oct 2020 13:31:22 -0500 Subject: [PATCH 066/243] Add ActionScript 3 syntax test --- .../highlighted/ActionScript/test.as | 75 +++++++++++++++++++ .../syntax-tests/source/ActionScript/test.as | 75 +++++++++++++++++++ 2 files changed, 150 insertions(+) create mode 100644 tests/syntax-tests/highlighted/ActionScript/test.as create mode 100644 tests/syntax-tests/source/ActionScript/test.as diff --git a/tests/syntax-tests/highlighted/ActionScript/test.as b/tests/syntax-tests/highlighted/ActionScript/test.as new file mode 100644 index 00000000..2078c571 --- /dev/null +++ b/tests/syntax-tests/highlighted/ActionScript/test.as @@ -0,0 +1,75 @@ +import flash.events.*; +import flash.events.MouseEvent; + +package TestSyntax { + public class TestSyntax extends flash.display.Sprite { + + public static const TEST_CONSTANT:Number = 33.333; + + var testAttribute:int = 1; + + public namespace TestNamespace; + TestNamespace function Method2():void { } + + /** + * Multi-line comment + */ + override public function set x(value:Number):void + { + super.x = Math.round(value); + } + + /** + * Actual multi-line comment + * Takes up multiple lines + */ + override public function set y(value:Number):void + { + super.y = 0; + } + + public function testFunction() { + var test:String = 'hello'; + + // arrays + var testArray:Array = ["a", "b", "c", "d"]; + for (var i:uint = 0; i < testArray.length; i++) + trace(testArray[i]); + + // objects + var testObject:Object = {foo: 20, bar: 40}; + for (var key:String in testObject) { + trace(testObject[key]); + } + for each (var objectValue:int in testObject) { + trace(objectValue); + } + + // dynamic variables + var testDynamic:*; + testDynamic = 75; + testDynamic = "Seventy-five"; + + // regex + var testRegExp:RegExp = /foo-\d+/i; + + // XML + var testXML:XML = + + Harold</firstName> + Webster</lastName> +</employee>; + } + + private function anotherFunc(a:int, arg2:uint, arg3:Function, ... args) { + + } + + [Embed(source="sound1.mp3")] public var soundCls:Class; + public function SoundAssetExample() + { + var mySound:SoundAsset = new soundCls() as SoundAsset; + var sndChannel:SoundChannel = mySound.play(); + } + } +} diff --git a/tests/syntax-tests/source/ActionScript/test.as b/tests/syntax-tests/source/ActionScript/test.as new file mode 100644 index 00000000..1f7a1936 --- /dev/null +++ b/tests/syntax-tests/source/ActionScript/test.as @@ -0,0 +1,75 @@ +import flash.events.*; +import flash.events.MouseEvent; + +package TestSyntax { + public class TestSyntax extends flash.display.Sprite { + + public static const TEST_CONSTANT:Number = 33.333; + + var testAttribute:int = 1; + + public namespace TestNamespace; + TestNamespace function Method2():void { } + + /** + * Multi-line comment + */ + override public function set x(value:Number):void + { + super.x = Math.round(value); + } + + /** + * Actual multi-line comment + * Takes up multiple lines + */ + override public function set y(value:Number):void + { + super.y = 0; + } + + public function testFunction() { + var test:String = 'hello'; + + // arrays + var testArray:Array = ["a", "b", "c", "d"]; + for (var i:uint = 0; i < testArray.length; i++) + trace(testArray[i]); + + // objects + var testObject:Object = {foo: 20, bar: 40}; + for (var key:String in testObject) { + trace(testObject[key]); + } + for each (var objectValue:int in testObject) { + trace(objectValue); + } + + // dynamic variables + var testDynamic:*; + testDynamic = 75; + testDynamic = "Seventy-five"; + + // regex + var testRegExp:RegExp = /foo-\d+/i; + + // XML + var testXML:XML = + + Harold + Webster +; + } + + private function anotherFunc(a:int, arg2:uint, arg3:Function, ... args) { + + } + + [Embed(source="sound1.mp3")] public var soundCls:Class; + public function SoundAssetExample() + { + var mySound:SoundAsset = new soundCls() as SoundAsset; + var sndChannel:SoundChannel = mySound.play(); + } + } +} \ No newline at end of file From d075d2b453c51c66cc02c69c22d431ffd056a259 Mon Sep 17 00:00:00 2001 From: Pablo Santiago Blum de Aguiar Date: Wed, 7 Oct 2020 20:45:36 +0200 Subject: [PATCH 067/243] Make logo compatible with light and dark themes --- doc/logo-header.svg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/logo-header.svg b/doc/logo-header.svg index 17830b84..b29b2e7f 100644 --- a/doc/logo-header.svg +++ b/doc/logo-header.svg @@ -45,7 +45,7 @@ showguides="true" inkscape:guide-bbox="true" /> Date: Wed, 14 Oct 2020 19:18:11 +1300 Subject: [PATCH 068/243] Integrate README.md with new assets.md (#1293) --- README.md | 16 +++++++++++----- assets/README.md => doc/assets.md | 18 +++++++++++++----- 2 files changed, 24 insertions(+), 10 deletions(-) rename assets/README.md => doc/assets.md (77%) diff --git a/README.md b/README.md index d4703245..522a4535 100644 --- a/README.md +++ b/README.md @@ -391,12 +391,14 @@ variable to make these changes permanent or use `bat`s ### Adding new syntaxes / language definitions -`bat` uses the excellent [`syntect`](https://github.com/trishume/syntect/) +Should you find a particular syntax is not available within `bat`, you can follow these instructions to easily add new syntaxes to your current `bat` installation. + +By default, `bat` uses the excellent [`syntect`](https://github.com/trishume/syntect/) library for syntax highlighting. `syntect` can read any [Sublime Text `.sublime-syntax` file](https://www.sublimetext.com/docs/3/syntax.html) -and theme. To add new syntax definitions, do the following. +and theme. -Create a folder with syntax definition files: +1. Create a folder with syntax definition files: ```bash mkdir -p "$(bat --config-dir)/syntaxes" @@ -407,13 +409,13 @@ cd "$(bat --config-dir)/syntaxes" git clone https://github.com/tellnobody1/sublime-purescript-syntax ``` -Now use the following command to parse these files into a binary cache: +2. Now use the following command to parse these files into a binary cache: ```bash bat cache --build ``` -Finally, use `bat --list-languages` to check if the new languages are available. +3. Finally, use `bat --list-languages` to check if the new languages are available. If you ever want to go back to the default settings, call: @@ -421,6 +423,10 @@ If you ever want to go back to the default settings, call: bat cache --clear ``` +4. If you think that a specific syntax should be included in `bat` by default, please + consider opening a "syntax request" ticket after reading the policies and + instructions [here](doc/assets.md) + ### Adding new themes This works very similar to how we add new syntax definitions. diff --git a/assets/README.md b/doc/assets.md similarity index 77% rename from assets/README.md rename to doc/assets.md index db87179f..20da7f55 100644 --- a/assets/README.md +++ b/doc/assets.md @@ -1,10 +1,12 @@ -## Syntax Highlighting in bat +## Add New Syntax Highlighting into the bat binary -`bat` uses the [syntect](https://github.com/trishume/syntect) library to highlight source +Should you find a particular syntax is not available within `bat` and think it should be included in `bat` by default, you can follow the instructions and policies outlined below. + +`bat` uses the excellent [syntect](https://github.com/trishume/syntect) library to highlight source code. As a basis, syntect uses [Sublime Text](https://www.sublimetext.com/) syntax definitions in the `.sublime-syntax` format. -In order to add new syntaxes to `bat`, follow these steps: +**Important:** Before proceeding, verify that the syntax you wish to add meets the [criteria for inclusion](#Criteria-for-inclusion-of-new-syntaxes). 1. Find a Sublime Text syntax for the given language, preferably in a separate Git repository which can be included as a submodule (under `assets/syntaxes`). @@ -13,13 +15,15 @@ In order to add new syntaxes to `bat`, follow these steps: Sublime Text and convert it to a `.sublime-syntax` file via *Tools* -> *Developer* -> *New Syntax from XXX.tmLanguage...*. Save the new file in the `assets/syntaxes` folder. -3. Run the `create.sh` script. It calls `bat cache --build` to parse all available +3. Run the `assets/create.sh` script. It calls `bat cache --build` to parse all available `.sublime-syntax` files and serialize them to a `syntaxes.bin` file (in this folder). 4. Re-compile `bat`. At compilation time, the `syntaxes.bin` file will be stored inside the `bat` binary. -5. If you send a pull request with your changes, please do *not* include the changed `syntaxes.bin` +5. Use `bat --list-languages` to check if the new languages are available. + +6. If you send a pull request with your changes, please do *not* include the changed `syntaxes.bin` file. A new binary cache file will be created once before every new release of `bat`. ### Troubleshooting @@ -50,3 +54,7 @@ The following files have been manually modified after converting from a `.tmLang https://github.com/seanjames777/SML-Language-Definition/blob/master/sml.tmLanguage * `Cabal.sublime_syntax` has been added manually from https://github.com/SublimeHaskell/SublimeHaskell/ - we don't want to include the whole submodule because it includes other syntaxes ("Haskell improved") as well. + +## Criteria for inclusion of new syntaxes + +* More than 10,000 downloads on packagecontrol.io/ \ No newline at end of file From bf78b74db4274361d2d6eb4746e1c77667b99255 Mon Sep 17 00:00:00 2001 From: sharkdp Date: Wed, 14 Oct 2020 08:24:20 +0200 Subject: [PATCH 069/243] Minor README improvements --- README.md | 16 ++++++++++------ doc/assets.md | 14 +++++++------- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 522a4535..a3a1e8dc 100644 --- a/README.md +++ b/README.md @@ -391,12 +391,16 @@ variable to make these changes permanent or use `bat`s ### Adding new syntaxes / language definitions -Should you find a particular syntax is not available within `bat`, you can follow these instructions to easily add new syntaxes to your current `bat` installation. +Should you find that a particular syntax is not available within `bat`, you can follow these +instructions to easily add new syntaxes to your current `bat` installation. -By default, `bat` uses the excellent [`syntect`](https://github.com/trishume/syntect/) +`bat` uses the excellent [`syntect`](https://github.com/trishume/syntect/) library for syntax highlighting. `syntect` can read any [Sublime Text `.sublime-syntax` file](https://www.sublimetext.com/docs/3/syntax.html) -and theme. +and theme. + +A good resource for finding Sublime Syntax packages is [Package Control](https://packagecontrol.io/). Once you found a +syntax: 1. Create a folder with syntax definition files: @@ -423,9 +427,9 @@ If you ever want to go back to the default settings, call: bat cache --clear ``` -4. If you think that a specific syntax should be included in `bat` by default, please - consider opening a "syntax request" ticket after reading the policies and - instructions [here](doc/assets.md) +4. If you think that a specific syntax should be included in `bat` by default, please + consider opening a "syntax request" ticket after reading the policies and + instructions [here](doc/assets.md): [Open Syntax Request](https://github.com/sharkdp/bat/issues/new?labels=syntax-request&template=syntax_request.md). ### Adding new themes diff --git a/doc/assets.md b/doc/assets.md index 20da7f55..b70603de 100644 --- a/doc/assets.md +++ b/doc/assets.md @@ -1,7 +1,7 @@ -## Add New Syntax Highlighting into the bat binary +## Adding new builtin languages for syntax highlighting + +Should you find that a particular syntax is not available within `bat` and think it should be included in `bat` by default, you can follow the instructions outlined below. -Should you find a particular syntax is not available within `bat` and think it should be included in `bat` by default, you can follow the instructions and policies outlined below. - `bat` uses the excellent [syntect](https://github.com/trishume/syntect) library to highlight source code. As a basis, syntect uses [Sublime Text](https://www.sublimetext.com/) syntax definitions in the `.sublime-syntax` format. @@ -31,6 +31,10 @@ in the `.sublime-syntax` format. Make sure that the local cache does not interfere with the internally stored syntaxes and themes (`bat cache --clear`). +## Criteria for inclusion of new syntaxes + +* More than 10,000 downloads on packagecontrol.io/ + ### Manual modifications The following files have been manually modified after converting from a `.tmLanguage` file: @@ -54,7 +58,3 @@ The following files have been manually modified after converting from a `.tmLang https://github.com/seanjames777/SML-Language-Definition/blob/master/sml.tmLanguage * `Cabal.sublime_syntax` has been added manually from https://github.com/SublimeHaskell/SublimeHaskell/ - we don't want to include the whole submodule because it includes other syntaxes ("Haskell improved") as well. - -## Criteria for inclusion of new syntaxes - -* More than 10,000 downloads on packagecontrol.io/ \ No newline at end of file From 57c1a7fd694a7fffcfa6d6d2071eb8d5aabcd186 Mon Sep 17 00:00:00 2001 From: David Peter Date: Wed, 14 Oct 2020 08:26:02 +0200 Subject: [PATCH 070/243] Formatting fix --- README.md | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index a3a1e8dc..e5cfc0f9 100644 --- a/README.md +++ b/README.md @@ -404,32 +404,32 @@ syntax: 1. Create a folder with syntax definition files: -```bash -mkdir -p "$(bat --config-dir)/syntaxes" -cd "$(bat --config-dir)/syntaxes" + ```bash + mkdir -p "$(bat --config-dir)/syntaxes" + cd "$(bat --config-dir)/syntaxes" -# Put new '.sublime-syntax' language definition files -# in this folder (or its subdirectories), for example: -git clone https://github.com/tellnobody1/sublime-purescript-syntax -``` + # Put new '.sublime-syntax' language definition files + # in this folder (or its subdirectories), for example: + git clone https://github.com/tellnobody1/sublime-purescript-syntax + ``` 2. Now use the following command to parse these files into a binary cache: -```bash -bat cache --build -``` + ```bash + bat cache --build + ``` 3. Finally, use `bat --list-languages` to check if the new languages are available. -If you ever want to go back to the default settings, call: + If you ever want to go back to the default settings, call: -```bash -bat cache --clear -``` + ```bash + bat cache --clear + ``` 4. If you think that a specific syntax should be included in `bat` by default, please - consider opening a "syntax request" ticket after reading the policies and - instructions [here](doc/assets.md): [Open Syntax Request](https://github.com/sharkdp/bat/issues/new?labels=syntax-request&template=syntax_request.md). + consider opening a "syntax request" ticket after reading the policies and + instructions [here](doc/assets.md): [Open Syntax Request](https://github.com/sharkdp/bat/issues/new?labels=syntax-request&template=syntax_request.md). ### Adding new themes From 4d6b2fec130331507f872b3683f8b2c8d3340dd5 Mon Sep 17 00:00:00 2001 From: sharkdp Date: Wed, 14 Oct 2020 08:12:50 +0200 Subject: [PATCH 071/243] Add PureScript syntax test --- .../highlighted/PureScript/test.purs | 89 +++++++++++++++++++ .../syntax-tests/source/PureScript/test.purs | 89 +++++++++++++++++++ 2 files changed, 178 insertions(+) create mode 100644 tests/syntax-tests/highlighted/PureScript/test.purs create mode 100644 tests/syntax-tests/source/PureScript/test.purs diff --git a/tests/syntax-tests/highlighted/PureScript/test.purs b/tests/syntax-tests/highlighted/PureScript/test.purs new file mode 100644 index 00000000..d59b29b8 --- /dev/null +++ b/tests/syntax-tests/highlighted/PureScript/test.purs @@ -0,0 +1,89 @@ +-- | This module defines a datatype `Pair` together with a few useful instances +-- | and helper functions. Note that this is not just `Tuple a a` but rather a +-- | list with exactly two elements. Specifically, the `Functor` instance maps +-- | over both values (in contrast to the `Functor` instance for `Tuple a`). +module Data.Pair + ( Pair(..) + , (~) + , fst + , snd + , curry + , uncurry + , swap + ) where + +import Prelude + +import Data.Foldable (class Foldable) +import Data.Traversable (class Traversable) +import Data.Distributive (class Distributive) + +import Test.QuickCheck.Arbitrary (class Arbitrary, arbitrary) + +-- | A pair simply consists of two values of the same type. +data Pair a = Pair a a + +infixl 6 Pair as ~ + +-- | Returns the first component of a pair. +fst ∷ ∀ a. Pair a → a +fst (x ~ _) = x + +-- | Returns the second component of a pair. +snd ∷ ∀ a. Pair a → a +snd (_ ~ y) = y + +-- | Turn a function that expects a pair into a function of two arguments. +curry ∷ ∀ a b. (Pair a → b) → a → a → b +curry f x y = f (x ~ y) + +-- | Turn a function of two arguments into a function that expects a pair. +uncurry ∷ ∀ a b. (a → a → b) → Pair a → b +uncurry f (x ~ y) = f x y + +-- | Exchange the two components of the pair +swap ∷ ∀ a. Pair a → Pair a +swap (x ~ y) = y ~ x + +derive instance eqPair ∷ Eq a ⇒ Eq (Pair a) + +derive instance ordPair ∷ Ord a ⇒ Ord (Pair a) + +instance showPair ∷ Show a ⇒ Show (Pair a) where + show (x ~ y) = "(" <> show x <> " ~ " <> show y <> ")" + +instance functorPair ∷ Functor Pair where + map f (x ~ y) = f x ~ f y + +instance applyPair ∷ Apply Pair where + apply (f ~ g) (x ~ y) = f x ~ g y + +instance applicativePair ∷ Applicative Pair where + pure x = x ~ x + +instance bindPair ∷ Bind Pair where + bind (x ~ y) f = fst (f x) ~ snd (f y) + +instance monadPair ∷ Monad Pair + +instance semigroupPair ∷ Semigroup a ⇒ Semigroup (Pair a) where + append (x1 ~ y1) (x2 ~ y2) = (x1 <> x2) ~ (y1 <> y2) + +instance monoidPair ∷ Monoid a ⇒ Monoid (Pair a) where + mempty = mempty ~ mempty + +instance foldablePair ∷ Foldable Pair where + foldr f z (Pair x y) = x `f` (y `f` z) + foldl f z (Pair x y) = (z `f` x) `f` y + foldMap f (Pair x y) = f x <> f y + +instance traversablePair ∷ Traversable Pair where + traverse f (Pair x y) = Pair <$> f x <*> f y + sequence (Pair mx my) = Pair <$> mx <*> my + +instance distributivePair ∷ Distributive Pair where + distribute xs = map fst xs ~ map snd xs + collect f xs = map (fst <<< f) xs ~ map (snd <<< f) xs + +instance arbitraryPair ∷ Arbitrary a ⇒ Arbitrary (Pair a) where + arbitrary = Pair <$> arbitrary <*> arbitrary diff --git a/tests/syntax-tests/source/PureScript/test.purs b/tests/syntax-tests/source/PureScript/test.purs new file mode 100644 index 00000000..35da2b62 --- /dev/null +++ b/tests/syntax-tests/source/PureScript/test.purs @@ -0,0 +1,89 @@ +-- | This module defines a datatype `Pair` together with a few useful instances +-- | and helper functions. Note that this is not just `Tuple a a` but rather a +-- | list with exactly two elements. Specifically, the `Functor` instance maps +-- | over both values (in contrast to the `Functor` instance for `Tuple a`). +module Data.Pair + ( Pair(..) + , (~) + , fst + , snd + , curry + , uncurry + , swap + ) where + +import Prelude + +import Data.Foldable (class Foldable) +import Data.Traversable (class Traversable) +import Data.Distributive (class Distributive) + +import Test.QuickCheck.Arbitrary (class Arbitrary, arbitrary) + +-- | A pair simply consists of two values of the same type. +data Pair a = Pair a a + +infixl 6 Pair as ~ + +-- | Returns the first component of a pair. +fst ∷ ∀ a. Pair a → a +fst (x ~ _) = x + +-- | Returns the second component of a pair. +snd ∷ ∀ a. Pair a → a +snd (_ ~ y) = y + +-- | Turn a function that expects a pair into a function of two arguments. +curry ∷ ∀ a b. (Pair a → b) → a → a → b +curry f x y = f (x ~ y) + +-- | Turn a function of two arguments into a function that expects a pair. +uncurry ∷ ∀ a b. (a → a → b) → Pair a → b +uncurry f (x ~ y) = f x y + +-- | Exchange the two components of the pair +swap ∷ ∀ a. Pair a → Pair a +swap (x ~ y) = y ~ x + +derive instance eqPair ∷ Eq a ⇒ Eq (Pair a) + +derive instance ordPair ∷ Ord a ⇒ Ord (Pair a) + +instance showPair ∷ Show a ⇒ Show (Pair a) where + show (x ~ y) = "(" <> show x <> " ~ " <> show y <> ")" + +instance functorPair ∷ Functor Pair where + map f (x ~ y) = f x ~ f y + +instance applyPair ∷ Apply Pair where + apply (f ~ g) (x ~ y) = f x ~ g y + +instance applicativePair ∷ Applicative Pair where + pure x = x ~ x + +instance bindPair ∷ Bind Pair where + bind (x ~ y) f = fst (f x) ~ snd (f y) + +instance monadPair ∷ Monad Pair + +instance semigroupPair ∷ Semigroup a ⇒ Semigroup (Pair a) where + append (x1 ~ y1) (x2 ~ y2) = (x1 <> x2) ~ (y1 <> y2) + +instance monoidPair ∷ Monoid a ⇒ Monoid (Pair a) where + mempty = mempty ~ mempty + +instance foldablePair ∷ Foldable Pair where + foldr f z (Pair x y) = x `f` (y `f` z) + foldl f z (Pair x y) = (z `f` x) `f` y + foldMap f (Pair x y) = f x <> f y + +instance traversablePair ∷ Traversable Pair where + traverse f (Pair x y) = Pair <$> f x <*> f y + sequence (Pair mx my) = Pair <$> mx <*> my + +instance distributivePair ∷ Distributive Pair where + distribute xs = map fst xs ~ map snd xs + collect f xs = map (fst <<< f) xs ~ map (snd <<< f) xs + +instance arbitraryPair ∷ Arbitrary a ⇒ Arbitrary (Pair a) where + arbitrary = Pair <$> arbitrary <*> arbitrary From 6872a4dd7f972721fe9b9698ca9fc5612b197890 Mon Sep 17 00:00:00 2001 From: Keith Hall Date: Thu, 15 Oct 2020 09:10:29 +0300 Subject: [PATCH 072/243] Fix small grammar mistake/typo in the readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e5cfc0f9..b2f7e74f 100644 --- a/README.md +++ b/README.md @@ -336,7 +336,7 @@ higher. You can then use `cargo` to build everything: cargo install --locked bat ``` -Note that addition files like the man page or shell completion +Note that additional files like the man page or shell completion files can not be installed in this way. They will be generated by `cargo` and should be available in the cargo target folder (under `build`). ## Customization From b83716f0ebc211924dbb11bcabcbba88373c9085 Mon Sep 17 00:00:00 2001 From: Celeo Date: Thu, 15 Oct 2020 14:54:13 -0700 Subject: [PATCH 073/243] feat: add Nim syntax test file --- tests/syntax-tests/highlighted/nim/main.nim | 41 +++++++++++++++++++++ tests/syntax-tests/source/nim/main.nim | 41 +++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 tests/syntax-tests/highlighted/nim/main.nim create mode 100644 tests/syntax-tests/source/nim/main.nim diff --git a/tests/syntax-tests/highlighted/nim/main.nim b/tests/syntax-tests/highlighted/nim/main.nim new file mode 100644 index 00000000..044c2590 --- /dev/null +++ b/tests/syntax-tests/highlighted/nim/main.nim @@ -0,0 +1,41 @@ +import json + +const + message = "hello world" + multiLine = """ + foo + bar + """ + numbers = @[1, 2, 3] + +type Options = enum + A, + B, + C + +## Top-level comment +type + SomeStruct* = ref object + value*: string + +proc someFunc*(): string = + ## Function docs + ## + ## More docs + result = message + +proc someOtherFunc(startingValue: int): (string, int) = + var num = startingValue + num += 1 + if num > 10 * 10 * 10: + echo "Encountered an error" + raise newException(ValueError, "Value was over 1000") + ("Fizz", num) + +proc `+=`(a: var SomeStruct, b: SomeStruct): string = + a.value.add(b.value) + return a.value + +echo someFunc() +echo(someOtherFunc(123)) +discard someFunc() diff --git a/tests/syntax-tests/source/nim/main.nim b/tests/syntax-tests/source/nim/main.nim new file mode 100644 index 00000000..5fa7a598 --- /dev/null +++ b/tests/syntax-tests/source/nim/main.nim @@ -0,0 +1,41 @@ +import json + +const + message = "hello world" + multiLine = """ + foo + bar + """ + numbers = @[1, 2, 3] + +type Options = enum + A, + B, + C + +## Top-level comment +type + SomeStruct* = ref object + value*: string + +proc someFunc*(): string = + ## Function docs + ## + ## More docs + result = message + +proc someOtherFunc(startingValue: int): (string, int) = + var num = startingValue + num += 1 + if num > 10 * 10 * 10: + echo "Encountered an error" + raise newException(ValueError, "Value was over 1000") + ("Fizz", num) + +proc `+=`(a: var SomeStruct, b: SomeStruct): string = + a.value.add(b.value) + return a.value + +echo someFunc() +echo(someOtherFunc(123)) +discard someFunc() From 4b2b419400834ba82aae957b73f273e68eb4a669 Mon Sep 17 00:00:00 2001 From: Benjamin Sinkula Date: Thu, 15 Oct 2020 16:30:16 -0500 Subject: [PATCH 074/243] Add Common Lisp syntax highlighting test files --- .../syntax-tests/highlighted/Lisp/utils.lisp | 80 +++++++++++++++++++ tests/syntax-tests/source/Lisp/LICENSE.md | 24 ++++++ tests/syntax-tests/source/Lisp/utils.lisp | 80 +++++++++++++++++++ 3 files changed, 184 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Lisp/utils.lisp create mode 100644 tests/syntax-tests/source/Lisp/LICENSE.md create mode 100644 tests/syntax-tests/source/Lisp/utils.lisp diff --git a/tests/syntax-tests/highlighted/Lisp/utils.lisp b/tests/syntax-tests/highlighted/Lisp/utils.lisp new file mode 100644 index 00000000..ef61a820 --- /dev/null +++ b/tests/syntax-tests/highlighted/Lisp/utils.lisp @@ -0,0 +1,80 @@ +(cl:defpackage :chillax.utils + (:use :cl :alexandria) + (:export + :fun :mkhash :hashget :strcat :dequote :at)) +(in-package :chillax.utils) + +;;; Functions +(defmacro fun (&body body) + "This macro puts the FUN back in FUNCTION." + `(lambda (&optional _) (declare (ignorable _)) ,@body)) + +;;; Hash tables +(defun mkhash (&rest keys-and-values &aux (table (make-hash-table :test #'equal))) + "Convenience function for `literal' hash table definition." + (loop for (key val) on keys-and-values by #'cddr do (setf (gethash key table) val) + finally (return table))) + +(defun hashget (hash &rest keys) + "Convenience function for recursively accessing hash tables." + (reduce (lambda (h k) (gethash k h)) keys :initial-value hash)) + +(define-compiler-macro hashget (hash &rest keys) + (if (null keys) hash + (let ((hash-sym (make-symbol "HASH")) + (key-syms (loop for i below (length keys) + collect (make-symbol (format nil "~:@(~:R~)-KEY" i))))) + `(let ((,hash-sym ,hash) + ,@(loop for key in keys for sym in key-syms + collect `(,sym ,key))) + ,(reduce (lambda (hash key) `(gethash ,key ,hash)) + key-syms :initial-value hash-sym))))) + +(defun (setf hashget) (new-value hash key &rest more-keys) + "Uses the last key given to hashget to insert NEW-VALUE into the hash table +returned by the second-to-last key. +tl;dr: DWIM SETF function for HASHGET." + (if more-keys + (setf (gethash (car (last more-keys)) + (apply #'hashget hash key (butlast more-keys))) + new-value) + (setf (gethash key hash) new-value))) + +;;; Strings +(defun strcat (string &rest more-strings) + (apply #'concatenate 'string string more-strings)) + +(defun dequote (string) + (let ((len (length string))) + (if (and (> len 1) (starts-with #\" string) (ends-with #\" string)) + (subseq string 1 (- len 1)) + string))) + +;;; +;;; At +;;; +(defgeneric at (doc &rest keys)) +(defgeneric (setf at) (new-value doc key &rest more-keys)) + +(defmethod at ((doc hash-table) &rest keys) + (apply #'hashget doc keys)) +(defmethod (setf at) (new-value (doc hash-table) key &rest more-keys) + (apply #'(setf hashget) new-value doc key more-keys)) + +(defmethod at ((doc list) &rest keys) + (reduce (lambda (alist key) + (cdr (assoc key alist :test #'equal))) + keys :initial-value doc)) +(defmethod (setf at) (new-value (doc list) key &rest more-keys) + (if more-keys + (setf (cdr (assoc (car (last more-keys)) + (apply #'at doc key (butlast more-keys)) + :test #'equal)) + new-value) + (setf (cdr (assoc key doc :test #'equal)) new-value))) + +;; A playful alias. +(defun @ (doc &rest keys) + (apply #'at doc keys)) +(defun (setf @) (new-value doc key &rest more-keys) + (apply #'(setf at) new-value doc key more-keys)) diff --git a/tests/syntax-tests/source/Lisp/LICENSE.md b/tests/syntax-tests/source/Lisp/LICENSE.md new file mode 100644 index 00000000..9da63d32 --- /dev/null +++ b/tests/syntax-tests/source/Lisp/LICENSE.md @@ -0,0 +1,24 @@ +The `utils.lisp` file has been added from https://github.com/zkat/chillax under the following license: + +Copyright © 2009-2010 Kat Marchán + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, +modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + diff --git a/tests/syntax-tests/source/Lisp/utils.lisp b/tests/syntax-tests/source/Lisp/utils.lisp new file mode 100644 index 00000000..91a76ae5 --- /dev/null +++ b/tests/syntax-tests/source/Lisp/utils.lisp @@ -0,0 +1,80 @@ +(cl:defpackage :chillax.utils + (:use :cl :alexandria) + (:export + :fun :mkhash :hashget :strcat :dequote :at)) +(in-package :chillax.utils) + +;;; Functions +(defmacro fun (&body body) + "This macro puts the FUN back in FUNCTION." + `(lambda (&optional _) (declare (ignorable _)) ,@body)) + +;;; Hash tables +(defun mkhash (&rest keys-and-values &aux (table (make-hash-table :test #'equal))) + "Convenience function for `literal' hash table definition." + (loop for (key val) on keys-and-values by #'cddr do (setf (gethash key table) val) + finally (return table))) + +(defun hashget (hash &rest keys) + "Convenience function for recursively accessing hash tables." + (reduce (lambda (h k) (gethash k h)) keys :initial-value hash)) + +(define-compiler-macro hashget (hash &rest keys) + (if (null keys) hash + (let ((hash-sym (make-symbol "HASH")) + (key-syms (loop for i below (length keys) + collect (make-symbol (format nil "~:@(~:R~)-KEY" i))))) + `(let ((,hash-sym ,hash) + ,@(loop for key in keys for sym in key-syms + collect `(,sym ,key))) + ,(reduce (lambda (hash key) `(gethash ,key ,hash)) + key-syms :initial-value hash-sym))))) + +(defun (setf hashget) (new-value hash key &rest more-keys) + "Uses the last key given to hashget to insert NEW-VALUE into the hash table +returned by the second-to-last key. +tl;dr: DWIM SETF function for HASHGET." + (if more-keys + (setf (gethash (car (last more-keys)) + (apply #'hashget hash key (butlast more-keys))) + new-value) + (setf (gethash key hash) new-value))) + +;;; Strings +(defun strcat (string &rest more-strings) + (apply #'concatenate 'string string more-strings)) + +(defun dequote (string) + (let ((len (length string))) + (if (and (> len 1) (starts-with #\" string) (ends-with #\" string)) + (subseq string 1 (- len 1)) + string))) + +;;; +;;; At +;;; +(defgeneric at (doc &rest keys)) +(defgeneric (setf at) (new-value doc key &rest more-keys)) + +(defmethod at ((doc hash-table) &rest keys) + (apply #'hashget doc keys)) +(defmethod (setf at) (new-value (doc hash-table) key &rest more-keys) + (apply #'(setf hashget) new-value doc key more-keys)) + +(defmethod at ((doc list) &rest keys) + (reduce (lambda (alist key) + (cdr (assoc key alist :test #'equal))) + keys :initial-value doc)) +(defmethod (setf at) (new-value (doc list) key &rest more-keys) + (if more-keys + (setf (cdr (assoc (car (last more-keys)) + (apply #'at doc key (butlast more-keys)) + :test #'equal)) + new-value) + (setf (cdr (assoc key doc :test #'equal)) new-value))) + +;; A playful alias. +(defun @ (doc &rest keys) + (apply #'at doc keys)) +(defun (setf @) (new-value doc key &rest more-keys) + (apply #'(setf at) new-value doc key more-keys)) From 57ad85814b89bdcb3ee8114b7eb45460156d9914 Mon Sep 17 00:00:00 2001 From: Matthieu Vion Date: Fri, 16 Oct 2020 11:25:15 +0200 Subject: [PATCH 075/243] Added Makefile to syntax tests Make progress in #1213 --- .../highlighted/Makefile/Makefile | 195 +++++ tests/syntax-tests/source/Makefile/LICENSE.md | 677 ++++++++++++++++++ tests/syntax-tests/source/Makefile/Makefile | 195 +++++ 3 files changed, 1067 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Makefile/Makefile create mode 100644 tests/syntax-tests/source/Makefile/LICENSE.md create mode 100644 tests/syntax-tests/source/Makefile/Makefile diff --git a/tests/syntax-tests/highlighted/Makefile/Makefile b/tests/syntax-tests/highlighted/Makefile/Makefile new file mode 100644 index 00000000..5c4e344a --- /dev/null +++ b/tests/syntax-tests/highlighted/Makefile/Makefile @@ -0,0 +1,195 @@ +#!/usr/bin/make -f +# Generated automatically from Makefile.in by configure. +# Un*x Makefile for GNU tar program. +# Copyright (C) 1991 Free Software Foundation, Inc. + +# This program is free software; you can redistribute +# it and/or modify it under the terms of the GNU +# General Public License … +… +… + +SHELL = /bin/sh + +#### Start of system configuration section. #### + +srcdir = . + +# If you use gcc, you should either run the +# fixincludes script that comes with it or else use +# gcc with the -traditional option. Otherwise ioctl +# calls will be compiled incorrectly on some systems. +CC = gcc -O +YACC = bison -y +INSTALL = /usr/local/bin/install -c +INSTALLDATA = /usr/local/bin/install -c -m 644 + +# Things you might add to DEFS: +# -DSTDC_HEADERS If you have ANSI C headers and +# libraries. +# -DPOSIX If you have POSIX.1 headers and +# libraries. +# -DBSD42 If you have sys/dir.h (unless +# you use -DPOSIX), sys/file.h, +# and st_blocks in `struct stat'. +# -DUSG If you have System V/ANSI C +# string and memory functions +# and headers, sys/sysmacros.h, +# fcntl.h, getcwd, no valloc, +# and ndir.h (unless +# you use -DDIRENT). +# -DNO_MEMORY_H If USG or STDC_HEADERS but do not +# include memory.h. +# -DDIRENT If USG and you have dirent.h +# instead of ndir.h. +# -DSIGTYPE=int If your signal handlers +# return int, not void. +# -DNO_MTIO If you lack sys/mtio.h +# (magtape ioctls). +# -DNO_REMOTE If you do not have a remote shell +# or rexec. +# -DUSE_REXEC To use rexec for remote tape +# operations instead of +# forking rsh or remsh. +# -DVPRINTF_MISSING If you lack vprintf function +# (but have _doprnt). +# -DDOPRNT_MISSING If you lack _doprnt function. +# Also need to define +# -DVPRINTF_MISSING. +# -DFTIME_MISSING If you lack ftime system call. +# -DSTRSTR_MISSING If you lack strstr function. +# -DVALLOC_MISSING If you lack valloc function. +# -DMKDIR_MISSING If you lack mkdir and +# rmdir system calls. +# -DRENAME_MISSING If you lack rename system call. +# -DFTRUNCATE_MISSING If you lack ftruncate +# system call. +# -DV7 On Version 7 Unix (not +# tested in a long time). +# -DEMUL_OPEN3 If you lack a 3-argument version +# of open, and want to emulate it +# with system calls you do have. +# -DNO_OPEN3 If you lack the 3-argument open +# and want to disable the tar -k +# option instead of emulating open. +# -DXENIX If you have sys/inode.h +# and need it 94 to be included. + +DEFS = -DSIGTYPE=int -DDIRENT -DSTRSTR_MISSING \ + -DVPRINTF_MISSING -DBSD42 +# Set this to rtapelib.o unless you defined NO_REMOTE, +# in which case make it empty. +RTAPELIB = rtapelib.o +LIBS = +DEF_AR_FILE = /dev/rmt8 +DEFBLOCKING = 20 + +CDEBUG = -g +CFLAGS = $(CDEBUG) -I. -I$(srcdir) $(DEFS) \ + -DDEF_AR_FILE=\"$(DEF_AR_FILE)\" \ + -DDEFBLOCKING=$(DEFBLOCKING) +LDFLAGS = -g + +prefix = /usr/local +# Prefix for each installed program, +# normally empty or `g'. +binprefix = + +# The directory to install tar in. +bindir = $(prefix)/bin + +# The directory to install the info files in. +infodir = $(prefix)/info + +#### End of system configuration section. #### + +SRCS_C = tar.c create.c extract.c buffer.c \ + getoldopt.c update.c gnu.c mangle.c \ + version.c list.c names.c diffarch.c \ + port.c wildmat.c getopt.c getopt1.c \ + regex.c +SRCS_Y = getdate.y +SRCS = $(SRCS_C) $(SRCS_Y) +OBJS = $(SRCS_C:.c=.o) $(SRCS_Y:.y=.o) $(RTAPELIB) +AUX = README COPYING ChangeLog Makefile.in \ + makefile.pc configure configure.in \ + tar.texinfo tar.info* texinfo.tex \ + tar.h port.h open3.h getopt.h regex.h \ + rmt.h rmt.c rtapelib.c alloca.c \ + msd_dir.h msd_dir.c tcexparg.c \ + level-0 level-1 backup-specs testpad.c + +.PHONY: all +all: tar rmt tar.info + +tar: $(OBJS) + $(CC) $(LDFLAGS) -o $@ $(OBJS) $(LIBS) + +rmt: rmt.c + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ rmt.c + +tar.info: tar.texinfo + makeinfo tar.texinfo + +.PHONY: install +install: all + $(INSTALL) tar $(bindir)/$(binprefix)tar + -test ! -f rmt || $(INSTALL) rmt /etc/rmt + $(INSTALLDATA) $(srcdir)/tar.info* $(infodir) + +$(OBJS): tar.h port.h testpad.h +regex.o buffer.o tar.o: regex.h +# getdate.y has 8 shift/reduce conflicts. + +testpad.h: testpad + ./testpad + +testpad: testpad.o + $(CC) -o $@ testpad.o + +TAGS: $(SRCS) + etags $(SRCS) + +.PHONY: clean +clean: + rm -f *.o tar rmt testpad testpad.h core + +.PHONY: distclean +distclean: clean + rm -f TAGS Makefile config.status + +.PHONY: realclean +realclean: distclean + rm -f tar.info* + +.PHONY: shar +shar: $(SRCS) $(AUX) + shar $(SRCS) $(AUX) | compress \ + > tar-`sed -e '/version_string/!d' \ + -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \ + -e q + version.c`.shar.Z + +.PHONY: dist +dist: $(SRCS) $(AUX) + echo tar-`sed \ + -e '/version_string/!d' \ + -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \ + -e q + version.c` > .fname + -rm -rf `cat .fname` + mkdir `cat .fname` + ln $(SRCS) $(AUX) `cat .fname` + tar chZf `cat .fname`.tar.Z `cat .fname` + -rm -rf `cat .fname` .fname + +tar.zoo: $(SRCS) $(AUX) + -rm -rf tmp.dir + -mkdir tmp.dir + -rm tar.zoo + for X in $(SRCS) $(AUX) ; do \ + echo $$X ; \ + sed 's/$$/^M/' $$X \ + > tmp.dir/$$X ; done + cd tmp.dir ; zoo aM ../tar.zoo * + -rm -rf tmp.dir diff --git a/tests/syntax-tests/source/Makefile/LICENSE.md b/tests/syntax-tests/source/Makefile/LICENSE.md new file mode 100644 index 00000000..a1244286 --- /dev/null +++ b/tests/syntax-tests/source/Makefile/LICENSE.md @@ -0,0 +1,677 @@ +The `Makefile` file has been added from GNU Tar (https://savannah.gnu.org/projects/tar/) under the following license: + + +GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/tests/syntax-tests/source/Makefile/Makefile b/tests/syntax-tests/source/Makefile/Makefile new file mode 100644 index 00000000..085d4f83 --- /dev/null +++ b/tests/syntax-tests/source/Makefile/Makefile @@ -0,0 +1,195 @@ +#!/usr/bin/make -f +# Generated automatically from Makefile.in by configure. +# Un*x Makefile for GNU tar program. +# Copyright (C) 1991 Free Software Foundation, Inc. + +# This program is free software; you can redistribute +# it and/or modify it under the terms of the GNU +# General Public License … +… +… + +SHELL = /bin/sh + +#### Start of system configuration section. #### + +srcdir = . + +# If you use gcc, you should either run the +# fixincludes script that comes with it or else use +# gcc with the -traditional option. Otherwise ioctl +# calls will be compiled incorrectly on some systems. +CC = gcc -O +YACC = bison -y +INSTALL = /usr/local/bin/install -c +INSTALLDATA = /usr/local/bin/install -c -m 644 + +# Things you might add to DEFS: +# -DSTDC_HEADERS If you have ANSI C headers and +# libraries. +# -DPOSIX If you have POSIX.1 headers and +# libraries. +# -DBSD42 If you have sys/dir.h (unless +# you use -DPOSIX), sys/file.h, +# and st_blocks in `struct stat'. +# -DUSG If you have System V/ANSI C +# string and memory functions +# and headers, sys/sysmacros.h, +# fcntl.h, getcwd, no valloc, +# and ndir.h (unless +# you use -DDIRENT). +# -DNO_MEMORY_H If USG or STDC_HEADERS but do not +# include memory.h. +# -DDIRENT If USG and you have dirent.h +# instead of ndir.h. +# -DSIGTYPE=int If your signal handlers +# return int, not void. +# -DNO_MTIO If you lack sys/mtio.h +# (magtape ioctls). +# -DNO_REMOTE If you do not have a remote shell +# or rexec. +# -DUSE_REXEC To use rexec for remote tape +# operations instead of +# forking rsh or remsh. +# -DVPRINTF_MISSING If you lack vprintf function +# (but have _doprnt). +# -DDOPRNT_MISSING If you lack _doprnt function. +# Also need to define +# -DVPRINTF_MISSING. +# -DFTIME_MISSING If you lack ftime system call. +# -DSTRSTR_MISSING If you lack strstr function. +# -DVALLOC_MISSING If you lack valloc function. +# -DMKDIR_MISSING If you lack mkdir and +# rmdir system calls. +# -DRENAME_MISSING If you lack rename system call. +# -DFTRUNCATE_MISSING If you lack ftruncate +# system call. +# -DV7 On Version 7 Unix (not +# tested in a long time). +# -DEMUL_OPEN3 If you lack a 3-argument version +# of open, and want to emulate it +# with system calls you do have. +# -DNO_OPEN3 If you lack the 3-argument open +# and want to disable the tar -k +# option instead of emulating open. +# -DXENIX If you have sys/inode.h +# and need it 94 to be included. + +DEFS = -DSIGTYPE=int -DDIRENT -DSTRSTR_MISSING \ + -DVPRINTF_MISSING -DBSD42 +# Set this to rtapelib.o unless you defined NO_REMOTE, +# in which case make it empty. +RTAPELIB = rtapelib.o +LIBS = +DEF_AR_FILE = /dev/rmt8 +DEFBLOCKING = 20 + +CDEBUG = -g +CFLAGS = $(CDEBUG) -I. -I$(srcdir) $(DEFS) \ + -DDEF_AR_FILE=\"$(DEF_AR_FILE)\" \ + -DDEFBLOCKING=$(DEFBLOCKING) +LDFLAGS = -g + +prefix = /usr/local +# Prefix for each installed program, +# normally empty or `g'. +binprefix = + +# The directory to install tar in. +bindir = $(prefix)/bin + +# The directory to install the info files in. +infodir = $(prefix)/info + +#### End of system configuration section. #### + +SRCS_C = tar.c create.c extract.c buffer.c \ + getoldopt.c update.c gnu.c mangle.c \ + version.c list.c names.c diffarch.c \ + port.c wildmat.c getopt.c getopt1.c \ + regex.c +SRCS_Y = getdate.y +SRCS = $(SRCS_C) $(SRCS_Y) +OBJS = $(SRCS_C:.c=.o) $(SRCS_Y:.y=.o) $(RTAPELIB) +AUX = README COPYING ChangeLog Makefile.in \ + makefile.pc configure configure.in \ + tar.texinfo tar.info* texinfo.tex \ + tar.h port.h open3.h getopt.h regex.h \ + rmt.h rmt.c rtapelib.c alloca.c \ + msd_dir.h msd_dir.c tcexparg.c \ + level-0 level-1 backup-specs testpad.c + +.PHONY: all +all: tar rmt tar.info + +tar: $(OBJS) + $(CC) $(LDFLAGS) -o $@ $(OBJS) $(LIBS) + +rmt: rmt.c + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ rmt.c + +tar.info: tar.texinfo + makeinfo tar.texinfo + +.PHONY: install +install: all + $(INSTALL) tar $(bindir)/$(binprefix)tar + -test ! -f rmt || $(INSTALL) rmt /etc/rmt + $(INSTALLDATA) $(srcdir)/tar.info* $(infodir) + +$(OBJS): tar.h port.h testpad.h +regex.o buffer.o tar.o: regex.h +# getdate.y has 8 shift/reduce conflicts. + +testpad.h: testpad + ./testpad + +testpad: testpad.o + $(CC) -o $@ testpad.o + +TAGS: $(SRCS) + etags $(SRCS) + +.PHONY: clean +clean: + rm -f *.o tar rmt testpad testpad.h core + +.PHONY: distclean +distclean: clean + rm -f TAGS Makefile config.status + +.PHONY: realclean +realclean: distclean + rm -f tar.info* + +.PHONY: shar +shar: $(SRCS) $(AUX) + shar $(SRCS) $(AUX) | compress \ + > tar-`sed -e '/version_string/!d' \ + -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \ + -e q + version.c`.shar.Z + +.PHONY: dist +dist: $(SRCS) $(AUX) + echo tar-`sed \ + -e '/version_string/!d' \ + -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \ + -e q + version.c` > .fname + -rm -rf `cat .fname` + mkdir `cat .fname` + ln $(SRCS) $(AUX) `cat .fname` + tar chZf `cat .fname`.tar.Z `cat .fname` + -rm -rf `cat .fname` .fname + +tar.zoo: $(SRCS) $(AUX) + -rm -rf tmp.dir + -mkdir tmp.dir + -rm tar.zoo + for X in $(SRCS) $(AUX) ; do \ + echo $$X ; \ + sed 's/$$/^M/' $$X \ + > tmp.dir/$$X ; done + cd tmp.dir ; zoo aM ../tar.zoo * + -rm -rf tmp.dir \ No newline at end of file From 7c7eebbe8368e9ac605113af026a9f5eaf74090e Mon Sep 17 00:00:00 2001 From: Matthieu Vion Date: Fri, 16 Oct 2020 11:52:15 +0200 Subject: [PATCH 076/243] Changed Makefile syntax test source Now using Makefile from the Redis project --- .../highlighted/Makefile/Makefile | 518 ++++++++----- tests/syntax-tests/source/Makefile/LICENSE.md | 681 +----------------- tests/syntax-tests/source/Makefile/Makefile | 518 ++++++++----- 3 files changed, 716 insertions(+), 1001 deletions(-) diff --git a/tests/syntax-tests/highlighted/Makefile/Makefile b/tests/syntax-tests/highlighted/Makefile/Makefile index 5c4e344a..dc4d36fc 100644 --- a/tests/syntax-tests/highlighted/Makefile/Makefile +++ b/tests/syntax-tests/highlighted/Makefile/Makefile @@ -1,195 +1,385 @@ -#!/usr/bin/make -f -# Generated automatically from Makefile.in by configure. -# Un*x Makefile for GNU tar program. -# Copyright (C) 1991 Free Software Foundation, Inc. +# Redis Makefile +# Copyright (C) 2009 Salvatore Sanfilippo  +# This file is released under the BSD license, see the COPYING file +# +# The Makefile composes the final FINAL_CFLAGS and FINAL_LDFLAGS using +# what is needed for Redis plus the standard CFLAGS and LDFLAGS passed. +# However when building the dependencies (Jemalloc, Lua, Hiredis, ...) +# CFLAGS and LDFLAGS are propagated to the dependencies, so to pass +# flags only to be used when compiling / linking Redis itself REDIS_CFLAGS +# and REDIS_LDFLAGS are used instead (this is the case of 'make gcov'). +# +# Dependencies are stored in the Makefile.dep file. To rebuild this file +# Just use 'make dep', but this is only needed by developers. -# This program is free software; you can redistribute -# it and/or modify it under the terms of the GNU -# General Public License … -… -… +release_hdr := $(shell sh -c './mkreleasehdr.sh') +uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') +uname_M := $(shell sh -c 'uname -m 2>/dev/null || echo not') +OPTIMIZATION?=-O2 +DEPENDENCY_TARGETS=hiredis linenoise lua +NODEPS:=clean distclean -SHELL = /bin/sh +# Default settings +STD=-std=c11 -pedantic -DREDIS_STATIC='' +ifneq (,$(findstring clang,$(CC))) +ifneq (,$(findstring FreeBSD,$(uname_S))) + STD+=-Wno-c11-extensions +endif +endif +WARN=-Wall -W -Wno-missing-field-initializers +OPT=$(OPTIMIZATION) -#### Start of system configuration section. #### +PREFIX?=/usr/local +INSTALL_BIN=$(PREFIX)/bin +INSTALL=install +PKG_CONFIG?=pkg-config -srcdir = . +# Default allocator defaults to Jemalloc if it's not an ARM +MALLOC=libc +ifneq ($(uname_M),armv6l) +ifneq ($(uname_M),armv7l) +ifeq ($(uname_S),Linux) + MALLOC=jemalloc +endif +endif +endif -# If you use gcc, you should either run the -# fixincludes script that comes with it or else use -# gcc with the -traditional option. Otherwise ioctl -# calls will be compiled incorrectly on some systems. -CC = gcc -O -YACC = bison -y -INSTALL = /usr/local/bin/install -c -INSTALLDATA = /usr/local/bin/install -c -m 644 +# To get ARM stack traces if Redis crashes we need a special C flag. +ifneq (,$(filter aarch64 armv,$(uname_M))) + CFLAGS+=-funwind-tables +else +ifneq (,$(findstring armv,$(uname_M))) + CFLAGS+=-funwind-tables +endif +endif -# Things you might add to DEFS: -# -DSTDC_HEADERS If you have ANSI C headers and -# libraries. -# -DPOSIX If you have POSIX.1 headers and -# libraries. -# -DBSD42 If you have sys/dir.h (unless -# you use -DPOSIX), sys/file.h, -# and st_blocks in `struct stat'. -# -DUSG If you have System V/ANSI C -# string and memory functions -# and headers, sys/sysmacros.h, -# fcntl.h, getcwd, no valloc, -# and ndir.h (unless -# you use -DDIRENT). -# -DNO_MEMORY_H If USG or STDC_HEADERS but do not -# include memory.h. -# -DDIRENT If USG and you have dirent.h -# instead of ndir.h. -# -DSIGTYPE=int If your signal handlers -# return int, not void. -# -DNO_MTIO If you lack sys/mtio.h -# (magtape ioctls). -# -DNO_REMOTE If you do not have a remote shell -# or rexec. -# -DUSE_REXEC To use rexec for remote tape -# operations instead of -# forking rsh or remsh. -# -DVPRINTF_MISSING If you lack vprintf function -# (but have _doprnt). -# -DDOPRNT_MISSING If you lack _doprnt function. -# Also need to define -# -DVPRINTF_MISSING. -# -DFTIME_MISSING If you lack ftime system call. -# -DSTRSTR_MISSING If you lack strstr function. -# -DVALLOC_MISSING If you lack valloc function. -# -DMKDIR_MISSING If you lack mkdir and -# rmdir system calls. -# -DRENAME_MISSING If you lack rename system call. -# -DFTRUNCATE_MISSING If you lack ftruncate -# system call. -# -DV7 On Version 7 Unix (not -# tested in a long time). -# -DEMUL_OPEN3 If you lack a 3-argument version -# of open, and want to emulate it -# with system calls you do have. -# -DNO_OPEN3 If you lack the 3-argument open -# and want to disable the tar -k -# option instead of emulating open. -# -DXENIX If you have sys/inode.h -# and need it 94 to be included. +# Backwards compatibility for selecting an allocator +ifeq ($(USE_TCMALLOC),yes) + MALLOC=tcmalloc +endif -DEFS = -DSIGTYPE=int -DDIRENT -DSTRSTR_MISSING \ - -DVPRINTF_MISSING -DBSD42 -# Set this to rtapelib.o unless you defined NO_REMOTE, -# in which case make it empty. -RTAPELIB = rtapelib.o -LIBS = -DEF_AR_FILE = /dev/rmt8 -DEFBLOCKING = 20 +ifeq ($(USE_TCMALLOC_MINIMAL),yes) + MALLOC=tcmalloc_minimal +endif -CDEBUG = -g -CFLAGS = $(CDEBUG) -I. -I$(srcdir) $(DEFS) \ - -DDEF_AR_FILE=\"$(DEF_AR_FILE)\" \ - -DDEFBLOCKING=$(DEFBLOCKING) -LDFLAGS = -g +ifeq ($(USE_JEMALLOC),yes) + MALLOC=jemalloc +endif -prefix = /usr/local -# Prefix for each installed program, -# normally empty or `g'. -binprefix = +ifeq ($(USE_JEMALLOC),no) + MALLOC=libc +endif -# The directory to install tar in. -bindir = $(prefix)/bin +# Override default settings if possible +-include .make-settings -# The directory to install the info files in. -infodir = $(prefix)/info +FINAL_CFLAGS=$(STD) $(WARN) $(OPT) $(DEBUG) $(CFLAGS) $(REDIS_CFLAGS) +FINAL_LDFLAGS=$(LDFLAGS) $(REDIS_LDFLAGS) $(DEBUG) +FINAL_LIBS=-lm +DEBUG=-g -ggdb -#### End of system configuration section. #### +# Linux ARM needs -latomic at linking time +ifneq (,$(filter aarch64 armv,$(uname_M))) + FINAL_LIBS+=-latomic +else +ifneq (,$(findstring armv,$(uname_M))) + FINAL_LIBS+=-latomic +endif +endif -SRCS_C = tar.c create.c extract.c buffer.c \ - getoldopt.c update.c gnu.c mangle.c \ - version.c list.c names.c diffarch.c \ - port.c wildmat.c getopt.c getopt1.c \ - regex.c -SRCS_Y = getdate.y -SRCS = $(SRCS_C) $(SRCS_Y) -OBJS = $(SRCS_C:.c=.o) $(SRCS_Y:.y=.o) $(RTAPELIB) -AUX = README COPYING ChangeLog Makefile.in \ - makefile.pc configure configure.in \ - tar.texinfo tar.info* texinfo.tex \ - tar.h port.h open3.h getopt.h regex.h \ - rmt.h rmt.c rtapelib.c alloca.c \ - msd_dir.h msd_dir.c tcexparg.c \ - level-0 level-1 backup-specs testpad.c +ifeq ($(uname_S),SunOS) + # SunOS + ifneq ($(@@),32bit) + CFLAGS+= -m64 + LDFLAGS+= -m64 + endif + DEBUG=-g + DEBUG_FLAGS=-g + export CFLAGS LDFLAGS DEBUG DEBUG_FLAGS + INSTALL=cp -pf + FINAL_CFLAGS+= -D__EXTENSIONS__ -D_XPG6 + FINAL_LIBS+= -ldl -lnsl -lsocket -lresolv -lpthread -lrt +else +ifeq ($(uname_S),Darwin) + # Darwin + FINAL_LIBS+= -ldl + OPENSSL_CFLAGS=-I/usr/local/opt/openssl/include + OPENSSL_LDFLAGS=-L/usr/local/opt/openssl/lib +else +ifeq ($(uname_S),AIX) + # AIX + FINAL_LDFLAGS+= -Wl,-bexpall + FINAL_LIBS+=-ldl -pthread -lcrypt -lbsd +else +ifeq ($(uname_S),OpenBSD) + # OpenBSD + FINAL_LIBS+= -lpthread + ifeq ($(USE_BACKTRACE),yes) + FINAL_CFLAGS+= -DUSE_BACKTRACE -I/usr/local/include + FINAL_LDFLAGS+= -L/usr/local/lib + FINAL_LIBS+= -lexecinfo + endif + +else +ifeq ($(uname_S),FreeBSD) + # FreeBSD + FINAL_LIBS+= -lpthread -lexecinfo +else +ifeq ($(uname_S),DragonFly) + # FreeBSD + FINAL_LIBS+= -lpthread -lexecinfo +else +ifeq ($(uname_S),OpenBSD) + # OpenBSD + FINAL_LIBS+= -lpthread -lexecinfo +else +ifeq ($(uname_S),NetBSD) + # NetBSD + FINAL_LIBS+= -lpthread -lexecinfo +else + # All the other OSes (notably Linux) + FINAL_LDFLAGS+= -rdynamic + FINAL_LIBS+=-ldl -pthread -lrt +endif +endif +endif +endif +endif +endif +endif +endif +# Include paths to dependencies +FINAL_CFLAGS+= -I../deps/hiredis -I../deps/linenoise -I../deps/lua/src + +# Determine systemd support and/or build preference (defaulting to auto-detection) +BUILD_WITH_SYSTEMD=no +# If 'USE_SYSTEMD' in the environment is neither "no" nor "yes", try to +# auto-detect libsystemd's presence and link accordingly. +ifneq ($(USE_SYSTEMD),no) + LIBSYSTEMD_PKGCONFIG := $(shell $(PKG_CONFIG) --exists libsystemd && echo $$?) +# If libsystemd cannot be detected, continue building without support for it +# (unless a later check tells us otherwise) +ifeq ($(LIBSYSTEMD_PKGCONFIG),0) + BUILD_WITH_SYSTEMD=yes +endif +endif +ifeq ($(USE_SYSTEMD),yes) +ifneq ($(LIBSYSTEMD_PKGCONFIG),0) +$(error USE_SYSTEMD is set to "$(USE_SYSTEMD)", but $(PKG_CONFIG) cannot find libsystemd) +endif +# Force building with libsystemd + BUILD_WITH_SYSTEMD=yes +endif +ifeq ($(BUILD_WITH_SYSTEMD),yes) + FINAL_LIBS+=$(shell $(PKG_CONFIG) --libs libsystemd) + FINAL_CFLAGS+= -DHAVE_LIBSYSTEMD +endif + +ifeq ($(MALLOC),tcmalloc) + FINAL_CFLAGS+= -DUSE_TCMALLOC + FINAL_LIBS+= -ltcmalloc +endif + +ifeq ($(MALLOC),tcmalloc_minimal) + FINAL_CFLAGS+= -DUSE_TCMALLOC + FINAL_LIBS+= -ltcmalloc_minimal +endif + +ifeq ($(MALLOC),jemalloc) + DEPENDENCY_TARGETS+= jemalloc + FINAL_CFLAGS+= -DUSE_JEMALLOC -I../deps/jemalloc/include + FINAL_LIBS := ../deps/jemalloc/lib/libjemalloc.a $(FINAL_LIBS) +endif + +ifeq ($(BUILD_TLS),yes) + FINAL_CFLAGS+=-DUSE_OPENSSL $(OPENSSL_CFLAGS) + FINAL_LDFLAGS+=$(OPENSSL_LDFLAGS) + LIBSSL_PKGCONFIG := $(shell $(PKG_CONFIG) --exists libssl && echo $$?) +ifeq ($(LIBSSL_PKGCONFIG),0) + LIBSSL_LIBS=$(shell $(PKG_CONFIG) --libs libssl) +else + LIBSSL_LIBS=-lssl +endif + LIBCRYPTO_PKGCONFIG := $(shell $(PKG_CONFIG) --exists libcrypto && echo $$?) +ifeq ($(LIBCRYPTO_PKGCONFIG),0) + LIBCRYPTO_LIBS=$(shell $(PKG_CONFIG) --libs libcrypto) +else + LIBCRYPTO_LIBS=-lcrypto +endif + FINAL_LIBS += ../deps/hiredis/libhiredis_ssl.a $(LIBSSL_LIBS) $(LIBCRYPTO_LIBS) +endif + +REDIS_CC=$(QUIET_CC)$(CC) $(FINAL_CFLAGS) +REDIS_LD=$(QUIET_LINK)$(CC) $(FINAL_LDFLAGS) +REDIS_INSTALL=$(QUIET_INSTALL)$(INSTALL) + +CCCOLOR="\033[34m" +LINKCOLOR="\033[34;1m" +SRCCOLOR="\033[33m" +BINCOLOR="\033[37;1m" +MAKECOLOR="\033[32;1m" +ENDCOLOR="\033[0m" + +ifndef V +QUIET_CC = @printf ' %b %b\n' $(CCCOLOR)CC$(ENDCOLOR) $(SRCCOLOR)$@$(ENDCOLOR) 1>&2; +QUIET_LINK = @printf ' %b %b\n' $(LINKCOLOR)LINK$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; +QUIET_INSTALL = @printf ' %b %b\n' $(LINKCOLOR)INSTALL$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; +endif + +REDIS_SERVER_NAME=redis-server +REDIS_SENTINEL_NAME=redis-sentinel +REDIS_SERVER_OBJ=adlist.o quicklist.o ae.o anet.o dict.o server.o sds.o zmalloc.o lzf_c.o lzf_d.o pqsort.o zipmap.o sha1.o ziplist.o release.o networking.o util.o object.o db.o replication.o rdb.o t_string.o t_list.o t_set.o t_zset.o t_hash.o config.o aof.o pubsub.o multi.o debug.o sort.o intset.o syncio.o cluster.o crc16.o endianconv.o slowlog.o scripting.o bio.o rio.o rand.o memtest.o crcspeed.o crc64.o bitops.o sentinel.o notify.o setproctitle.o blocked.o hyperloglog.o latency.o sparkline.o redis-check-rdb.o redis-check-aof.o geo.o lazyfree.o module.o evict.o expire.o geohash.o geohash_helper.o childinfo.o defrag.o siphash.o rax.o t_stream.o listpack.o localtime.o lolwut.o lolwut5.o lolwut6.o acl.o gopher.o tracking.o connection.o tls.o sha256.o timeout.o setcpuaffinity.o +REDIS_CLI_NAME=redis-cli +REDIS_CLI_OBJ=anet.o adlist.o dict.o redis-cli.o zmalloc.o release.o ae.o crcspeed.o crc64.o siphash.o crc16.o +REDIS_BENCHMARK_NAME=redis-benchmark +REDIS_BENCHMARK_OBJ=ae.o anet.o redis-benchmark.o adlist.o dict.o zmalloc.o siphash.o +REDIS_CHECK_RDB_NAME=redis-check-rdb +REDIS_CHECK_AOF_NAME=redis-check-aof + +all: $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_RDB_NAME) $(REDIS_CHECK_AOF_NAME) + @echo "" + @echo "Hint: It's a good idea to run 'make test' ;)" + @echo "" + +Makefile.dep: + -$(REDIS_CC) -MM *.c > Makefile.dep 2> /dev/null || true + +ifeq (0, $(words $(findstring $(MAKECMDGOALS), $(NODEPS)))) +-include Makefile.dep +endif .PHONY: all -all: tar rmt tar.info -tar: $(OBJS) - $(CC) $(LDFLAGS) -o $@ $(OBJS) $(LIBS) +persist-settings: distclean + echo STD=$(STD) >> .make-settings + echo WARN=$(WARN) >> .make-settings + echo OPT=$(OPT) >> .make-settings + echo MALLOC=$(MALLOC) >> .make-settings + echo BUILD_TLS=$(BUILD_TLS) >> .make-settings + echo USE_SYSTEMD=$(USE_SYSTEMD) >> .make-settings + echo CFLAGS=$(CFLAGS) >> .make-settings + echo LDFLAGS=$(LDFLAGS) >> .make-settings + echo REDIS_CFLAGS=$(REDIS_CFLAGS) >> .make-settings + echo REDIS_LDFLAGS=$(REDIS_LDFLAGS) >> .make-settings + echo PREV_FINAL_CFLAGS=$(FINAL_CFLAGS) >> .make-settings + echo PREV_FINAL_LDFLAGS=$(FINAL_LDFLAGS) >> .make-settings + -(cd ../deps && $(MAKE) $(DEPENDENCY_TARGETS)) -rmt: rmt.c - $(CC) $(CFLAGS) $(LDFLAGS) -o $@ rmt.c +.PHONY: persist-settings -tar.info: tar.texinfo - makeinfo tar.texinfo +# Prerequisites target +.make-prerequisites: + @touch $@ -.PHONY: install -install: all - $(INSTALL) tar $(bindir)/$(binprefix)tar - -test ! -f rmt || $(INSTALL) rmt /etc/rmt - $(INSTALLDATA) $(srcdir)/tar.info* $(infodir) +# Clean everything, persist settings and build dependencies if anything changed +ifneq ($(strip $(PREV_FINAL_CFLAGS)), $(strip $(FINAL_CFLAGS))) +.make-prerequisites: persist-settings +endif -$(OBJS): tar.h port.h testpad.h -regex.o buffer.o tar.o: regex.h -# getdate.y has 8 shift/reduce conflicts. +ifneq ($(strip $(PREV_FINAL_LDFLAGS)), $(strip $(FINAL_LDFLAGS))) +.make-prerequisites: persist-settings +endif -testpad.h: testpad - ./testpad +# redis-server +$(REDIS_SERVER_NAME): $(REDIS_SERVER_OBJ) + $(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a ../deps/lua/src/liblua.a $(FINAL_LIBS) -testpad: testpad.o - $(CC) -o $@ testpad.o +# redis-sentinel +$(REDIS_SENTINEL_NAME): $(REDIS_SERVER_NAME) + $(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) -TAGS: $(SRCS) - etags $(SRCS) +# redis-check-rdb +$(REDIS_CHECK_RDB_NAME): $(REDIS_SERVER_NAME) + $(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(REDIS_CHECK_RDB_NAME) + +# redis-check-aof +$(REDIS_CHECK_AOF_NAME): $(REDIS_SERVER_NAME) + $(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(REDIS_CHECK_AOF_NAME) + +# redis-cli +$(REDIS_CLI_NAME): $(REDIS_CLI_OBJ) + $(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a ../deps/linenoise/linenoise.o $(FINAL_LIBS) + +# redis-benchmark +$(REDIS_BENCHMARK_NAME): $(REDIS_BENCHMARK_OBJ) + $(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a $(FINAL_LIBS) + +dict-benchmark: dict.c zmalloc.c sds.c siphash.c + $(REDIS_CC) $(FINAL_CFLAGS) $^ -D DICT_BENCHMARK_MAIN -o $@ $(FINAL_LIBS) + +DEP = $(REDIS_SERVER_OBJ:%.o=%.d) $(REDIS_CLI_OBJ:%.o=%.d) $(REDIS_BENCHMARK_OBJ:%.o=%.d) +-include $(DEP) + +# Because the jemalloc.h header is generated as a part of the jemalloc build, +# building it should complete before building any other object. Instead of +# depending on a single artifact, build all dependencies first. +%.o: %.c .make-prerequisites + $(REDIS_CC) -MMD -o $@ -c $< + +clean: + rm -rf $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_RDB_NAME) $(REDIS_CHECK_AOF_NAME) *.o *.gcda *.gcno *.gcov redis.info lcov-html Makefile.dep dict-benchmark + rm -f $(DEP) .PHONY: clean -clean: - rm -f *.o tar rmt testpad testpad.h core + +distclean: clean + -(cd ../deps && $(MAKE) distclean) + -(rm -f .make-*) .PHONY: distclean -distclean: clean - rm -f TAGS Makefile config.status -.PHONY: realclean -realclean: distclean - rm -f tar.info* +test: $(REDIS_SERVER_NAME) $(REDIS_CHECK_AOF_NAME) + @(cd ..; ./runtest) -.PHONY: shar -shar: $(SRCS) $(AUX) - shar $(SRCS) $(AUX) | compress \ - > tar-`sed -e '/version_string/!d' \ - -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \ - -e q - version.c`.shar.Z +test-sentinel: $(REDIS_SENTINEL_NAME) + @(cd ..; ./runtest-sentinel) -.PHONY: dist -dist: $(SRCS) $(AUX) - echo tar-`sed \ - -e '/version_string/!d' \ - -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \ - -e q - version.c` > .fname - -rm -rf `cat .fname` - mkdir `cat .fname` - ln $(SRCS) $(AUX) `cat .fname` - tar chZf `cat .fname`.tar.Z `cat .fname` - -rm -rf `cat .fname` .fname +check: test -tar.zoo: $(SRCS) $(AUX) - -rm -rf tmp.dir - -mkdir tmp.dir - -rm tar.zoo - for X in $(SRCS) $(AUX) ; do \ - echo $$X ; \ - sed 's/$$/^M/' $$X \ - > tmp.dir/$$X ; done - cd tmp.dir ; zoo aM ../tar.zoo * - -rm -rf tmp.dir +lcov: + $(MAKE) gcov + @(set -e; cd ..; ./runtest --clients 1) + @geninfo -o redis.info . + @genhtml --legend -o lcov-html redis.info + +test-sds: sds.c sds.h + $(REDIS_CC) sds.c zmalloc.c -DSDS_TEST_MAIN $(FINAL_LIBS) -o /tmp/sds_test + /tmp/sds_test + +.PHONY: lcov + +bench: $(REDIS_BENCHMARK_NAME) + ./$(REDIS_BENCHMARK_NAME) + +32bit: + @echo "" + @echo "WARNING: if it fails under Linux you probably need to install libc6-dev-i386" + @echo "" + $(MAKE) CFLAGS="-m32" LDFLAGS="-m32" + +gcov: + $(MAKE) REDIS_CFLAGS="-fprofile-arcs -ftest-coverage -DCOVERAGE_TEST" REDIS_LDFLAGS="-fprofile-arcs -ftest-coverage" + +noopt: + $(MAKE) OPTIMIZATION="-O0" + +valgrind: + $(MAKE) OPTIMIZATION="-O0" MALLOC="libc" + +helgrind: + $(MAKE) OPTIMIZATION="-O0" MALLOC="libc" CFLAGS="-D__ATOMIC_VAR_FORCE_SYNC_MACROS" + +src/help.h: + @../utils/generate-command-help.rb > help.h + +install: all + @mkdir -p $(INSTALL_BIN) + $(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(INSTALL_BIN) + $(REDIS_INSTALL) $(REDIS_BENCHMARK_NAME) $(INSTALL_BIN) + $(REDIS_INSTALL) $(REDIS_CLI_NAME) $(INSTALL_BIN) + $(REDIS_INSTALL) $(REDIS_CHECK_RDB_NAME) $(INSTALL_BIN) + $(REDIS_INSTALL) $(REDIS_CHECK_AOF_NAME) $(INSTALL_BIN) + @ln -sf $(REDIS_SERVER_NAME) $(INSTALL_BIN)/$(REDIS_SENTINEL_NAME) + +uninstall: + rm -f $(INSTALL_BIN)/{$(REDIS_SERVER_NAME),$(REDIS_BENCHMARK_NAME),$(REDIS_CLI_NAME),$(REDIS_CHECK_RDB_NAME),$(REDIS_CHECK_AOF_NAME),$(REDIS_SENTINEL_NAME)} diff --git a/tests/syntax-tests/source/Makefile/LICENSE.md b/tests/syntax-tests/source/Makefile/LICENSE.md index a1244286..4e975b88 100644 --- a/tests/syntax-tests/source/Makefile/LICENSE.md +++ b/tests/syntax-tests/source/Makefile/LICENSE.md @@ -1,677 +1,12 @@ -The `Makefile` file has been added from GNU Tar (https://savannah.gnu.org/projects/tar/) under the following license: +The `Makefile` (https://github.com/redis/redis/blob/6.0.8/src/Makefile) file has been added from Redis (https://github.com/redis/redis) under the following license: +Copyright (c) 2006-2020, Salvatore Sanfilippo +All rights reserved. -GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * Neither the name of Redis nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. \ No newline at end of file +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/tests/syntax-tests/source/Makefile/Makefile b/tests/syntax-tests/source/Makefile/Makefile index 085d4f83..7acc5b2d 100644 --- a/tests/syntax-tests/source/Makefile/Makefile +++ b/tests/syntax-tests/source/Makefile/Makefile @@ -1,195 +1,385 @@ -#!/usr/bin/make -f -# Generated automatically from Makefile.in by configure. -# Un*x Makefile for GNU tar program. -# Copyright (C) 1991 Free Software Foundation, Inc. +# Redis Makefile +# Copyright (C) 2009 Salvatore Sanfilippo +# This file is released under the BSD license, see the COPYING file +# +# The Makefile composes the final FINAL_CFLAGS and FINAL_LDFLAGS using +# what is needed for Redis plus the standard CFLAGS and LDFLAGS passed. +# However when building the dependencies (Jemalloc, Lua, Hiredis, ...) +# CFLAGS and LDFLAGS are propagated to the dependencies, so to pass +# flags only to be used when compiling / linking Redis itself REDIS_CFLAGS +# and REDIS_LDFLAGS are used instead (this is the case of 'make gcov'). +# +# Dependencies are stored in the Makefile.dep file. To rebuild this file +# Just use 'make dep', but this is only needed by developers. -# This program is free software; you can redistribute -# it and/or modify it under the terms of the GNU -# General Public License … -… -… +release_hdr := $(shell sh -c './mkreleasehdr.sh') +uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') +uname_M := $(shell sh -c 'uname -m 2>/dev/null || echo not') +OPTIMIZATION?=-O2 +DEPENDENCY_TARGETS=hiredis linenoise lua +NODEPS:=clean distclean -SHELL = /bin/sh +# Default settings +STD=-std=c11 -pedantic -DREDIS_STATIC='' +ifneq (,$(findstring clang,$(CC))) +ifneq (,$(findstring FreeBSD,$(uname_S))) + STD+=-Wno-c11-extensions +endif +endif +WARN=-Wall -W -Wno-missing-field-initializers +OPT=$(OPTIMIZATION) -#### Start of system configuration section. #### +PREFIX?=/usr/local +INSTALL_BIN=$(PREFIX)/bin +INSTALL=install +PKG_CONFIG?=pkg-config -srcdir = . +# Default allocator defaults to Jemalloc if it's not an ARM +MALLOC=libc +ifneq ($(uname_M),armv6l) +ifneq ($(uname_M),armv7l) +ifeq ($(uname_S),Linux) + MALLOC=jemalloc +endif +endif +endif -# If you use gcc, you should either run the -# fixincludes script that comes with it or else use -# gcc with the -traditional option. Otherwise ioctl -# calls will be compiled incorrectly on some systems. -CC = gcc -O -YACC = bison -y -INSTALL = /usr/local/bin/install -c -INSTALLDATA = /usr/local/bin/install -c -m 644 +# To get ARM stack traces if Redis crashes we need a special C flag. +ifneq (,$(filter aarch64 armv,$(uname_M))) + CFLAGS+=-funwind-tables +else +ifneq (,$(findstring armv,$(uname_M))) + CFLAGS+=-funwind-tables +endif +endif -# Things you might add to DEFS: -# -DSTDC_HEADERS If you have ANSI C headers and -# libraries. -# -DPOSIX If you have POSIX.1 headers and -# libraries. -# -DBSD42 If you have sys/dir.h (unless -# you use -DPOSIX), sys/file.h, -# and st_blocks in `struct stat'. -# -DUSG If you have System V/ANSI C -# string and memory functions -# and headers, sys/sysmacros.h, -# fcntl.h, getcwd, no valloc, -# and ndir.h (unless -# you use -DDIRENT). -# -DNO_MEMORY_H If USG or STDC_HEADERS but do not -# include memory.h. -# -DDIRENT If USG and you have dirent.h -# instead of ndir.h. -# -DSIGTYPE=int If your signal handlers -# return int, not void. -# -DNO_MTIO If you lack sys/mtio.h -# (magtape ioctls). -# -DNO_REMOTE If you do not have a remote shell -# or rexec. -# -DUSE_REXEC To use rexec for remote tape -# operations instead of -# forking rsh or remsh. -# -DVPRINTF_MISSING If you lack vprintf function -# (but have _doprnt). -# -DDOPRNT_MISSING If you lack _doprnt function. -# Also need to define -# -DVPRINTF_MISSING. -# -DFTIME_MISSING If you lack ftime system call. -# -DSTRSTR_MISSING If you lack strstr function. -# -DVALLOC_MISSING If you lack valloc function. -# -DMKDIR_MISSING If you lack mkdir and -# rmdir system calls. -# -DRENAME_MISSING If you lack rename system call. -# -DFTRUNCATE_MISSING If you lack ftruncate -# system call. -# -DV7 On Version 7 Unix (not -# tested in a long time). -# -DEMUL_OPEN3 If you lack a 3-argument version -# of open, and want to emulate it -# with system calls you do have. -# -DNO_OPEN3 If you lack the 3-argument open -# and want to disable the tar -k -# option instead of emulating open. -# -DXENIX If you have sys/inode.h -# and need it 94 to be included. +# Backwards compatibility for selecting an allocator +ifeq ($(USE_TCMALLOC),yes) + MALLOC=tcmalloc +endif -DEFS = -DSIGTYPE=int -DDIRENT -DSTRSTR_MISSING \ - -DVPRINTF_MISSING -DBSD42 -# Set this to rtapelib.o unless you defined NO_REMOTE, -# in which case make it empty. -RTAPELIB = rtapelib.o -LIBS = -DEF_AR_FILE = /dev/rmt8 -DEFBLOCKING = 20 +ifeq ($(USE_TCMALLOC_MINIMAL),yes) + MALLOC=tcmalloc_minimal +endif -CDEBUG = -g -CFLAGS = $(CDEBUG) -I. -I$(srcdir) $(DEFS) \ - -DDEF_AR_FILE=\"$(DEF_AR_FILE)\" \ - -DDEFBLOCKING=$(DEFBLOCKING) -LDFLAGS = -g +ifeq ($(USE_JEMALLOC),yes) + MALLOC=jemalloc +endif -prefix = /usr/local -# Prefix for each installed program, -# normally empty or `g'. -binprefix = +ifeq ($(USE_JEMALLOC),no) + MALLOC=libc +endif -# The directory to install tar in. -bindir = $(prefix)/bin +# Override default settings if possible +-include .make-settings -# The directory to install the info files in. -infodir = $(prefix)/info +FINAL_CFLAGS=$(STD) $(WARN) $(OPT) $(DEBUG) $(CFLAGS) $(REDIS_CFLAGS) +FINAL_LDFLAGS=$(LDFLAGS) $(REDIS_LDFLAGS) $(DEBUG) +FINAL_LIBS=-lm +DEBUG=-g -ggdb -#### End of system configuration section. #### +# Linux ARM needs -latomic at linking time +ifneq (,$(filter aarch64 armv,$(uname_M))) + FINAL_LIBS+=-latomic +else +ifneq (,$(findstring armv,$(uname_M))) + FINAL_LIBS+=-latomic +endif +endif -SRCS_C = tar.c create.c extract.c buffer.c \ - getoldopt.c update.c gnu.c mangle.c \ - version.c list.c names.c diffarch.c \ - port.c wildmat.c getopt.c getopt1.c \ - regex.c -SRCS_Y = getdate.y -SRCS = $(SRCS_C) $(SRCS_Y) -OBJS = $(SRCS_C:.c=.o) $(SRCS_Y:.y=.o) $(RTAPELIB) -AUX = README COPYING ChangeLog Makefile.in \ - makefile.pc configure configure.in \ - tar.texinfo tar.info* texinfo.tex \ - tar.h port.h open3.h getopt.h regex.h \ - rmt.h rmt.c rtapelib.c alloca.c \ - msd_dir.h msd_dir.c tcexparg.c \ - level-0 level-1 backup-specs testpad.c +ifeq ($(uname_S),SunOS) + # SunOS + ifneq ($(@@),32bit) + CFLAGS+= -m64 + LDFLAGS+= -m64 + endif + DEBUG=-g + DEBUG_FLAGS=-g + export CFLAGS LDFLAGS DEBUG DEBUG_FLAGS + INSTALL=cp -pf + FINAL_CFLAGS+= -D__EXTENSIONS__ -D_XPG6 + FINAL_LIBS+= -ldl -lnsl -lsocket -lresolv -lpthread -lrt +else +ifeq ($(uname_S),Darwin) + # Darwin + FINAL_LIBS+= -ldl + OPENSSL_CFLAGS=-I/usr/local/opt/openssl/include + OPENSSL_LDFLAGS=-L/usr/local/opt/openssl/lib +else +ifeq ($(uname_S),AIX) + # AIX + FINAL_LDFLAGS+= -Wl,-bexpall + FINAL_LIBS+=-ldl -pthread -lcrypt -lbsd +else +ifeq ($(uname_S),OpenBSD) + # OpenBSD + FINAL_LIBS+= -lpthread + ifeq ($(USE_BACKTRACE),yes) + FINAL_CFLAGS+= -DUSE_BACKTRACE -I/usr/local/include + FINAL_LDFLAGS+= -L/usr/local/lib + FINAL_LIBS+= -lexecinfo + endif + +else +ifeq ($(uname_S),FreeBSD) + # FreeBSD + FINAL_LIBS+= -lpthread -lexecinfo +else +ifeq ($(uname_S),DragonFly) + # FreeBSD + FINAL_LIBS+= -lpthread -lexecinfo +else +ifeq ($(uname_S),OpenBSD) + # OpenBSD + FINAL_LIBS+= -lpthread -lexecinfo +else +ifeq ($(uname_S),NetBSD) + # NetBSD + FINAL_LIBS+= -lpthread -lexecinfo +else + # All the other OSes (notably Linux) + FINAL_LDFLAGS+= -rdynamic + FINAL_LIBS+=-ldl -pthread -lrt +endif +endif +endif +endif +endif +endif +endif +endif +# Include paths to dependencies +FINAL_CFLAGS+= -I../deps/hiredis -I../deps/linenoise -I../deps/lua/src + +# Determine systemd support and/or build preference (defaulting to auto-detection) +BUILD_WITH_SYSTEMD=no +# If 'USE_SYSTEMD' in the environment is neither "no" nor "yes", try to +# auto-detect libsystemd's presence and link accordingly. +ifneq ($(USE_SYSTEMD),no) + LIBSYSTEMD_PKGCONFIG := $(shell $(PKG_CONFIG) --exists libsystemd && echo $$?) +# If libsystemd cannot be detected, continue building without support for it +# (unless a later check tells us otherwise) +ifeq ($(LIBSYSTEMD_PKGCONFIG),0) + BUILD_WITH_SYSTEMD=yes +endif +endif +ifeq ($(USE_SYSTEMD),yes) +ifneq ($(LIBSYSTEMD_PKGCONFIG),0) +$(error USE_SYSTEMD is set to "$(USE_SYSTEMD)", but $(PKG_CONFIG) cannot find libsystemd) +endif +# Force building with libsystemd + BUILD_WITH_SYSTEMD=yes +endif +ifeq ($(BUILD_WITH_SYSTEMD),yes) + FINAL_LIBS+=$(shell $(PKG_CONFIG) --libs libsystemd) + FINAL_CFLAGS+= -DHAVE_LIBSYSTEMD +endif + +ifeq ($(MALLOC),tcmalloc) + FINAL_CFLAGS+= -DUSE_TCMALLOC + FINAL_LIBS+= -ltcmalloc +endif + +ifeq ($(MALLOC),tcmalloc_minimal) + FINAL_CFLAGS+= -DUSE_TCMALLOC + FINAL_LIBS+= -ltcmalloc_minimal +endif + +ifeq ($(MALLOC),jemalloc) + DEPENDENCY_TARGETS+= jemalloc + FINAL_CFLAGS+= -DUSE_JEMALLOC -I../deps/jemalloc/include + FINAL_LIBS := ../deps/jemalloc/lib/libjemalloc.a $(FINAL_LIBS) +endif + +ifeq ($(BUILD_TLS),yes) + FINAL_CFLAGS+=-DUSE_OPENSSL $(OPENSSL_CFLAGS) + FINAL_LDFLAGS+=$(OPENSSL_LDFLAGS) + LIBSSL_PKGCONFIG := $(shell $(PKG_CONFIG) --exists libssl && echo $$?) +ifeq ($(LIBSSL_PKGCONFIG),0) + LIBSSL_LIBS=$(shell $(PKG_CONFIG) --libs libssl) +else + LIBSSL_LIBS=-lssl +endif + LIBCRYPTO_PKGCONFIG := $(shell $(PKG_CONFIG) --exists libcrypto && echo $$?) +ifeq ($(LIBCRYPTO_PKGCONFIG),0) + LIBCRYPTO_LIBS=$(shell $(PKG_CONFIG) --libs libcrypto) +else + LIBCRYPTO_LIBS=-lcrypto +endif + FINAL_LIBS += ../deps/hiredis/libhiredis_ssl.a $(LIBSSL_LIBS) $(LIBCRYPTO_LIBS) +endif + +REDIS_CC=$(QUIET_CC)$(CC) $(FINAL_CFLAGS) +REDIS_LD=$(QUIET_LINK)$(CC) $(FINAL_LDFLAGS) +REDIS_INSTALL=$(QUIET_INSTALL)$(INSTALL) + +CCCOLOR="\033[34m" +LINKCOLOR="\033[34;1m" +SRCCOLOR="\033[33m" +BINCOLOR="\033[37;1m" +MAKECOLOR="\033[32;1m" +ENDCOLOR="\033[0m" + +ifndef V +QUIET_CC = @printf ' %b %b\n' $(CCCOLOR)CC$(ENDCOLOR) $(SRCCOLOR)$@$(ENDCOLOR) 1>&2; +QUIET_LINK = @printf ' %b %b\n' $(LINKCOLOR)LINK$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; +QUIET_INSTALL = @printf ' %b %b\n' $(LINKCOLOR)INSTALL$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR) 1>&2; +endif + +REDIS_SERVER_NAME=redis-server +REDIS_SENTINEL_NAME=redis-sentinel +REDIS_SERVER_OBJ=adlist.o quicklist.o ae.o anet.o dict.o server.o sds.o zmalloc.o lzf_c.o lzf_d.o pqsort.o zipmap.o sha1.o ziplist.o release.o networking.o util.o object.o db.o replication.o rdb.o t_string.o t_list.o t_set.o t_zset.o t_hash.o config.o aof.o pubsub.o multi.o debug.o sort.o intset.o syncio.o cluster.o crc16.o endianconv.o slowlog.o scripting.o bio.o rio.o rand.o memtest.o crcspeed.o crc64.o bitops.o sentinel.o notify.o setproctitle.o blocked.o hyperloglog.o latency.o sparkline.o redis-check-rdb.o redis-check-aof.o geo.o lazyfree.o module.o evict.o expire.o geohash.o geohash_helper.o childinfo.o defrag.o siphash.o rax.o t_stream.o listpack.o localtime.o lolwut.o lolwut5.o lolwut6.o acl.o gopher.o tracking.o connection.o tls.o sha256.o timeout.o setcpuaffinity.o +REDIS_CLI_NAME=redis-cli +REDIS_CLI_OBJ=anet.o adlist.o dict.o redis-cli.o zmalloc.o release.o ae.o crcspeed.o crc64.o siphash.o crc16.o +REDIS_BENCHMARK_NAME=redis-benchmark +REDIS_BENCHMARK_OBJ=ae.o anet.o redis-benchmark.o adlist.o dict.o zmalloc.o siphash.o +REDIS_CHECK_RDB_NAME=redis-check-rdb +REDIS_CHECK_AOF_NAME=redis-check-aof + +all: $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_RDB_NAME) $(REDIS_CHECK_AOF_NAME) + @echo "" + @echo "Hint: It's a good idea to run 'make test' ;)" + @echo "" + +Makefile.dep: + -$(REDIS_CC) -MM *.c > Makefile.dep 2> /dev/null || true + +ifeq (0, $(words $(findstring $(MAKECMDGOALS), $(NODEPS)))) +-include Makefile.dep +endif .PHONY: all -all: tar rmt tar.info -tar: $(OBJS) - $(CC) $(LDFLAGS) -o $@ $(OBJS) $(LIBS) +persist-settings: distclean + echo STD=$(STD) >> .make-settings + echo WARN=$(WARN) >> .make-settings + echo OPT=$(OPT) >> .make-settings + echo MALLOC=$(MALLOC) >> .make-settings + echo BUILD_TLS=$(BUILD_TLS) >> .make-settings + echo USE_SYSTEMD=$(USE_SYSTEMD) >> .make-settings + echo CFLAGS=$(CFLAGS) >> .make-settings + echo LDFLAGS=$(LDFLAGS) >> .make-settings + echo REDIS_CFLAGS=$(REDIS_CFLAGS) >> .make-settings + echo REDIS_LDFLAGS=$(REDIS_LDFLAGS) >> .make-settings + echo PREV_FINAL_CFLAGS=$(FINAL_CFLAGS) >> .make-settings + echo PREV_FINAL_LDFLAGS=$(FINAL_LDFLAGS) >> .make-settings + -(cd ../deps && $(MAKE) $(DEPENDENCY_TARGETS)) -rmt: rmt.c - $(CC) $(CFLAGS) $(LDFLAGS) -o $@ rmt.c +.PHONY: persist-settings -tar.info: tar.texinfo - makeinfo tar.texinfo +# Prerequisites target +.make-prerequisites: + @touch $@ -.PHONY: install -install: all - $(INSTALL) tar $(bindir)/$(binprefix)tar - -test ! -f rmt || $(INSTALL) rmt /etc/rmt - $(INSTALLDATA) $(srcdir)/tar.info* $(infodir) +# Clean everything, persist settings and build dependencies if anything changed +ifneq ($(strip $(PREV_FINAL_CFLAGS)), $(strip $(FINAL_CFLAGS))) +.make-prerequisites: persist-settings +endif -$(OBJS): tar.h port.h testpad.h -regex.o buffer.o tar.o: regex.h -# getdate.y has 8 shift/reduce conflicts. +ifneq ($(strip $(PREV_FINAL_LDFLAGS)), $(strip $(FINAL_LDFLAGS))) +.make-prerequisites: persist-settings +endif -testpad.h: testpad - ./testpad +# redis-server +$(REDIS_SERVER_NAME): $(REDIS_SERVER_OBJ) + $(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a ../deps/lua/src/liblua.a $(FINAL_LIBS) -testpad: testpad.o - $(CC) -o $@ testpad.o +# redis-sentinel +$(REDIS_SENTINEL_NAME): $(REDIS_SERVER_NAME) + $(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) -TAGS: $(SRCS) - etags $(SRCS) +# redis-check-rdb +$(REDIS_CHECK_RDB_NAME): $(REDIS_SERVER_NAME) + $(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(REDIS_CHECK_RDB_NAME) + +# redis-check-aof +$(REDIS_CHECK_AOF_NAME): $(REDIS_SERVER_NAME) + $(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(REDIS_CHECK_AOF_NAME) + +# redis-cli +$(REDIS_CLI_NAME): $(REDIS_CLI_OBJ) + $(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a ../deps/linenoise/linenoise.o $(FINAL_LIBS) + +# redis-benchmark +$(REDIS_BENCHMARK_NAME): $(REDIS_BENCHMARK_OBJ) + $(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a $(FINAL_LIBS) + +dict-benchmark: dict.c zmalloc.c sds.c siphash.c + $(REDIS_CC) $(FINAL_CFLAGS) $^ -D DICT_BENCHMARK_MAIN -o $@ $(FINAL_LIBS) + +DEP = $(REDIS_SERVER_OBJ:%.o=%.d) $(REDIS_CLI_OBJ:%.o=%.d) $(REDIS_BENCHMARK_OBJ:%.o=%.d) +-include $(DEP) + +# Because the jemalloc.h header is generated as a part of the jemalloc build, +# building it should complete before building any other object. Instead of +# depending on a single artifact, build all dependencies first. +%.o: %.c .make-prerequisites + $(REDIS_CC) -MMD -o $@ -c $< + +clean: + rm -rf $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_RDB_NAME) $(REDIS_CHECK_AOF_NAME) *.o *.gcda *.gcno *.gcov redis.info lcov-html Makefile.dep dict-benchmark + rm -f $(DEP) .PHONY: clean -clean: - rm -f *.o tar rmt testpad testpad.h core + +distclean: clean + -(cd ../deps && $(MAKE) distclean) + -(rm -f .make-*) .PHONY: distclean -distclean: clean - rm -f TAGS Makefile config.status -.PHONY: realclean -realclean: distclean - rm -f tar.info* +test: $(REDIS_SERVER_NAME) $(REDIS_CHECK_AOF_NAME) + @(cd ..; ./runtest) -.PHONY: shar -shar: $(SRCS) $(AUX) - shar $(SRCS) $(AUX) | compress \ - > tar-`sed -e '/version_string/!d' \ - -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \ - -e q - version.c`.shar.Z +test-sentinel: $(REDIS_SENTINEL_NAME) + @(cd ..; ./runtest-sentinel) -.PHONY: dist -dist: $(SRCS) $(AUX) - echo tar-`sed \ - -e '/version_string/!d' \ - -e 's/[^0-9.]*\([0-9.]*\).*/\1/' \ - -e q - version.c` > .fname - -rm -rf `cat .fname` - mkdir `cat .fname` - ln $(SRCS) $(AUX) `cat .fname` - tar chZf `cat .fname`.tar.Z `cat .fname` - -rm -rf `cat .fname` .fname +check: test -tar.zoo: $(SRCS) $(AUX) - -rm -rf tmp.dir - -mkdir tmp.dir - -rm tar.zoo - for X in $(SRCS) $(AUX) ; do \ - echo $$X ; \ - sed 's/$$/^M/' $$X \ - > tmp.dir/$$X ; done - cd tmp.dir ; zoo aM ../tar.zoo * - -rm -rf tmp.dir \ No newline at end of file +lcov: + $(MAKE) gcov + @(set -e; cd ..; ./runtest --clients 1) + @geninfo -o redis.info . + @genhtml --legend -o lcov-html redis.info + +test-sds: sds.c sds.h + $(REDIS_CC) sds.c zmalloc.c -DSDS_TEST_MAIN $(FINAL_LIBS) -o /tmp/sds_test + /tmp/sds_test + +.PHONY: lcov + +bench: $(REDIS_BENCHMARK_NAME) + ./$(REDIS_BENCHMARK_NAME) + +32bit: + @echo "" + @echo "WARNING: if it fails under Linux you probably need to install libc6-dev-i386" + @echo "" + $(MAKE) CFLAGS="-m32" LDFLAGS="-m32" + +gcov: + $(MAKE) REDIS_CFLAGS="-fprofile-arcs -ftest-coverage -DCOVERAGE_TEST" REDIS_LDFLAGS="-fprofile-arcs -ftest-coverage" + +noopt: + $(MAKE) OPTIMIZATION="-O0" + +valgrind: + $(MAKE) OPTIMIZATION="-O0" MALLOC="libc" + +helgrind: + $(MAKE) OPTIMIZATION="-O0" MALLOC="libc" CFLAGS="-D__ATOMIC_VAR_FORCE_SYNC_MACROS" + +src/help.h: + @../utils/generate-command-help.rb > help.h + +install: all + @mkdir -p $(INSTALL_BIN) + $(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(INSTALL_BIN) + $(REDIS_INSTALL) $(REDIS_BENCHMARK_NAME) $(INSTALL_BIN) + $(REDIS_INSTALL) $(REDIS_CLI_NAME) $(INSTALL_BIN) + $(REDIS_INSTALL) $(REDIS_CHECK_RDB_NAME) $(INSTALL_BIN) + $(REDIS_INSTALL) $(REDIS_CHECK_AOF_NAME) $(INSTALL_BIN) + @ln -sf $(REDIS_SERVER_NAME) $(INSTALL_BIN)/$(REDIS_SENTINEL_NAME) + +uninstall: + rm -f $(INSTALL_BIN)/{$(REDIS_SERVER_NAME),$(REDIS_BENCHMARK_NAME),$(REDIS_CLI_NAME),$(REDIS_CHECK_RDB_NAME),$(REDIS_CHECK_AOF_NAME),$(REDIS_SENTINEL_NAME)} \ No newline at end of file From 8d574826c9a7a7b8d250eb95bb8fa0e34137811d Mon Sep 17 00:00:00 2001 From: Matthieu Vion Date: Fri, 16 Oct 2020 15:14:15 +0200 Subject: [PATCH 077/243] Added reStructuredText reference for syntax tests --- .../reStructuredText/reference.rst | 320 ++++++++++++++++++ .../source/reStructuredText/reference.rst | 320 ++++++++++++++++++ 2 files changed, 640 insertions(+) create mode 100644 tests/syntax-tests/highlighted/reStructuredText/reference.rst create mode 100644 tests/syntax-tests/source/reStructuredText/reference.rst diff --git a/tests/syntax-tests/highlighted/reStructuredText/reference.rst b/tests/syntax-tests/highlighted/reStructuredText/reference.rst new file mode 100644 index 00000000..4981e15e --- /dev/null +++ b/tests/syntax-tests/highlighted/reStructuredText/reference.rst @@ -0,0 +1,320 @@ +===== +Title +===== + +Subtitle +-------- +Titles are underlined (or over- +and underlined) with a printing +nonalphanumeric 7-bit ASCII +character. Recommended choices +are "``= - ` : ' " ~ ^ _ * + # < >``". +The underline/overline must be at +least as long as the title text. + +A lone top-level (sub)section +is lifted up to be the document's +(sub)title. + +Inline syntaxes +--------------- + +*emphasis*  +**strong emphasis** +`interpreted text` +``inline literal`` +http://docutils.sf.net/ + +Bullet lists +------------ + +- This is item 1 +- This is item 2 + +- Bullets are "-", "*" or "+". + Continuing text must be aligned + after the bullet and whitespace. + +Note that a blank line is required +before the first item and after the +last, but is optional between items. + +Enumerated lists +---------------- +3. This is the first item +4. This is the second item +5. Enumerators are arabic numbers, + single letters, or roman numerals +6. List items should be sequentially + numbered, but need not start at 1 + (although not all formatters will + honour the first index). +#. This item is auto-enumerated + +Definition lists +---------------- + +what + Definition lists associate a term with + a definition. + +how + The term is a one-line phrase, and the + definition is one or more paragraphs or + body elements, indented relative to the + term. Blank lines are not allowed + between term and definition. + +Field lists +----------- +:Authors: + Tony J. (Tibs) Ibbs, + David Goodger + (and sundry other good-natured folks) + +:Version: 1.0 of 2001/08/08 +:Dedication: To my father. + +Options lists +------------- +-a command-line option "a" +-b file options can have arguments + and long descriptions +--long options can be long also +--input=file long options can also have + arguments +/V DOS/VMS-style options too + +Literal Blocks +-------------- + +A paragraph containing only two colons +indicates that the following indented +or quoted text is a literal block. + +:: + + Whitespace, newlines, blank lines, and + all kinds of markup (like *this* or + \this) is preserved by literal blocks. + + The paragraph containing only '::' + will be omitted from the result. + +The ``::`` may be tacked onto the very +end of any paragraph. The ``::`` will be +omitted if it is preceded by whitespace. +The ``::`` will be converted to a single +colon if preceded by text, like this:: + + It's very convenient to use this form. + +Literal blocks end when text returns to +the preceding paragraph's indentation. +This means that something like this +is possible:: + + We start here + and continue here + and end here. + +Per-line quoting can also be used on +unindented literal blocks:: + +> Useful for quotes from email and +> for Haskell literate programming. + +Line blocks +----------- + +A paragraph containing only two colons +indicates that the following indented +or quoted text is a literal block. + +:: + + Whitespace, newlines, blank lines, and + all kinds of markup (like *this* or + \this) is preserved by literal blocks. + + The paragraph containing only '::' + will be omitted from the result. + +The ``::`` may be tacked onto the very +end of any paragraph. The ``::`` will be +omitted if it is preceded by whitespace. +The ``::`` will be converted to a single +colon if preceded by text, like this:: + + It's very convenient to use this form. + +Literal blocks end when text returns to +the preceding paragraph's indentation. +This means that something like this +is possible:: + + We start here + and continue here + and end here. + +Per-line quoting can also be used on +unindented literal blocks:: + +> Useful for quotes from email and +> for Haskell literate programming. + +Block quotes +------------ + +Block quotes are just: + Indented paragraphs, + + and they may nest. + +Doctest blocks +-------------- +Doctest blocks are interactive +Python sessions. They begin with +"``>>>``" and end with a blank line. + +>>> print "This is a doctest block." +This is a doctest block. + +Tables +------ + +Grid table: + ++------------+------------+-----------+ +| Header 1 | Header 2 | Header 3 | ++============+============+===========+ +| body row 1 | column 2 | column 3 | ++------------+------------+-----------+ +| body row 2 | Cells may span columns.| ++------------+------------+-----------+ +| body row 3 | Cells may | - Cells | ++------------+ span rows. | - contain | +| body row 4 | | - blocks. | ++------------+------------+-----------+ + +Simple table: + +===== ===== ====== + Inputs Output +------------ ------ + A B A or B +===== ===== ====== +False False False +True False True +False True True +True True True +===== ===== ====== + +Transitions +----------- + +A transition marker is a horizontal line +of 4 or more repeated punctuation +characters. + +------------ + +A transition should not begin or end a +section or document, nor should two +transitions be immediately adjacent. + +Footnotes +--------- + +Footnote references, like [5]_. +Note that footnotes may get +rearranged, e.g., to the bottom of +the "page". +.. [5] A numerical footnote. Note there's no colon after the ``]``. + +Autonumbered footnotes are +possible, like using [#]_ and [#]_. +.. [#] This is the first one. +.. [#] This is the second one. + +They may be assigned 'autonumber +labels' - for instance, +[#fourth]_ and [#third]_. + +.. [#third] a.k.a. third_ + +.. [#fourth] a.k.a. fourth_ + +Auto-symbol footnotes are also +possible, like this: [*]_ and [*]_. +.. [*] This is the first one. +.. [*] This is the second one. + +Citations +--------- + +Citation references, like [CIT2002]_. +Note that citations may get +rearranged, e.g., to the bottom of +the "page". + +.. [CIT2002] A citation (as often used in journals). + +Citation labels contain alphanumerics, +underlines, hyphens and fullstops. +Case is not significant. + +Given a citation like [this]_, one +can also refer to it like this_. + +.. [this] here. + +Hyperlink Targets +----------------- + +External hyperlinks, like Python_. +.. _Python: http://www.python.org/ + +External hyperlinks, like `Python +`_. + +Internal crossreferences, like example_. +.. _example: + +This is an example crossreference target. + +Python_ is `my favourite +programming language`__. +.. _Python: http://www.python.org/ + +__ Python_ + +Titles are targets, too +======================= +Implict references, like `Titles are +targets, too`_. + +Directives +---------- + +For instance: +.. image:: images/ball1.gif + +The |biohazard| symbol must be used on containers used to dispose of medical waste. +.. |biohazard| image:: biohazard.png + +Comments +-------- + +.. This text will not be shown + (but, for instance, in HTML might be + rendered as an HTML comment) + +An "empty comment" does not +consume following blocks. +(An empty comment is ".." with +blank lines before and after.) +.. + + So this block is not "lost", + despite its indentation. diff --git a/tests/syntax-tests/source/reStructuredText/reference.rst b/tests/syntax-tests/source/reStructuredText/reference.rst new file mode 100644 index 00000000..e07f54c4 --- /dev/null +++ b/tests/syntax-tests/source/reStructuredText/reference.rst @@ -0,0 +1,320 @@ +===== +Title +===== + +Subtitle +-------- +Titles are underlined (or over- +and underlined) with a printing +nonalphanumeric 7-bit ASCII +character. Recommended choices +are "``= - ` : ' " ~ ^ _ * + # < >``". +The underline/overline must be at +least as long as the title text. + +A lone top-level (sub)section +is lifted up to be the document's +(sub)title. + +Inline syntaxes +--------------- + +*emphasis* +**strong emphasis** +`interpreted text` +``inline literal`` +http://docutils.sf.net/ + +Bullet lists +------------ + +- This is item 1 +- This is item 2 + +- Bullets are "-", "*" or "+". + Continuing text must be aligned + after the bullet and whitespace. + +Note that a blank line is required +before the first item and after the +last, but is optional between items. + +Enumerated lists +---------------- +3. This is the first item +4. This is the second item +5. Enumerators are arabic numbers, + single letters, or roman numerals +6. List items should be sequentially + numbered, but need not start at 1 + (although not all formatters will + honour the first index). +#. This item is auto-enumerated + +Definition lists +---------------- + +what + Definition lists associate a term with + a definition. + +how + The term is a one-line phrase, and the + definition is one or more paragraphs or + body elements, indented relative to the + term. Blank lines are not allowed + between term and definition. + +Field lists +----------- +:Authors: + Tony J. (Tibs) Ibbs, + David Goodger + (and sundry other good-natured folks) + +:Version: 1.0 of 2001/08/08 +:Dedication: To my father. + +Options lists +------------- +-a command-line option "a" +-b file options can have arguments + and long descriptions +--long options can be long also +--input=file long options can also have + arguments +/V DOS/VMS-style options too + +Literal Blocks +-------------- + +A paragraph containing only two colons +indicates that the following indented +or quoted text is a literal block. + +:: + + Whitespace, newlines, blank lines, and + all kinds of markup (like *this* or + \this) is preserved by literal blocks. + + The paragraph containing only '::' + will be omitted from the result. + +The ``::`` may be tacked onto the very +end of any paragraph. The ``::`` will be +omitted if it is preceded by whitespace. +The ``::`` will be converted to a single +colon if preceded by text, like this:: + + It's very convenient to use this form. + +Literal blocks end when text returns to +the preceding paragraph's indentation. +This means that something like this +is possible:: + + We start here + and continue here + and end here. + +Per-line quoting can also be used on +unindented literal blocks:: + +> Useful for quotes from email and +> for Haskell literate programming. + +Line blocks +----------- + +A paragraph containing only two colons +indicates that the following indented +or quoted text is a literal block. + +:: + + Whitespace, newlines, blank lines, and + all kinds of markup (like *this* or + \this) is preserved by literal blocks. + + The paragraph containing only '::' + will be omitted from the result. + +The ``::`` may be tacked onto the very +end of any paragraph. The ``::`` will be +omitted if it is preceded by whitespace. +The ``::`` will be converted to a single +colon if preceded by text, like this:: + + It's very convenient to use this form. + +Literal blocks end when text returns to +the preceding paragraph's indentation. +This means that something like this +is possible:: + + We start here + and continue here + and end here. + +Per-line quoting can also be used on +unindented literal blocks:: + +> Useful for quotes from email and +> for Haskell literate programming. + +Block quotes +------------ + +Block quotes are just: + Indented paragraphs, + + and they may nest. + +Doctest blocks +-------------- +Doctest blocks are interactive +Python sessions. They begin with +"``>>>``" and end with a blank line. + +>>> print "This is a doctest block." +This is a doctest block. + +Tables +------ + +Grid table: + ++------------+------------+-----------+ +| Header 1 | Header 2 | Header 3 | ++============+============+===========+ +| body row 1 | column 2 | column 3 | ++------------+------------+-----------+ +| body row 2 | Cells may span columns.| ++------------+------------+-----------+ +| body row 3 | Cells may | - Cells | ++------------+ span rows. | - contain | +| body row 4 | | - blocks. | ++------------+------------+-----------+ + +Simple table: + +===== ===== ====== + Inputs Output +------------ ------ + A B A or B +===== ===== ====== +False False False +True False True +False True True +True True True +===== ===== ====== + +Transitions +----------- + +A transition marker is a horizontal line +of 4 or more repeated punctuation +characters. + +------------ + +A transition should not begin or end a +section or document, nor should two +transitions be immediately adjacent. + +Footnotes +--------- + +Footnote references, like [5]_. +Note that footnotes may get +rearranged, e.g., to the bottom of +the "page". +.. [5] A numerical footnote. Note there's no colon after the ``]``. + +Autonumbered footnotes are +possible, like using [#]_ and [#]_. +.. [#] This is the first one. +.. [#] This is the second one. + +They may be assigned 'autonumber +labels' - for instance, +[#fourth]_ and [#third]_. + +.. [#third] a.k.a. third_ + +.. [#fourth] a.k.a. fourth_ + +Auto-symbol footnotes are also +possible, like this: [*]_ and [*]_. +.. [*] This is the first one. +.. [*] This is the second one. + +Citations +--------- + +Citation references, like [CIT2002]_. +Note that citations may get +rearranged, e.g., to the bottom of +the "page". + +.. [CIT2002] A citation (as often used in journals). + +Citation labels contain alphanumerics, +underlines, hyphens and fullstops. +Case is not significant. + +Given a citation like [this]_, one +can also refer to it like this_. + +.. [this] here. + +Hyperlink Targets +----------------- + +External hyperlinks, like Python_. +.. _Python: http://www.python.org/ + +External hyperlinks, like `Python +`_. + +Internal crossreferences, like example_. +.. _example: + +This is an example crossreference target. + +Python_ is `my favourite +programming language`__. +.. _Python: http://www.python.org/ + +__ Python_ + +Titles are targets, too +======================= +Implict references, like `Titles are +targets, too`_. + +Directives +---------- + +For instance: +.. image:: images/ball1.gif + +The |biohazard| symbol must be used on containers used to dispose of medical waste. +.. |biohazard| image:: biohazard.png + +Comments +-------- + +.. This text will not be shown + (but, for instance, in HTML might be + rendered as an HTML comment) + +An "empty comment" does not +consume following blocks. +(An empty comment is ".." with +blank lines before and after.) +.. + + So this block is not "lost", + despite its indentation. \ No newline at end of file From 3c756a65a61219d7a68aa1551dbda45b5464a030 Mon Sep 17 00:00:00 2001 From: "Zachary J. Rollyson" Date: Sat, 17 Oct 2020 10:22:37 -0400 Subject: [PATCH 078/243] feat: add syntax tests for sass --- .../highlighted/Sass/example.sass | 76 +++++++++++++++++++ tests/syntax-tests/source/Sass/example.sass | 76 +++++++++++++++++++ 2 files changed, 152 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Sass/example.sass create mode 100644 tests/syntax-tests/source/Sass/example.sass diff --git a/tests/syntax-tests/highlighted/Sass/example.sass b/tests/syntax-tests/highlighted/Sass/example.sass new file mode 100644 index 00000000..845a2b94 --- /dev/null +++ b/tests/syntax-tests/highlighted/Sass/example.sass @@ -0,0 +1,76 @@ +@import "fonts" + +$theme_dark: ( + "background-color": null +) + +$theme_main: ( + "text-size": 3em + "text-color": black + "text-shadow": #36ad 0px 0px 3px + "card-background": #d6f + "card-shadow": #11121212 0px 0px 2px 1px + "card-padding": 1rem + "card-margin": 0.5in + "image-width": 600px + "image-height": 100vh + "background-color": #dedbef + "i-ran-out-of-placeholders-for-units": ( + 1vw 100% 60pt + ) +) + +$current_theme: $theme_main + +@mixin themed() + $current_theme: $theme_main !global + @content + + @media (prefers-color-scheme: dark) + $current_theme: $theme_dark !global + @content + + .#{"dark"} & + $current_theme: $theme_dark !global + @content + +@function theme($variable) + @if map-has_key($current_theme, $variable) + @return map-get($current_theme, $variable) + @else + @error "Unknown theme variable: #{$variable}" + +body + @include themed + background-color: theme("background-color") + background-image: url("https://github.com/sharkdp/bat/raw/master/doc/logo-header.svg") + + + header[data-selectable="false"] + -webkit-user-select: none + -moz-user-select: none + -ms-user-select: /* CSS comment */ none + cursor: default !important // Sass comment + + + > div + border: #04f 1px solid + + &::after + content: "Pseudo" + color: #2f5f7f + box-sizing: border-box + +@keyframes rotate + 0% + transform: rotate(0deg) + 50% + transform: rotate(180deg) + 100% + transform: rotate(0rad) + +@font-face + font-family: "Example Font" + src: url(example.ttf) format("ttf") + src: local("Comic Sans MS") + diff --git a/tests/syntax-tests/source/Sass/example.sass b/tests/syntax-tests/source/Sass/example.sass new file mode 100644 index 00000000..27717008 --- /dev/null +++ b/tests/syntax-tests/source/Sass/example.sass @@ -0,0 +1,76 @@ +@import "fonts" + +$theme_dark: ( + "background-color": null +) + +$theme_main: ( + "text-size": 3em + "text-color": black + "text-shadow": #36ad 0px 0px 3px + "card-background": #d6f + "card-shadow": #11121212 0px 0px 2px 1px + "card-padding": 1rem + "card-margin": 0.5in + "image-width": 600px + "image-height": 100vh + "background-color": #dedbef + "i-ran-out-of-placeholders-for-units": ( + 1vw 100% 60pt + ) +) + +$current_theme: $theme_main + +@mixin themed() + $current_theme: $theme_main !global + @content + + @media (prefers-color-scheme: dark) + $current_theme: $theme_dark !global + @content + + .#{"dark"} & + $current_theme: $theme_dark !global + @content + +@function theme($variable) + @if map-has_key($current_theme, $variable) + @return map-get($current_theme, $variable) + @else + @error "Unknown theme variable: #{$variable}" + +body + @include themed + background-color: theme("background-color") + background-image: url("https://github.com/sharkdp/bat/raw/master/doc/logo-header.svg") + + + header[data-selectable="false"] + -webkit-user-select: none + -moz-user-select: none + -ms-user-select: /* CSS comment */ none + cursor: default !important // Sass comment + + + > div + border: #04f 1px solid + + &::after + content: "Pseudo" + color: #2f5f7f + box-sizing: border-box + +@keyframes rotate + 0% + transform: rotate(0deg) + 50% + transform: rotate(180deg) + 100% + transform: rotate(0rad) + +@font-face + font-family: "Example Font" + src: url(example.ttf) format("ttf") + src: local("Comic Sans MS") + From bb25111ca9ccb08d9d383b2bd7f816b3c6a105e7 Mon Sep 17 00:00:00 2001 From: Keith Hall Date: Wed, 14 Oct 2020 22:20:14 +0300 Subject: [PATCH 079/243] Improve Manpage syntax --- .../syntaxes/02_Extra/Manpage.sublime-syntax | 137 ++++++++-- assets/syntaxes/02_Extra/syntax_test_man.man | 103 ++++++++ .../highlighted/Manpage/bat-0.16.man | 243 ++++++++++++++++++ .../syntax-tests/source/Manpage/bat-0.16.man | 243 ++++++++++++++++++ 4 files changed, 702 insertions(+), 24 deletions(-) create mode 100644 assets/syntaxes/02_Extra/syntax_test_man.man create mode 100644 tests/syntax-tests/highlighted/Manpage/bat-0.16.man create mode 100644 tests/syntax-tests/source/Manpage/bat-0.16.man diff --git a/assets/syntaxes/02_Extra/Manpage.sublime-syntax b/assets/syntaxes/02_Extra/Manpage.sublime-syntax index e99c2497..121f6ab0 100644 --- a/assets/syntaxes/02_Extra/Manpage.sublime-syntax +++ b/assets/syntaxes/02_Extra/Manpage.sublime-syntax @@ -7,47 +7,136 @@ file_extensions: scope: source.man variables: - section_heading: '^\S.*$' + section_heading: '^(?!#)\S.*$' + command_line_option: '(--?[A-Za-z0-9][_A-Za-z0-9-]*)' contexts: + prototype: + # ignore syntax test lines + - match: '^#' + push: + - meta_scope: comment.syntax-test.man + - match: $\n? + pop: true main: - match: ^ push: first_line first_line: - - match: '([A-Z0-9_\-]+)(\()([^)]+)(\))' + - match: '([A-Z0-9_\-]+)(\()([^)]+)(\))\s*' captures: - 1: meta.preprocessor - 2: keyword.operator - 3: string.quoted.other - 4: keyword.operator + 1: meta.preprocessor.man + 2: keyword.operator.man + 3: string.quoted.other.man + 4: keyword.operator.man + push: + - match: (?:[\w'-]+|\s(?!\s)) + scope: markup.heading.title.man + - match: \s\s + pop: true + - match: '(?=\S)' + pop: true - match: '$' push: body body: - - match: '^(SYNOPSIS|SYNTAX|SINTASSI|SKŁADNIA|СИНТАКСИС|書式)' - push: Packages/C/C.sublime-syntax - scope: markup.heading - with_prototype: - - match: '(?={{section_heading}})' - pop: true + # English, ..., ..., ..., Russian, ... - - match: '^\S.*$' - scope: markup.heading + - match: '^(?:SYNOPSIS|SYNTAX|SINTASSI|SKŁADNIA|СИНТАКСИС|書式)' + scope: markup.heading.synopsis.man + embed: synopsis + escape: '(?={{section_heading}})' + + - match: '{{section_heading}}' + scope: markup.heading.other.man + embed: options # some man pages put command line options under the description heading + escape: '(?={{section_heading}})' + + - include: function-call + + function-call: - match: '\b([A-Za-z0-9_\-]+)(\()([^)]*)(\))' captures: - 1: entity.name.function - 2: keyword.operator - 3: constant.numeric - 4: keyword.operator + 1: entity.name.function.man + 2: keyword.operator.man + 3: constant.numeric.man + 4: keyword.operator.man + options: # command-line options like --option=value, --some-flag, or -x - - match: '(?:[^a-zA-Z0-9_-]|^|\s)(--?[A-Za-z0-9][A-Za-z0-9-]*)(?:(=)?("?)([A-Za-z0-9]+)("?))?' + - match: '^[ ]{7}(?=-)' + push: expect-command-line-option + - match: '(?:[^a-zA-Z0-9_-]|^|\s){{command_line_option}}' captures: - 1: entity.name - 2: keyword.operator - 3: punctuation.definition.string.begin - 4: variable.parameter - 3: punctuation.definition.string.end + 1: entity.name.command-line-option + push: + - match: '=' + scope: keyword.operator.man + set: + - match: '[^],.() ]+' + scope: variable.parameter.man + pop: true + - match: $ + pop: true + - match: '' + pop: true + - include: function-call + + expect-command-line-option: + - match: '[A-Za-z0-9-]+' + scope: entity.name.command-line-option.man + - match: '(\[)(=)' + captures: + 2: keyword.operator.man + push: expect-parameter + - match: '\[' + push: + - meta_scope: entity.name.command-line-option.man + - match: '\]' + pop: true + - match: '=' + scope: keyword.operator.man + push: expect-parameter + - match: (?=.*\.) + pop: true + - match: '\s' + push: expect-parameter + - match: '(,)\s*' + captures: + 1: punctuation.separator.man + - match: $|(?=\]) + pop: true + + expect-parameter: + - match: '[A-Za-z0-9-]+' + scope: variable.parameter.man + - match: \| + scope: keyword.operator.logical.man + - match: '$|(?=[],]|{{command_line_option}})' + pop: true + + synopsis: + #- include: scope:source.c + - match: \[ + scope: punctuation.section.brackets.begin.man + push: command-line-option-or-pipe + - include: options + + command-line-option-or-pipe: + - match: (\|)\s* + captures: + 1: keyword.operator.logical.man + #- match: (?={{command_line_option}}) + - match: (?=-) + push: + - match: (?=\s*\|) + pop: true + - include: expect-command-line-option + - match: \] + scope: punctuation.section.brackets.end.man + pop: true + - match: \[ + scope: punctuation.section.brackets.begin.man + push: command-line-option-or-pipe diff --git a/assets/syntaxes/02_Extra/syntax_test_man.man b/assets/syntaxes/02_Extra/syntax_test_man.man new file mode 100644 index 00000000..54c052a5 --- /dev/null +++ b/assets/syntaxes/02_Extra/syntax_test_man.man @@ -0,0 +1,103 @@ +# SYNTAX TEST "Manpage.sublime-syntax" +SOMETHING(8) System Manager's Manual SOMETHING(8) +# ^^^^^ meta.preprocessor +# ^^^^^^^^^^^^^^^^^^^^^^^ markup.heading.title +# ^^^^^^^ meta.preprocessor + +NAME +#^^^ markup.heading.title + example - do something useful + +SYNOPSIS + example [options] [--home DIR] [--shell SHELL] [--no-create-home] +# ^ punctuation.section.brackets.begin +# ^^^^^^ entity.name.command-line-option +# ^^^ variable.parameter +# ^ punctuation.section.brackets.end +# ^ punctuation.section.brackets.begin +# ^^^^^^^ entity.name.command-line-option +# ^^^^^ variable.parameter +# ^ punctuation.section.brackets.end +# ^ punctuation.section.brackets.begin +# ^^^^^^^^^^^^^^^^ entity.name.command-line-option +# ^ punctuation.section.brackets.end + + example --system [options] +# ^^^^^^^^ entity.name + + COMMON OPTIONS + [--quiet] [--debug] [--help|-h] [--version] [--conf FILE] + +DESCRIPTION + example does something useful in relation to the command line options + and configuration information in /etc/example.conf. + +OPTIONS + --conf FILE +# ^^^^^^ entity.name.command-line-option +#^^^^^^ - variable - entity - markup +# ^^^^ variable.parameter + Use FILE instead of /etc/example.conf. +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - variable - entity + + --disabled-login + Do not run passwd to set the password. The user won't be able + to use her account until the password is set. + + --disabled-password + Like --disabled-login, but logins are still possible (for exam- +# ^^^^^^^^^^^^^^^^ entity.name +#^^^^^^^^^^^^^^^^^^ - entity - variable - markup +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - entity - variable - markup + ple using SSH RSA keys) but not using password authentication. + + --help Display brief instructions. +# ^^^^^^ entity.name.command-line-option +# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - variable.parameter + + --home DIR +# ^^^^^^ entity.name.command-line-option +# ^^^ variable.parameter +# ^ - variable - entity - markup + Use DIR as the user's home directory, rather than the default + specified by the configuration file. If the directory does not + exist, it is created and skeleton files are copied. + + --[no-]signed, --signed=(true|false|if-asked) +# ^^^^^^^^^^^^^ entity.name.command-line-option +# ^ punctuation.separator +# ^^^^^^^^ entity.name.command-line-option +# ^ keyword.operator +# ^ - variable +# ^^^^ variable.parameter +# ^ keyword.operator.logical +# ^^^^^ variable.parameter +# ^ keyword.operator.logical +# ^^^^^^^^ variable.parameter +# ^ - variable + --no-recurse-submodules, --recurse-submodules=check|on-demand|only|no +# ^^^^^^^^^^^^^^^^^^^^^^^ entity.name.command-line-option +# ^ punctuation.separator +# ^^^^^^^^^^^^^^^^^^^^ entity.name.command-line-option +# ^ keyword.operator +# ^^^^^ variable.parameter +# ^ keyword.operator.logical +# ^^^^^^^^^ variable.parameter +# ^ keyword.operator.logical +# ^^^^ variable.parameter +# ^ keyword.operator.logical +# ^^ variable.parameter + May be used to make sure all submodule commits used by the + + -c, -C NUM, --context[=NUM] +# ^^ entity.name.command-line-option +# ^ punctuation.separator +# ^^ entity.name.command-line-option +# ^^^ variable.parameter +# ^ punctuation.separator +# ^^^^^^^^^ entity.name.command-line-option +# ^^^^^^^ - entity.name +# ^ keyword.operator +# ^^^ variable.parameter +# ^^ - variable + output NUM (default 3) lines of copied context diff --git a/tests/syntax-tests/highlighted/Manpage/bat-0.16.man b/tests/syntax-tests/highlighted/Manpage/bat-0.16.man new file mode 100644 index 00000000..921fe261 --- /dev/null +++ b/tests/syntax-tests/highlighted/Manpage/bat-0.16.man @@ -0,0 +1,243 @@ +BAT(1) General Commands Manual BAT(1) + +NAME + bat - a cat(1) clone with syntax highlighting and Git integration. + +USAGE + bat [OPTIONS] [FILE]... + + bat cache [CACHE-OPTIONS] [--build|--clear] + +DESCRIPTION + bat prints the syntax-highlighted content of a collection of FILEs to + the terminal. If no FILE is specified, or when FILE is '-', it reads + from standard input. + + bat supports a large number of programming and markup languages. It + also communicates with git(1) to show modifications with respect to the + git index. bat automatically pipes its output through a pager (by de‐ + fault: less). + + Whenever the output of bat goes to a non-interactive terminal, i.e. + when the output is piped into another process or into a file, bat will + act as a drop-in replacement for cat(1) and fall back to printing the + plain file contents. + +OPTIONS + General remarks: Command-line options like '-l'/'--language' that take + values can be specified as either '--language value', '--lan‐ + guage=value', '-l value' or '-lvalue'. + + -A, --show-all + + Show non-printable characters like space, tab or newline. Use + '--tabs' to control the width of the tab-placeholders. + + -p, --plain + + Only show plain style, no decorations. This is an alias for + '--style=plain'. When '-p' is used twice ('-pp'), it also dis‐ + ables automatic paging (alias for '--style=plain + --pager=never'). + + -l, --language <language> + + Explicitly set the language for syntax highlighting. The lan‐ + guage can be specified as a name (like 'C++' or 'LaTeX') or pos‐ + sible file extension (like 'cpp', 'hpp' or 'md'). Use + '--list-languages' to show all supported language names and file + extensions. + + -H, --highlight-line ... + + Highlight the specified line ranges with a different background + color For example: + + --highlight-line 40 + highlights line 40 + + --highlight-line 30:40 + highlights lines 30 to 40 + + --highlight-line :40 + highlights lines 1 to 40 + + --highlight-line 40: + highlights lines 40 to the end of the file + + --tabs <T> + + Set the tab width to T spaces. Use a width of 0 to pass tabs + through directly + + --wrap <mode> + + Specify the text-wrapping mode (*auto*, never, character). The + '--terminal-width' option can be used in addition to control the + output width. + + --terminal-width <width> + + Explicitly set the width of the terminal instead of determining + it automatically. If prefixed with '+' or '-', the value will be + treated as an offset to the actual terminal width. See also: + '--wrap'. + + -n, --number + + Only show line numbers, no other decorations. This is an alias + for '--style=numbers' + + --color <when> + + Specify when to use colored output. The automatic mode only en‐ + ables colors if an interactive terminal is detected. Possible + values: *auto*, never, always. + + --italic-text <when> + + Specify when to use ANSI sequences for italic text in the out‐ + put. Possible values: always, *never*. + + --decorations <when> + + Specify when to use the decorations that have been specified via + '--style'. The automatic mode only enables decorations if an in‐ + teractive terminal is detected. Possible values: *auto*, never, + always. + + -f, --force-colorization + + Alias for '--decorations=always --color=always'. This is useful + if the output of bat is piped to another program, but you want + to keep the colorization/decorations. + + --paging <when> + + Specify when to use the pager. To disable the pager, use '--pag‐ + ing=never' or its alias, -P. To disable the pager permanently, + set BAT_PAGER to an empty string. To control which pager is + used, see the '--pager' option. Possible values: *auto*, never, + always. + + --pager <command> + + Determine which pager is used. This option will override the + PAGER and BAT_PAGER environment variables. The default pager is + 'less'. To control when the pager is used, see the '--paging' + option. Example: '--pager "less -RF"'. + + -m, --map-syntax ... + + Map a glob pattern to an existing syntax name. The glob pattern + is matched on the full path and the filename. For example, to + highlight *.build files with the Python syntax, use -m + '*.build:Python'. To highlight files named '.myignore' with the + Git Ignore syntax, use -m '.myignore:Git Ignore'. + + --theme <theme> + + Set the theme for syntax highlighting. Use '--list-themes' to + see all available themes. To set a default theme, add the + '--theme="..."' option to the configuration file or export the + BAT_THEME environment variable (e.g.: export BAT_THEME="..."). + + --list-themes + + Display a list of supported themes for syntax highlighting. + + --style <style-components> + + Configure which elements (line numbers, file headers, grid bor‐ + ders, Git modifications, ..) to display in addition to the file + contents. The argument is a comma-separated list of components + to display (e.g. 'numbers,changes,grid') or a pre-defined style + ('full'). To set a default style, add the '--style=".."' option + to the configuration file or export the BAT_STYLE environment + variable (e.g.: export BAT_STYLE=".."). Possible values: *auto*, + full, plain, changes, header, grid, numbers, snip. + + -r, --line-range ... + + Only print the specified range of lines for each file. For exam‐ + ple: + + --line-range 30:40 + prints lines 30 to 40 + + --line-range :40 + prints lines 1 to 40 + + --line-range 40: + prints lines 40 to the end of the file + + -L, --list-languages + + Display a list of supported languages for syntax highlighting. + + -u, --unbuffered + + This option exists for POSIX-compliance reasons ('u' is for 'un‐ + buffered'). The output is always unbuffered - this option is + simply ignored. + + -h, --help + + Print this help message. + + -V, --version + + Show version information. + +POSITIONAL ARGUMENTS + ... + + Files to print and concatenate. Use a dash ('-') or no argument + at all to read from standard input. + +SUBCOMMANDS + cache - Modify the syntax-definition and theme cache. + +FILES + bat can also be customized with a configuration file. The location of + the file is dependent on your operating system. To get the default path + for your system, call: + + bat --config-file + + Alternatively, you can use the BAT_CONFIG_PATH environment variable to + point bat to a non-default location of the configuration file. + +ADDING CUSTOM LANGUAGES + bat supports Sublime Text .sublime-syntax language files, and can be + customized to add additional languages to your local installation. To + do this, add the .sublime-snytax language files to `$(bat --config- + dir)/syntaxes` and run `bat cache --build`. + + Example: + + mkdir -p "$(bat --config-dir)/syntaxes" + cd "$(bat --config-dir)/syntaxes" + + # Put new '.sublime-syntax' language definition files + # in this folder (or its subdirectories), for example: + git clone https://github.com/tellnobody1/sublime-purescript-syntax + + # And then build the cache. + bat cache --build + + Once the cache is built, the new language will be visible in `bat + --list-languages`. + If you ever want to remove the custom languages, you can clear the + cache with `bat cache --clear`. + +ADDING CUSTOM THEMES + Similarly to custom languages, bat supports Sublime Text .tmTheme + themes. These can be installed to `$(bat --config-dir)/themes`, and + are added to the cache with `bat cache --build`. + +MORE INFORMATION + For more information and up-to-date documentation, visit the bat repo: + https://github.com/sharkdp/bat + + BAT(1) diff --git a/tests/syntax-tests/source/Manpage/bat-0.16.man b/tests/syntax-tests/source/Manpage/bat-0.16.man new file mode 100644 index 00000000..05281dde --- /dev/null +++ b/tests/syntax-tests/source/Manpage/bat-0.16.man @@ -0,0 +1,243 @@ +BAT(1) General Commands Manual BAT(1) + +NAME + bat - a cat(1) clone with syntax highlighting and Git integration. + +USAGE + bat [OPTIONS] [FILE]... + + bat cache [CACHE-OPTIONS] [--build|--clear] + +DESCRIPTION + bat prints the syntax-highlighted content of a collection of FILEs to + the terminal. If no FILE is specified, or when FILE is '-', it reads + from standard input. + + bat supports a large number of programming and markup languages. It + also communicates with git(1) to show modifications with respect to the + git index. bat automatically pipes its output through a pager (by de‐ + fault: less). + + Whenever the output of bat goes to a non-interactive terminal, i.e. + when the output is piped into another process or into a file, bat will + act as a drop-in replacement for cat(1) and fall back to printing the + plain file contents. + +OPTIONS + General remarks: Command-line options like '-l'/'--language' that take + values can be specified as either '--language value', '--lan‐ + guage=value', '-l value' or '-lvalue'. + + -A, --show-all + + Show non-printable characters like space, tab or newline. Use + '--tabs' to control the width of the tab-placeholders. + + -p, --plain + + Only show plain style, no decorations. This is an alias for + '--style=plain'. When '-p' is used twice ('-pp'), it also dis‐ + ables automatic paging (alias for '--style=plain + --pager=never'). + + -l, --language + + Explicitly set the language for syntax highlighting. The lan‐ + guage can be specified as a name (like 'C++' or 'LaTeX') or pos‐ + sible file extension (like 'cpp', 'hpp' or 'md'). Use + '--list-languages' to show all supported language names and file + extensions. + + -H, --highlight-line ... + + Highlight the specified line ranges with a different background + color For example: + + --highlight-line 40 + highlights line 40 + + --highlight-line 30:40 + highlights lines 30 to 40 + + --highlight-line :40 + highlights lines 1 to 40 + + --highlight-line 40: + highlights lines 40 to the end of the file + + --tabs + + Set the tab width to T spaces. Use a width of 0 to pass tabs + through directly + + --wrap + + Specify the text-wrapping mode (*auto*, never, character). The + '--terminal-width' option can be used in addition to control the + output width. + + --terminal-width + + Explicitly set the width of the terminal instead of determining + it automatically. If prefixed with '+' or '-', the value will be + treated as an offset to the actual terminal width. See also: + '--wrap'. + + -n, --number + + Only show line numbers, no other decorations. This is an alias + for '--style=numbers' + + --color + + Specify when to use colored output. The automatic mode only en‐ + ables colors if an interactive terminal is detected. Possible + values: *auto*, never, always. + + --italic-text + + Specify when to use ANSI sequences for italic text in the out‐ + put. Possible values: always, *never*. + + --decorations + + Specify when to use the decorations that have been specified via + '--style'. The automatic mode only enables decorations if an in‐ + teractive terminal is detected. Possible values: *auto*, never, + always. + + -f, --force-colorization + + Alias for '--decorations=always --color=always'. This is useful + if the output of bat is piped to another program, but you want + to keep the colorization/decorations. + + --paging + + Specify when to use the pager. To disable the pager, use '--pag‐ + ing=never' or its alias, -P. To disable the pager permanently, + set BAT_PAGER to an empty string. To control which pager is + used, see the '--pager' option. Possible values: *auto*, never, + always. + + --pager + + Determine which pager is used. This option will override the + PAGER and BAT_PAGER environment variables. The default pager is + 'less'. To control when the pager is used, see the '--paging' + option. Example: '--pager "less -RF"'. + + -m, --map-syntax ... + + Map a glob pattern to an existing syntax name. The glob pattern + is matched on the full path and the filename. For example, to + highlight *.build files with the Python syntax, use -m + '*.build:Python'. To highlight files named '.myignore' with the + Git Ignore syntax, use -m '.myignore:Git Ignore'. + + --theme + + Set the theme for syntax highlighting. Use '--list-themes' to + see all available themes. To set a default theme, add the + '--theme="..."' option to the configuration file or export the + BAT_THEME environment variable (e.g.: export BAT_THEME="..."). + + --list-themes + + Display a list of supported themes for syntax highlighting. + + --style + + Configure which elements (line numbers, file headers, grid bor‐ + ders, Git modifications, ..) to display in addition to the file + contents. The argument is a comma-separated list of components + to display (e.g. 'numbers,changes,grid') or a pre-defined style + ('full'). To set a default style, add the '--style=".."' option + to the configuration file or export the BAT_STYLE environment + variable (e.g.: export BAT_STYLE=".."). Possible values: *auto*, + full, plain, changes, header, grid, numbers, snip. + + -r, --line-range ... + + Only print the specified range of lines for each file. For exam‐ + ple: + + --line-range 30:40 + prints lines 30 to 40 + + --line-range :40 + prints lines 1 to 40 + + --line-range 40: + prints lines 40 to the end of the file + + -L, --list-languages + + Display a list of supported languages for syntax highlighting. + + -u, --unbuffered + + This option exists for POSIX-compliance reasons ('u' is for 'un‐ + buffered'). The output is always unbuffered - this option is + simply ignored. + + -h, --help + + Print this help message. + + -V, --version + + Show version information. + +POSITIONAL ARGUMENTS + ... + + Files to print and concatenate. Use a dash ('-') or no argument + at all to read from standard input. + +SUBCOMMANDS + cache - Modify the syntax-definition and theme cache. + +FILES + bat can also be customized with a configuration file. The location of + the file is dependent on your operating system. To get the default path + for your system, call: + + bat --config-file + + Alternatively, you can use the BAT_CONFIG_PATH environment variable to + point bat to a non-default location of the configuration file. + +ADDING CUSTOM LANGUAGES + bat supports Sublime Text .sublime-syntax language files, and can be + customized to add additional languages to your local installation. To + do this, add the .sublime-snytax language files to `$(bat --config- + dir)/syntaxes` and run `bat cache --build`. + + Example: + + mkdir -p "$(bat --config-dir)/syntaxes" + cd "$(bat --config-dir)/syntaxes" + + # Put new '.sublime-syntax' language definition files + # in this folder (or its subdirectories), for example: + git clone https://github.com/tellnobody1/sublime-purescript-syntax + + # And then build the cache. + bat cache --build + + Once the cache is built, the new language will be visible in `bat + --list-languages`. + If you ever want to remove the custom languages, you can clear the + cache with `bat cache --clear`. + +ADDING CUSTOM THEMES + Similarly to custom languages, bat supports Sublime Text .tmTheme + themes. These can be installed to `$(bat --config-dir)/themes`, and + are added to the cache with `bat cache --build`. + +MORE INFORMATION + For more information and up-to-date documentation, visit the bat repo: + https://github.com/sharkdp/bat + + BAT(1) From 3539d3e72da3fb0042e8c05a196d1f50a408c3cd Mon Sep 17 00:00:00 2001 From: sharkdp Date: Wed, 14 Oct 2020 22:49:38 +0200 Subject: [PATCH 080/243] Add Manpage syntax regression test for select(2) --- .../highlighted/Manpage/select-2.man | 330 ++++++++++++++++++ .../syntax-tests/source/Manpage/select-2.man | 330 ++++++++++++++++++ 2 files changed, 660 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Manpage/select-2.man create mode 100644 tests/syntax-tests/source/Manpage/select-2.man diff --git a/tests/syntax-tests/highlighted/Manpage/select-2.man b/tests/syntax-tests/highlighted/Manpage/select-2.man new file mode 100644 index 00000000..5ca67908 --- /dev/null +++ b/tests/syntax-tests/highlighted/Manpage/select-2.man @@ -0,0 +1,330 @@ +SELECT(2) Linux Programmer's Manual SELECT(2) + +NAME + select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO - synchronous I/O multiplexing + +SYNOPSIS + #include <sys/select.h> + + int select(int nfds, fd_set *readfds, fd_set *writefds, + fd_set *exceptfds, struct timeval *timeout); + + void FD_CLR(int fd, fd_set *set); + int FD_ISSET(int fd, fd_set *set); + void FD_SET(int fd, fd_set *set); + void FD_ZERO(fd_set *set); + + int pselect(int nfds, fd_set *readfds, fd_set *writefds, + fd_set *exceptfds, const struct timespec *timeout, + const sigset_t *sigmask); + + Feature Test Macro Requirements for glibc (see feature_test_macros(7)): + + pselect(): _POSIX_C_SOURCE >= 200112L + +DESCRIPTION + select() allows a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become + "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to + perform a corresponding I/O operation (e.g., read(2), or a sufficiently small write(2)) without blocking. + + select() can monitor only file descriptors numbers that are less than FD_SETSIZE; poll(2) and epoll(7) do not have this limi‐ + tation. See BUGS. + + File descriptor sets + The principal arguments of select() are three "sets" of file descriptors (declared with the type fd_set), which allow the + caller to wait for three classes of events on the specified set of file descriptors. Each of the fd_set arguments may be + specified as NULL if no file descriptors are to be watched for the corresponding class of events. + + Note well: Upon return, each of the file descriptor sets is modified in place to indicate which file descriptors are currently + "ready". Thus, if using select() within a loop, the sets must be reinitialized before each call. The implementation of the + fd_set arguments as value-result arguments is a design error that is avoided in poll(2) and epoll(7). + + The contents of a file descriptor set can be manipulated using the following macros: + + FD_ZERO() + This macro clears (removes all file descriptors from) set. It should be employed as the first step in initializing a + file descriptor set. + + FD_SET() + This macro adds the file descriptor fd to set. Adding a file descriptor that is already present in the set is a no-op, + and does not produce an error. + + FD_CLR() + This macro removes the file descriptor fd from set. Removing a file descriptor that is not present in the set is a no- + op, and does not produce an error. + + FD_ISSET() + select() modifies the contents of the sets according to the rules described below. After calling select(), the FD_IS‐ + SET() macro can be used to test if a file descriptor is still present in a set. FD_ISSET() returns nonzero if the file + descriptor fd is present in set, and zero if it is not. + + Arguments + The arguments of select() are as follows: + + readfds + The file descriptors in this set are watched to see if they are ready for reading. A file descriptor is ready for + reading if a read operation will not block; in particular, a file descriptor is also ready on end-of-file. + + After select() has returned, readfds will be cleared of all file descriptors except for those that are ready for read‐ + ing. + + writefds + The file descriptors in this set are watched to see if they are ready for writing. A file descriptor is ready for + writing if a write operation will not block. However, even if a file descriptor indicates as writable, a large write + may still block. + + After select() has returned, writefds will be cleared of all file descriptors except for those that are ready for writ‐ + ing. + + exceptfds + The file descriptors in this set are watched for "exceptional conditions". For examples of some exceptional condi‐ + tions, see the discussion of POLLPRI in poll(2). + + After select() has returned, exceptfds will be cleared of all file descriptors except for those for which an excep‐ + tional condition has occurred. + + nfds This argument should be set to the highest-numbered file descriptor in any of the three sets, plus 1. The indicated + file descriptors in each set are checked, up to this limit (but see BUGS). + + timeout + The timeout argument is a timeval structure (shown below) that specifies the interval that select() should block wait‐ + ing for a file descriptor to become ready. The call will block until either: + + • a file descriptor becomes ready; + + • the call is interrupted by a signal handler; or + + • the timeout expires. + + Note that the timeout interval will be rounded up to the system clock granularity, and kernel scheduling delays mean + that the blocking interval may overrun by a small amount. + + If both fields of the timeval structure are zero, then select() returns immediately. (This is useful for polling.) + + If timeout is specified as NULL, select() blocks indefinitely waiting for a file descriptor to become ready. + + pselect() + The pselect() system call allows an application to safely wait until either a file descriptor becomes ready or until a signal + is caught. + + The operation of select() and pselect() is identical, other than these three differences: + + • select() uses a timeout that is a struct timeval (with seconds and microseconds), while pselect() uses a struct timespec + (with seconds and nanoseconds). + + • select() may update the timeout argument to indicate how much time was left. pselect() does not change this argument. + + • select() has no sigmask argument, and behaves as pselect() called with NULL sigmask. + + sigmask is a pointer to a signal mask (see sigprocmask(2)); if it is not NULL, then pselect() first replaces the current sig‐ + nal mask by the one pointed to by sigmask, then does the "select" function, and then restores the original signal mask. (If + sigmask is NULL, the signal mask is not modified during the pselect() call.) + + Other than the difference in the precision of the timeout argument, the following pselect() call: + + ready = pselect(nfds, &readfds, &writefds, &exceptfds, + timeout, &sigmask); + + is equivalent to atomically executing the following calls: + + sigset_t origmask; + + pthread_sigmask(SIG_SETMASK, &sigmask, &origmask); + ready = select(nfds, &readfds, &writefds, &exceptfds, timeout); + pthread_sigmask(SIG_SETMASK, &origmask, NULL); + + The reason that pselect() is needed is that if one wants to wait for either a signal or for a file descriptor to become ready, + then an atomic test is needed to prevent race conditions. (Suppose the signal handler sets a global flag and returns. Then a + test of this global flag followed by a call of select() could hang indefinitely if the signal arrived just after the test but + just before the call. By contrast, pselect() allows one to first block signals, handle the signals that have come in, then + call pselect() with the desired sigmask, avoiding the race.) + + The timeout + The timeout argument for select() is a structure of the following type: + + struct timeval { + time_t tv_sec; /* seconds */ + suseconds_t tv_usec; /* microseconds */ + }; + + The corresponding argument for pselect() has the following type: + + struct timespec { + time_t tv_sec; /* seconds */ + long tv_nsec; /* nanoseconds */ + }; + + On Linux, select() modifies timeout to reflect the amount of time not slept; most other implementations do not do this. + (POSIX.1 permits either behavior.) This causes problems both when Linux code which reads timeout is ported to other operating + systems, and when code is ported to Linux that reuses a struct timeval for multiple select()s in a loop without reinitializing + it. Consider timeout to be undefined after select() returns. + +RETURN VALUE + On success, select() and pselect() return the number of file descriptors contained in the three returned descriptor sets (that + is, the total number of bits that are set in readfds, writefds, exceptfds). The return value may be zero if the timeout ex‐ + pired before any file descriptors became ready. + + On error, -1 is returned, and errno is set to indicate the error; the file descriptor sets are unmodified, and timeout becomes + undefined. + +ERRORS + EBADF An invalid file descriptor was given in one of the sets. (Perhaps a file descriptor that was already closed, or one on + which an error has occurred.) However, see BUGS. + + EINTR A signal was caught; see signal(7). + + EINVAL nfds is negative or exceeds the RLIMIT_NOFILE resource limit (see getrlimit(2)). + + EINVAL The value contained within timeout is invalid. + + ENOMEM Unable to allocate memory for internal tables. + +VERSIONS + pselect() was added to Linux in kernel 2.6.16. Prior to this, pselect() was emulated in glibc (but see BUGS). + +CONFORMING TO + select() conforms to POSIX.1-2001, POSIX.1-2008, and 4.4BSD (select() first appeared in 4.2BSD). Generally portable to/from + non-BSD systems supporting clones of the BSD socket layer (including System V variants). However, note that the System V + variant typically sets the timeout variable before returning, but the BSD variant does not. + + pselect() is defined in POSIX.1g, and in POSIX.1-2001 and POSIX.1-2008. + +NOTES + An fd_set is a fixed size buffer. Executing FD_CLR() or FD_SET() with a value of fd that is negative or is equal to or larger + than FD_SETSIZE will result in undefined behavior. Moreover, POSIX requires fd to be a valid file descriptor. + + The operation of select() and pselect() is not affected by the O_NONBLOCK flag. + + On some other UNIX systems, select() can fail with the error EAGAIN if the system fails to allocate kernel-internal resources, + rather than ENOMEM as Linux does. POSIX specifies this error for poll(2), but not for select(). Portable programs may wish + to check for EAGAIN and loop, just as with EINTR. + + The self-pipe trick + On systems that lack pselect(), reliable (and more portable) signal trapping can be achieved using the self-pipe trick. In + this technique, a signal handler writes a byte to a pipe whose other end is monitored by select() in the main program. (To + avoid possibly blocking when writing to a pipe that may be full or reading from a pipe that may be empty, nonblocking I/O is + used when reading from and writing to the pipe.) + + Emulating usleep(3) + Before the advent of usleep(3), some code employed a call to select() with all three sets empty, nfds zero, and a non-NULL + timeout as a fairly portable way to sleep with subsecond precision. + + Correspondence between select() and poll() notifications + Within the Linux kernel source, we find the following definitions which show the correspondence between the readable, + writable, and exceptional condition notifications of select() and the event notifications provided by poll(2) and epoll(7): + + #define POLLIN_SET (EPOLLRDNORM | EPOLLRDBAND | EPOLLIN | + EPOLLHUP | EPOLLERR) + /* Ready for reading */ + #define POLLOUT_SET (EPOLLWRBAND | EPOLLWRNORM | EPOLLOUT | + EPOLLERR) + /* Ready for writing */ + #define POLLEX_SET (EPOLLPRI) + /* Exceptional condition */ + + Multithreaded applications + If a file descriptor being monitored by select() is closed in another thread, the result is unspecified. On some UNIX sys‐ + tems, select() unblocks and returns, with an indication that the file descriptor is ready (a subsequent I/O operation will + likely fail with an error, unless another process reopens file descriptor between the time select() returned and the I/O oper‐ + ation is performed). On Linux (and some other systems), closing the file descriptor in another thread has no effect on se‐ + lect(). In summary, any application that relies on a particular behavior in this scenario must be considered buggy. + + C library/kernel differences + The Linux kernel allows file descriptor sets of arbitrary size, determining the length of the sets to be checked from the + value of nfds. However, in the glibc implementation, the fd_set type is fixed in size. See also BUGS. + + The pselect() interface described in this page is implemented by glibc. The underlying Linux system call is named pselect6(). + This system call has somewhat different behavior from the glibc wrapper function. + + The Linux pselect6() system call modifies its timeout argument. However, the glibc wrapper function hides this behavior by + using a local variable for the timeout argument that is passed to the system call. Thus, the glibc pselect() function does + not modify its timeout argument; this is the behavior required by POSIX.1-2001. + + The final argument of the pselect6() system call is not a sigset_t * pointer, but is instead a structure of the form: + + struct { + const kernel_sigset_t *ss; /* Pointer to signal set */ + size_t ss_len; /* Size (in bytes) of object + pointed to by 'ss' */ + }; + + This allows the system call to obtain both a pointer to the signal set and its size, while allowing for the fact that most ar‐ + chitectures support a maximum of 6 arguments to a system call. See sigprocmask(2) for a discussion of the difference between + the kernel and libc notion of the signal set. + + Historical glibc details + Glibc 2.0 provided an incorrect version of pselect() that did not take a sigmask argument. + + In glibc versions 2.1 to 2.2.1, one must define _GNU_SOURCE in order to obtain the declaration of pselect() from . + +BUGS + POSIX allows an implementation to define an upper limit, advertised via the constant FD_SETSIZE, on the range of file descrip‐ + tors that can be specified in a file descriptor set. The Linux kernel imposes no fixed limit, but the glibc implementation + makes fd_set a fixed-size type, with FD_SETSIZE defined as 1024, and the FD_*() macros operating according to that limit. To + monitor file descriptors greater than 1023, use poll(2) or epoll(7) instead. + + According to POSIX, select() should check all specified file descriptors in the three file descriptor sets, up to the limit + nfds-1. However, the current implementation ignores any file descriptor in these sets that is greater than the maximum file + descriptor number that the process currently has open. According to POSIX, any such file descriptor that is specified in one + of the sets should result in the error EBADF. + + Starting with version 2.1, glibc provided an emulation of pselect() that was implemented using sigprocmask(2) and select(). + This implementation remained vulnerable to the very race condition that pselect() was designed to prevent. Modern versions of + glibc use the (race-free) pselect() system call on kernels where it is provided. + + On Linux, select() may report a socket file descriptor as "ready for reading", while nevertheless a subsequent read blocks. + This could for example happen when data has arrived but upon examination has the wrong checksum and is discarded. There may + be other circumstances in which a file descriptor is spuriously reported as ready. Thus it may be safer to use O_NONBLOCK on + sockets that should not block. + + On Linux, select() also modifies timeout if the call is interrupted by a signal handler (i.e., the EINTR error return). This + is not permitted by POSIX.1. The Linux pselect() system call has the same behavior, but the glibc wrapper hides this behavior + by internally copying the timeout to a local variable and passing that variable to the system call. + +EXAMPLES + #include  + #include  + #include  + + int + main(void) + { + fd_set rfds; + struct timeval tv; + int retval; + + /* Watch stdin (fd 0) to see when it has input. */ + + FD_ZERO(&rfds); + FD_SET(0, &rfds); + + /* Wait up to five seconds. */ + + tv.tv_sec = 5; + tv.tv_usec = 0; + + retval = select(1, &rfds, NULL, NULL, &tv); + /* Don't rely on the value of tv now! */ + + if (retval == -1) + perror("select()"); + else if (retval) + printf("Data is available now.\n"); + /* FD_ISSET(0, &rfds) will be true. */ + else + printf("No data within five seconds.\n"); + + exit(EXIT_SUCCESS); + } + +SEE ALSO + accept(2), connect(2), poll(2), read(2), recv(2), restart_syscall(2), send(2), sigprocmask(2), write(2), epoll(7), time(7) + + For a tutorial with discussion and examples, see select_tut(2). + +COLOPHON + This page is part of release 5.08 of the Linux man-pages project. A description of the project, information about reporting + bugs, and the latest version of this page, can be found at https://www.kernel.org/doc/man-pages/. + +Linux 2020-04-11 SELECT(2) diff --git a/tests/syntax-tests/source/Manpage/select-2.man b/tests/syntax-tests/source/Manpage/select-2.man new file mode 100644 index 00000000..c11e411b --- /dev/null +++ b/tests/syntax-tests/source/Manpage/select-2.man @@ -0,0 +1,330 @@ +SELECT(2) Linux Programmer's Manual SELECT(2) + +NAME + select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO - synchronous I/O multiplexing + +SYNOPSIS + #include + + int select(int nfds, fd_set *readfds, fd_set *writefds, + fd_set *exceptfds, struct timeval *timeout); + + void FD_CLR(int fd, fd_set *set); + int FD_ISSET(int fd, fd_set *set); + void FD_SET(int fd, fd_set *set); + void FD_ZERO(fd_set *set); + + int pselect(int nfds, fd_set *readfds, fd_set *writefds, + fd_set *exceptfds, const struct timespec *timeout, + const sigset_t *sigmask); + + Feature Test Macro Requirements for glibc (see feature_test_macros(7)): + + pselect(): _POSIX_C_SOURCE >= 200112L + +DESCRIPTION + select() allows a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become + "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to + perform a corresponding I/O operation (e.g., read(2), or a sufficiently small write(2)) without blocking. + + select() can monitor only file descriptors numbers that are less than FD_SETSIZE; poll(2) and epoll(7) do not have this limi‐ + tation. See BUGS. + + File descriptor sets + The principal arguments of select() are three "sets" of file descriptors (declared with the type fd_set), which allow the + caller to wait for three classes of events on the specified set of file descriptors. Each of the fd_set arguments may be + specified as NULL if no file descriptors are to be watched for the corresponding class of events. + + Note well: Upon return, each of the file descriptor sets is modified in place to indicate which file descriptors are currently + "ready". Thus, if using select() within a loop, the sets must be reinitialized before each call. The implementation of the + fd_set arguments as value-result arguments is a design error that is avoided in poll(2) and epoll(7). + + The contents of a file descriptor set can be manipulated using the following macros: + + FD_ZERO() + This macro clears (removes all file descriptors from) set. It should be employed as the first step in initializing a + file descriptor set. + + FD_SET() + This macro adds the file descriptor fd to set. Adding a file descriptor that is already present in the set is a no-op, + and does not produce an error. + + FD_CLR() + This macro removes the file descriptor fd from set. Removing a file descriptor that is not present in the set is a no- + op, and does not produce an error. + + FD_ISSET() + select() modifies the contents of the sets according to the rules described below. After calling select(), the FD_IS‐ + SET() macro can be used to test if a file descriptor is still present in a set. FD_ISSET() returns nonzero if the file + descriptor fd is present in set, and zero if it is not. + + Arguments + The arguments of select() are as follows: + + readfds + The file descriptors in this set are watched to see if they are ready for reading. A file descriptor is ready for + reading if a read operation will not block; in particular, a file descriptor is also ready on end-of-file. + + After select() has returned, readfds will be cleared of all file descriptors except for those that are ready for read‐ + ing. + + writefds + The file descriptors in this set are watched to see if they are ready for writing. A file descriptor is ready for + writing if a write operation will not block. However, even if a file descriptor indicates as writable, a large write + may still block. + + After select() has returned, writefds will be cleared of all file descriptors except for those that are ready for writ‐ + ing. + + exceptfds + The file descriptors in this set are watched for "exceptional conditions". For examples of some exceptional condi‐ + tions, see the discussion of POLLPRI in poll(2). + + After select() has returned, exceptfds will be cleared of all file descriptors except for those for which an excep‐ + tional condition has occurred. + + nfds This argument should be set to the highest-numbered file descriptor in any of the three sets, plus 1. The indicated + file descriptors in each set are checked, up to this limit (but see BUGS). + + timeout + The timeout argument is a timeval structure (shown below) that specifies the interval that select() should block wait‐ + ing for a file descriptor to become ready. The call will block until either: + + • a file descriptor becomes ready; + + • the call is interrupted by a signal handler; or + + • the timeout expires. + + Note that the timeout interval will be rounded up to the system clock granularity, and kernel scheduling delays mean + that the blocking interval may overrun by a small amount. + + If both fields of the timeval structure are zero, then select() returns immediately. (This is useful for polling.) + + If timeout is specified as NULL, select() blocks indefinitely waiting for a file descriptor to become ready. + + pselect() + The pselect() system call allows an application to safely wait until either a file descriptor becomes ready or until a signal + is caught. + + The operation of select() and pselect() is identical, other than these three differences: + + • select() uses a timeout that is a struct timeval (with seconds and microseconds), while pselect() uses a struct timespec + (with seconds and nanoseconds). + + • select() may update the timeout argument to indicate how much time was left. pselect() does not change this argument. + + • select() has no sigmask argument, and behaves as pselect() called with NULL sigmask. + + sigmask is a pointer to a signal mask (see sigprocmask(2)); if it is not NULL, then pselect() first replaces the current sig‐ + nal mask by the one pointed to by sigmask, then does the "select" function, and then restores the original signal mask. (If + sigmask is NULL, the signal mask is not modified during the pselect() call.) + + Other than the difference in the precision of the timeout argument, the following pselect() call: + + ready = pselect(nfds, &readfds, &writefds, &exceptfds, + timeout, &sigmask); + + is equivalent to atomically executing the following calls: + + sigset_t origmask; + + pthread_sigmask(SIG_SETMASK, &sigmask, &origmask); + ready = select(nfds, &readfds, &writefds, &exceptfds, timeout); + pthread_sigmask(SIG_SETMASK, &origmask, NULL); + + The reason that pselect() is needed is that if one wants to wait for either a signal or for a file descriptor to become ready, + then an atomic test is needed to prevent race conditions. (Suppose the signal handler sets a global flag and returns. Then a + test of this global flag followed by a call of select() could hang indefinitely if the signal arrived just after the test but + just before the call. By contrast, pselect() allows one to first block signals, handle the signals that have come in, then + call pselect() with the desired sigmask, avoiding the race.) + + The timeout + The timeout argument for select() is a structure of the following type: + + struct timeval { + time_t tv_sec; /* seconds */ + suseconds_t tv_usec; /* microseconds */ + }; + + The corresponding argument for pselect() has the following type: + + struct timespec { + time_t tv_sec; /* seconds */ + long tv_nsec; /* nanoseconds */ + }; + + On Linux, select() modifies timeout to reflect the amount of time not slept; most other implementations do not do this. + (POSIX.1 permits either behavior.) This causes problems both when Linux code which reads timeout is ported to other operating + systems, and when code is ported to Linux that reuses a struct timeval for multiple select()s in a loop without reinitializing + it. Consider timeout to be undefined after select() returns. + +RETURN VALUE + On success, select() and pselect() return the number of file descriptors contained in the three returned descriptor sets (that + is, the total number of bits that are set in readfds, writefds, exceptfds). The return value may be zero if the timeout ex‐ + pired before any file descriptors became ready. + + On error, -1 is returned, and errno is set to indicate the error; the file descriptor sets are unmodified, and timeout becomes + undefined. + +ERRORS + EBADF An invalid file descriptor was given in one of the sets. (Perhaps a file descriptor that was already closed, or one on + which an error has occurred.) However, see BUGS. + + EINTR A signal was caught; see signal(7). + + EINVAL nfds is negative or exceeds the RLIMIT_NOFILE resource limit (see getrlimit(2)). + + EINVAL The value contained within timeout is invalid. + + ENOMEM Unable to allocate memory for internal tables. + +VERSIONS + pselect() was added to Linux in kernel 2.6.16. Prior to this, pselect() was emulated in glibc (but see BUGS). + +CONFORMING TO + select() conforms to POSIX.1-2001, POSIX.1-2008, and 4.4BSD (select() first appeared in 4.2BSD). Generally portable to/from + non-BSD systems supporting clones of the BSD socket layer (including System V variants). However, note that the System V + variant typically sets the timeout variable before returning, but the BSD variant does not. + + pselect() is defined in POSIX.1g, and in POSIX.1-2001 and POSIX.1-2008. + +NOTES + An fd_set is a fixed size buffer. Executing FD_CLR() or FD_SET() with a value of fd that is negative or is equal to or larger + than FD_SETSIZE will result in undefined behavior. Moreover, POSIX requires fd to be a valid file descriptor. + + The operation of select() and pselect() is not affected by the O_NONBLOCK flag. + + On some other UNIX systems, select() can fail with the error EAGAIN if the system fails to allocate kernel-internal resources, + rather than ENOMEM as Linux does. POSIX specifies this error for poll(2), but not for select(). Portable programs may wish + to check for EAGAIN and loop, just as with EINTR. + + The self-pipe trick + On systems that lack pselect(), reliable (and more portable) signal trapping can be achieved using the self-pipe trick. In + this technique, a signal handler writes a byte to a pipe whose other end is monitored by select() in the main program. (To + avoid possibly blocking when writing to a pipe that may be full or reading from a pipe that may be empty, nonblocking I/O is + used when reading from and writing to the pipe.) + + Emulating usleep(3) + Before the advent of usleep(3), some code employed a call to select() with all three sets empty, nfds zero, and a non-NULL + timeout as a fairly portable way to sleep with subsecond precision. + + Correspondence between select() and poll() notifications + Within the Linux kernel source, we find the following definitions which show the correspondence between the readable, + writable, and exceptional condition notifications of select() and the event notifications provided by poll(2) and epoll(7): + + #define POLLIN_SET (EPOLLRDNORM | EPOLLRDBAND | EPOLLIN | + EPOLLHUP | EPOLLERR) + /* Ready for reading */ + #define POLLOUT_SET (EPOLLWRBAND | EPOLLWRNORM | EPOLLOUT | + EPOLLERR) + /* Ready for writing */ + #define POLLEX_SET (EPOLLPRI) + /* Exceptional condition */ + + Multithreaded applications + If a file descriptor being monitored by select() is closed in another thread, the result is unspecified. On some UNIX sys‐ + tems, select() unblocks and returns, with an indication that the file descriptor is ready (a subsequent I/O operation will + likely fail with an error, unless another process reopens file descriptor between the time select() returned and the I/O oper‐ + ation is performed). On Linux (and some other systems), closing the file descriptor in another thread has no effect on se‐ + lect(). In summary, any application that relies on a particular behavior in this scenario must be considered buggy. + + C library/kernel differences + The Linux kernel allows file descriptor sets of arbitrary size, determining the length of the sets to be checked from the + value of nfds. However, in the glibc implementation, the fd_set type is fixed in size. See also BUGS. + + The pselect() interface described in this page is implemented by glibc. The underlying Linux system call is named pselect6(). + This system call has somewhat different behavior from the glibc wrapper function. + + The Linux pselect6() system call modifies its timeout argument. However, the glibc wrapper function hides this behavior by + using a local variable for the timeout argument that is passed to the system call. Thus, the glibc pselect() function does + not modify its timeout argument; this is the behavior required by POSIX.1-2001. + + The final argument of the pselect6() system call is not a sigset_t * pointer, but is instead a structure of the form: + + struct { + const kernel_sigset_t *ss; /* Pointer to signal set */ + size_t ss_len; /* Size (in bytes) of object + pointed to by 'ss' */ + }; + + This allows the system call to obtain both a pointer to the signal set and its size, while allowing for the fact that most ar‐ + chitectures support a maximum of 6 arguments to a system call. See sigprocmask(2) for a discussion of the difference between + the kernel and libc notion of the signal set. + + Historical glibc details + Glibc 2.0 provided an incorrect version of pselect() that did not take a sigmask argument. + + In glibc versions 2.1 to 2.2.1, one must define _GNU_SOURCE in order to obtain the declaration of pselect() from . + +BUGS + POSIX allows an implementation to define an upper limit, advertised via the constant FD_SETSIZE, on the range of file descrip‐ + tors that can be specified in a file descriptor set. The Linux kernel imposes no fixed limit, but the glibc implementation + makes fd_set a fixed-size type, with FD_SETSIZE defined as 1024, and the FD_*() macros operating according to that limit. To + monitor file descriptors greater than 1023, use poll(2) or epoll(7) instead. + + According to POSIX, select() should check all specified file descriptors in the three file descriptor sets, up to the limit + nfds-1. However, the current implementation ignores any file descriptor in these sets that is greater than the maximum file + descriptor number that the process currently has open. According to POSIX, any such file descriptor that is specified in one + of the sets should result in the error EBADF. + + Starting with version 2.1, glibc provided an emulation of pselect() that was implemented using sigprocmask(2) and select(). + This implementation remained vulnerable to the very race condition that pselect() was designed to prevent. Modern versions of + glibc use the (race-free) pselect() system call on kernels where it is provided. + + On Linux, select() may report a socket file descriptor as "ready for reading", while nevertheless a subsequent read blocks. + This could for example happen when data has arrived but upon examination has the wrong checksum and is discarded. There may + be other circumstances in which a file descriptor is spuriously reported as ready. Thus it may be safer to use O_NONBLOCK on + sockets that should not block. + + On Linux, select() also modifies timeout if the call is interrupted by a signal handler (i.e., the EINTR error return). This + is not permitted by POSIX.1. The Linux pselect() system call has the same behavior, but the glibc wrapper hides this behavior + by internally copying the timeout to a local variable and passing that variable to the system call. + +EXAMPLES + #include + #include + #include + + int + main(void) + { + fd_set rfds; + struct timeval tv; + int retval; + + /* Watch stdin (fd 0) to see when it has input. */ + + FD_ZERO(&rfds); + FD_SET(0, &rfds); + + /* Wait up to five seconds. */ + + tv.tv_sec = 5; + tv.tv_usec = 0; + + retval = select(1, &rfds, NULL, NULL, &tv); + /* Don't rely on the value of tv now! */ + + if (retval == -1) + perror("select()"); + else if (retval) + printf("Data is available now.\n"); + /* FD_ISSET(0, &rfds) will be true. */ + else + printf("No data within five seconds.\n"); + + exit(EXIT_SUCCESS); + } + +SEE ALSO + accept(2), connect(2), poll(2), read(2), recv(2), restart_syscall(2), send(2), sigprocmask(2), write(2), epoll(7), time(7) + + For a tutorial with discussion and examples, see select_tut(2). + +COLOPHON + This page is part of release 5.08 of the Linux man-pages project. A description of the project, information about reporting + bugs, and the latest version of this page, can be found at https://www.kernel.org/doc/man-pages/. + +Linux 2020-04-11 SELECT(2) From 575888d81b3ecdb49dc31406d12053ab135f648e Mon Sep 17 00:00:00 2001 From: Keith Hall Date: Thu, 15 Oct 2020 06:39:27 +0300 Subject: [PATCH 081/243] Fix Manpage C highlighting regression --- .../syntaxes/02_Extra/Manpage.sublime-syntax | 15 +++++++++++-- assets/syntaxes/02_Extra/syntax_test_man.man | 22 +++++++++++++++++++ .../highlighted/Manpage/select-2.man | 2 +- 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/assets/syntaxes/02_Extra/Manpage.sublime-syntax b/assets/syntaxes/02_Extra/Manpage.sublime-syntax index 121f6ab0..ea0bcb3c 100644 --- a/assets/syntaxes/02_Extra/Manpage.sublime-syntax +++ b/assets/syntaxes/02_Extra/Manpage.sublime-syntax @@ -89,8 +89,9 @@ contexts: scope: entity.name.command-line-option.man - match: '(\[)(=)' captures: + 1: punctuation.section.brackets.begin.man 2: keyword.operator.man - push: expect-parameter + push: [command-line-option-or-pipe, expect-parameter] - match: '\[' push: - meta_scope: entity.name.command-line-option.man @@ -112,13 +113,23 @@ contexts: expect-parameter: - match: '[A-Za-z0-9-]+' scope: variable.parameter.man + - match: (?=\s+\|) + pop: true - match: \| scope: keyword.operator.logical.man + - match: '\[' + scope: punctuation.section.brackets.begin.man + push: + - match: '\]' + scope: punctuation.section.brackets.end.man + pop: true + - include: expect-parameter - match: '$|(?=[],]|{{command_line_option}})' pop: true synopsis: - #- include: scope:source.c + - match: '^(?=\s+(?:#include|/\*))' + push: scope:source.c - match: \[ scope: punctuation.section.brackets.begin.man push: command-line-option-or-pipe diff --git a/assets/syntaxes/02_Extra/syntax_test_man.man b/assets/syntaxes/02_Extra/syntax_test_man.man index 54c052a5..a4c8f91d 100644 --- a/assets/syntaxes/02_Extra/syntax_test_man.man +++ b/assets/syntaxes/02_Extra/syntax_test_man.man @@ -21,6 +21,22 @@ SYNOPSIS # ^ punctuation.section.brackets.begin # ^^^^^^^^^^^^^^^^ entity.name.command-line-option # ^ punctuation.section.brackets.end + [-u | --set-upstream] [-o | --push-option=] +# ^ punctuation.section.brackets.begin +# ^^ entity.name.command-line-option +# ^ keyword.operator.logical +# ^^^^^^^^^^^^^^ entity.name.command-line-option +# ^ punctuation.section.brackets.end +# ^^^^^^^^^^^^^ entity.name.command-line-option + [--force-with-lease[=[:]]] +# ^ punctuation.section.brackets.begin +# ^^^^^^^^^^^^^^^^^^ entity.name.command-line-option +# ^ punctuation.section.brackets.begin +# ^ keyword.operator +# ^^^^^^^ variable.parameter +# ^ punctuation.section.brackets.begin +# ^^^^^^ variable.parameter +# ^^^ punctuation.section.brackets.end example --system [options] # ^^^^^^^^ entity.name @@ -28,6 +44,12 @@ SYNOPSIS COMMON OPTIONS [--quiet] [--debug] [--help|-h] [--version] [--conf FILE] + /* According to POSIX.1-2001, POSIX.1-2008 */ +# ^^ source comment.block punctuation.definition.comment + #include +# ^^^^^^^^ source meta.preprocessor.include keyword.control.import.include + + DESCRIPTION example does something useful in relation to the command line options and configuration information in /etc/example.conf. diff --git a/tests/syntax-tests/highlighted/Manpage/select-2.man b/tests/syntax-tests/highlighted/Manpage/select-2.man index 5ca67908..e01db209 100644 --- a/tests/syntax-tests/highlighted/Manpage/select-2.man +++ b/tests/syntax-tests/highlighted/Manpage/select-2.man @@ -1,4 +1,4 @@ -SELECT(2) Linux Programmer's Manual SELECT(2) +SELECT(2) Linux Programmer's Manual SELECT(2) NAME  select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO - synchronous I/O multiplexing From 5d9adc14e7c5ef15f9bf9d7c2405af22f6d7e978 Mon Sep 17 00:00:00 2001 From: Keith Hall Date: Thu, 15 Oct 2020 08:50:47 +0300 Subject: [PATCH 082/243] Include details about Manpage syntax improvements in the changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b181ff3a..0971c859 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ ## Syntaxes +- Manpage syntax highlighting has been improved, see #1315 (@keith-hall) + ## New themes ## `bat` as a library From 6bf7b79f13b308d6b14d5dfb78ba348922c4cf5b Mon Sep 17 00:00:00 2001 From: Albert Safin Date: Sat, 17 Oct 2020 06:47:09 +0000 Subject: [PATCH 083/243] Fix zsh completion * Fix completion for -p option (#1320) * Use prefixed function names to avoid name clash --- assets/completions/bat.zsh.in | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/assets/completions/bat.zsh.in b/assets/completions/bat.zsh.in index cef5daaa..edaf7aee 100644 --- a/assets/completions/bat.zsh.in +++ b/assets/completions/bat.zsh.in @@ -3,8 +3,8 @@ local context state state_descr line typeset -A opt_args -(( $+functions[_cache_subcommand] )) || -_cache_subcommand() { +(( $+functions[_{{PROJECT_EXECUTABLE}}_cache_subcommand] )) || +_{{PROJECT_EXECUTABLE}}_cache_subcommand() { local -a args args=( '(-b --build -c --clear)'{-b,--build}'[Initialize or update the syntax/theme cache]' @@ -19,12 +19,12 @@ _cache_subcommand() { _arguments -S -s $args } -(( $+functions[_main] )) || -_main() { +(( $+functions[_{{PROJECT_EXECUTABLE}}_main] )) || +_{{PROJECT_EXECUTABLE}}_main() { local -a args args=( '(-A --show-all)'{-A,--show-all}'[Show non-printable characters (space, tab, newline, ..)]' - {-p,--plain}'[Show plain style (alias for `--style=plain`)]:When `-p` is used twice (`-pp`), it also disables automatic paging (alias for `--style=plain --paging=never`)' + '*'{-p,--plain}'[Show plain style (alias for `--style=plain`), repeat twice to disable disable automatic paging (alias for `--paging=never`)]' '(-l --language)'{-l+,--language=}'[Set the language for syntax highlighting]::->language' '(-H --highlight-line)'{-H,--highlight-line}'[Highlight lines N through M]:...' '(--file-name)'--file-name'[Specify the name to display for a file]:...:_files' @@ -51,13 +51,13 @@ _main() { _arguments -S -s $args - case "$state" in + case "$state" in language) local IFS=$'\n' local -a languages languages=( $({{PROJECT_EXECUTABLE}} --list-languages | awk -F':|,' '{ for (i = 1; i <= NF; ++i) printf("%s:%s\n", $i, $1) }') ) - _describe 'language' languages + _describe 'language' languages ;; theme) @@ -79,15 +79,15 @@ if (( ${#words} == 2 )); then local -a subcommands subcommands=('cache:Modify the syntax-definition and theme cache') _describe subcommand subcommands - _main + _{{PROJECT_EXECUTABLE}}_main else case $words[2] in cache) - _cache_subcommand + _{{PROJECT_EXECUTABLE}}_cache_subcommand ;; *) - _main + _{{PROJECT_EXECUTABLE}}_main ;; esac fi From c71c8980cf4a7a917d9fb1712985d3abd48ef54b Mon Sep 17 00:00:00 2001 From: "Zachary J. Rollyson" Date: Sat, 17 Oct 2020 11:19:56 -0400 Subject: [PATCH 084/243] feat: add syntax sample for dotEnv files --- tests/syntax-tests/highlighted/DotENV/.env | 57 +++++++++++++++++++++ tests/syntax-tests/source/DotENV/.env | 57 +++++++++++++++++++++ tests/syntax-tests/source/DotENV/LICENSE.md | 23 +++++++++ 3 files changed, 137 insertions(+) create mode 100644 tests/syntax-tests/highlighted/DotENV/.env create mode 100644 tests/syntax-tests/source/DotENV/.env create mode 100644 tests/syntax-tests/source/DotENV/LICENSE.md diff --git a/tests/syntax-tests/highlighted/DotENV/.env b/tests/syntax-tests/highlighted/DotENV/.env new file mode 100644 index 00000000..f46097cc --- /dev/null +++ b/tests/syntax-tests/highlighted/DotENV/.env @@ -0,0 +1,57 @@ +# Keyword +export TEST_KEYWORD="bar" +export TEST_KEYWORD=12345 +export TEST_KEYWORD=TRUE + +# Variable +TEST_VARIABLE="Hello" + +# String interpolation +TEST_INTERPOLATION_VARIABLE="$VAR1 test test$VAR2test test" +TEST_INTERPOLATION_SYNTAX_ONE="test test{$NVAR1}test{$NVAR2}test test" +TEST_INTERPOLATION_SYNTAX_TWO="test test${NVAR1}test${NVAR2}test test" +TEST_INTERPOLATION_SYNTAX_ALL="test$VAR1test test {VAR2}test test${VAR3}test" + +# Unquoted +TEST_UNQUOTED=bar +TEST_UNQUOTED_NO_VALUE= + +# White spaced +TEST_WHITE_SPACE = +TEST_WHITE_SPACE_STRING = "Hello" +TEST_WHITE_SPACE_UNQUOTED = bar +TEST_WHITE_SPACE_UNQUOTED_BOOL = false +TEST_WHITE_SPACE_UNQUOTED_NUM = 20 + +# language constants +TEST_TRUE=true +TEST_FALSE=false +TEST_NULL=null +TEST_TRUE_CAPITAL=TRUE +TEST_FALSE_CAPITAL=FALSE +TEST_NULL_CAPITAL=NULL + +# Numerical values +TEST_NUM_DECIMAL=54 +TEST_NUM_FLOAT=5.3 +TEST_NUM=1e10 +TEST_NUM_NEGATIVE=-42 +TEST_NUM_OCTAL=057 +TEST_NUM_HEX=0x1A + +# Comments +#TEST_ONE=foobar +# TEST_TWO='foobar' +# TEST_THREE="foobar" # a comment on a commented row +TEST_FOUR="test test test" # this is a comment +TEST_FIVE="comment symbol # inside string" # this is a comment +TEST_SIX="comment symbol # and quotes \" \' inside quotes" # " this is a comment + +# Escape sequences +TEST_ESCAPE="escaped characters \n \t \r \" \' \$ or maybe a backslash \\..." + +# Double Quotes +TEST_DOUBLE="Lorem {$VAR1} ${VAR2} $VAR3 ipsum dolor sit amet\n\r\t\\" + +# Single Quotes +TEST_SINGLE='Lorem {$VAR1} ${VAR2} $VAR3 ipsum dolor sit amet\n\r\t\\' diff --git a/tests/syntax-tests/source/DotENV/.env b/tests/syntax-tests/source/DotENV/.env new file mode 100644 index 00000000..474f6f14 --- /dev/null +++ b/tests/syntax-tests/source/DotENV/.env @@ -0,0 +1,57 @@ +# Keyword +export TEST_KEYWORD="bar" +export TEST_KEYWORD=12345 +export TEST_KEYWORD=TRUE + +# Variable +TEST_VARIABLE="Hello" + +# String interpolation +TEST_INTERPOLATION_VARIABLE="$VAR1 test test$VAR2test test" +TEST_INTERPOLATION_SYNTAX_ONE="test test{$NVAR1}test{$NVAR2}test test" +TEST_INTERPOLATION_SYNTAX_TWO="test test${NVAR1}test${NVAR2}test test" +TEST_INTERPOLATION_SYNTAX_ALL="test$VAR1test test {VAR2}test test${VAR3}test" + +# Unquoted +TEST_UNQUOTED=bar +TEST_UNQUOTED_NO_VALUE= + +# White spaced +TEST_WHITE_SPACE = +TEST_WHITE_SPACE_STRING = "Hello" +TEST_WHITE_SPACE_UNQUOTED = bar +TEST_WHITE_SPACE_UNQUOTED_BOOL = false +TEST_WHITE_SPACE_UNQUOTED_NUM = 20 + +# language constants +TEST_TRUE=true +TEST_FALSE=false +TEST_NULL=null +TEST_TRUE_CAPITAL=TRUE +TEST_FALSE_CAPITAL=FALSE +TEST_NULL_CAPITAL=NULL + +# Numerical values +TEST_NUM_DECIMAL=54 +TEST_NUM_FLOAT=5.3 +TEST_NUM=1e10 +TEST_NUM_NEGATIVE=-42 +TEST_NUM_OCTAL=057 +TEST_NUM_HEX=0x1A + +# Comments +#TEST_ONE=foobar +# TEST_TWO='foobar' +# TEST_THREE="foobar" # a comment on a commented row +TEST_FOUR="test test test" # this is a comment +TEST_FIVE="comment symbol # inside string" # this is a comment +TEST_SIX="comment symbol # and quotes \" \' inside quotes" # " this is a comment + +# Escape sequences +TEST_ESCAPE="escaped characters \n \t \r \" \' \$ or maybe a backslash \\..." + +# Double Quotes +TEST_DOUBLE="Lorem {$VAR1} ${VAR2} $VAR3 ipsum dolor sit amet\n\r\t\\" + +# Single Quotes +TEST_SINGLE='Lorem {$VAR1} ${VAR2} $VAR3 ipsum dolor sit amet\n\r\t\\' \ No newline at end of file diff --git a/tests/syntax-tests/source/DotENV/LICENSE.md b/tests/syntax-tests/source/DotENV/LICENSE.md new file mode 100644 index 00000000..59d0e293 --- /dev/null +++ b/tests/syntax-tests/source/DotENV/LICENSE.md @@ -0,0 +1,23 @@ +The `.env.test` file has been added from https://github.com/zaynali53/DotENV under the following license: + +The MIT License (MIT) + +Copyright (c) 2016 Zayn Ali + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From a3f037773a9ba9dfa21675bc745965864cac9ee8 Mon Sep 17 00:00:00 2001 From: "Zachary J. Rollyson" Date: Sat, 17 Oct 2020 11:20:24 -0400 Subject: [PATCH 085/243] feat: include dotfiles (.) in create_highlighted_versions.py search --- tests/syntax-tests/create_highlighted_versions.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/syntax-tests/create_highlighted_versions.py b/tests/syntax-tests/create_highlighted_versions.py index a8d0bc78..4319f47a 100755 --- a/tests/syntax-tests/create_highlighted_versions.py +++ b/tests/syntax-tests/create_highlighted_versions.py @@ -39,8 +39,9 @@ def get_options(source): def create_highlighted_versions(output_basepath): root = os.path.dirname(os.path.abspath(__file__)) + sources = path.join(root, "source", "*") - for source in glob.glob(path.join(root, "source", "*", "*")): + for source in glob.glob(path.join(sources, "*")) + glob.glob(path.join(sources, ".*")): try: env = os.environ.copy() env.pop("PAGER", None) From fc1f37d3df86616d8a99d70dc5d05fb637417915 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A1n=20Priner?= Date: Tue, 20 Oct 2020 19:32:14 +0200 Subject: [PATCH 086/243] Add Ninja syntax highlighting --- .gitmodules | 3 ++ assets/syntaxes/02_Extra/Ninja | 1 + assets/syntaxes/02_Extra/Ninja.sublime-syntax | 52 +++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 160000 assets/syntaxes/02_Extra/Ninja create mode 100644 assets/syntaxes/02_Extra/Ninja.sublime-syntax diff --git a/.gitmodules b/.gitmodules index 1d94f27e..e00573c6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -197,3 +197,6 @@ [submodule "assets/syntaxes/02_Extra/Apache"] path = assets/syntaxes/02_Extra/Apache url = https://github.com/colinta/ApacheConf.tmLanguage +[submodule "assets/syntaxes/02_Extra/Ninja"] + path = assets/syntaxes/02_Extra/Ninja + url = https://github.com/pope/SublimeNinja.git diff --git a/assets/syntaxes/02_Extra/Ninja b/assets/syntaxes/02_Extra/Ninja new file mode 160000 index 00000000..25830aae --- /dev/null +++ b/assets/syntaxes/02_Extra/Ninja @@ -0,0 +1 @@ +Subproject commit 25830aaec9316b7fca6600000535214164525d7a diff --git a/assets/syntaxes/02_Extra/Ninja.sublime-syntax b/assets/syntaxes/02_Extra/Ninja.sublime-syntax new file mode 100644 index 00000000..e86a522e --- /dev/null +++ b/assets/syntaxes/02_Extra/Ninja.sublime-syntax @@ -0,0 +1,52 @@ +%YAML 1.2 +--- +# http://www.sublimetext.com/docs/3/syntax.html +name: Ninja +file_extensions: + - ninja +scope: source.ninja +contexts: + main: + - match: (#).*$\n? + comment: Comment line. + scope: comment.line.number-sign.ninja + captures: + 1: punctuation.definition.comment.ninja + - match: ^(rule)\b + comment: Rule keyword and keywords for a rule. + captures: + 1: keyword.other.ninja + push: + - match: ^(?=\S) + pop: true + - include: main + - match: \b(?:command|deps|depfile|description|generator|pool|restat|rspfile|rspfile_content)\b + scope: keyword.other.ninja + - match: ^(pool)\b + comment: Pool keyword and keywords for a pool. + captures: + 1: keyword.other.ninja + push: + - match: ^(?=\S) + pop: true + - include: main + - match: \b(?:depth)\b + scope: keyword.other.ninja + - match: ^(?:build|rule|default|include|subninja)\b + comment: Other Keywords. + scope: keyword.other.ninja + - match: '(?:[=:]|\|{1,2})(?=\s)' + comment: Operators for variable assignment (=), rule definition (:), implicit (|) and order only (||) dependencies. + scope: keyword.operator.ninja + - match: \$$ + comment: Line wrap. + scope: keyword.operator.ninja + - match: \$\$ + comment: Dollar literal. + scope: keyword.operator.ninja + - match: '\$[[:alnum:]_-]+' + comment: Simple variables, e.g. $var. + scope: variable.other.ninja + - match: '\${[[:alnum:]_.-]+}' + comment: "Variables, e.g. ${some.var.name}." + scope: variable.other.ninja From b07f3b4e74b104b40b4b79e2a7094cd18b9ec1c2 Mon Sep 17 00:00:00 2001 From: ubaumann Date: Fri, 23 Oct 2020 17:04:56 +0000 Subject: [PATCH 087/243] Add Salt State (SLS) test file --- tests/syntax-tests/highlighted/SLS/test.sls | 57 +++++++++++++++++++++ tests/syntax-tests/source/SLS/test.sls | 57 +++++++++++++++++++++ 2 files changed, 114 insertions(+) create mode 100644 tests/syntax-tests/highlighted/SLS/test.sls create mode 100644 tests/syntax-tests/source/SLS/test.sls diff --git a/tests/syntax-tests/highlighted/SLS/test.sls b/tests/syntax-tests/highlighted/SLS/test.sls new file mode 100644 index 00000000..3e4c6386 --- /dev/null +++ b/tests/syntax-tests/highlighted/SLS/test.sls @@ -0,0 +1,57 @@ +required_packages: + pkg.installed: + - pkgs: + - git + - perl + - fortune + +cowsay_source: + git.latest: + - name: https://github.com/jasonm23/cowsay.git + - target: /root/cowsay + +run_installer: + cmd.run: + - name: ./install.sh /usr/local + - cwd: /root/cowsay + - onchanges: + - git: cowsay_source + +{% set cowfiles = salt.cmd.run('cowsay -l').split('\n')[1:] %} +{% set ascii_arts = cowfiles | join(' ') %} + +{% for ascii_art in ascii_arts.split(' ') %} +run_cowsay_{{ ascii_art }}: # name must be unique + cmd.run: + {% if ascii_art is in ['head-in', 'sodomized', 'telebears'] %} + - name: echo cowsay -f {{ ascii_art }} should not be used + {% else %} + - name: fortune | cowsay -f {{ ascii_art }} + {% endif %} +{% endfor %} + +echo_pillar_demo_1: + cmd.run: + - name: "echo {{ pillar.demo_text | default('pillar not defined') }}" + +echo_pillar_demo_2: + cmd.run: + - name: "echo {{ pillar.demo.text | default('pillar not defined') }}" + +# Comment +{% set rand = salt['random.get_str'](20) %} +{% set IP_Address = pillar['IP_Address'] %} + +wait: + cmd.run: + - name: sleep 210 # another comment + +create_roster_file: + file.managed: + - name: /tmp/salt-roster-{{ rand }} + - contents: + - 'switch:' + - ' host: {{ IP_Address }}' + - " user: test" + - " passwd: {{ passwd }}" + diff --git a/tests/syntax-tests/source/SLS/test.sls b/tests/syntax-tests/source/SLS/test.sls new file mode 100644 index 00000000..a116e6d7 --- /dev/null +++ b/tests/syntax-tests/source/SLS/test.sls @@ -0,0 +1,57 @@ +required_packages: + pkg.installed: + - pkgs: + - git + - perl + - fortune + +cowsay_source: + git.latest: + - name: https://github.com/jasonm23/cowsay.git + - target: /root/cowsay + +run_installer: + cmd.run: + - name: ./install.sh /usr/local + - cwd: /root/cowsay + - onchanges: + - git: cowsay_source + +{% set cowfiles = salt.cmd.run('cowsay -l').split('\n')[1:] %} +{% set ascii_arts = cowfiles | join(' ') %} + +{% for ascii_art in ascii_arts.split(' ') %} +run_cowsay_{{ ascii_art }}: # name must be unique + cmd.run: + {% if ascii_art is in ['head-in', 'sodomized', 'telebears'] %} + - name: echo cowsay -f {{ ascii_art }} should not be used + {% else %} + - name: fortune | cowsay -f {{ ascii_art }} + {% endif %} +{% endfor %} + +echo_pillar_demo_1: + cmd.run: + - name: "echo {{ pillar.demo_text | default('pillar not defined') }}" + +echo_pillar_demo_2: + cmd.run: + - name: "echo {{ pillar.demo.text | default('pillar not defined') }}" + +# Comment +{% set rand = salt['random.get_str'](20) %} +{% set IP_Address = pillar['IP_Address'] %} + +wait: + cmd.run: + - name: sleep 210 # another comment + +create_roster_file: + file.managed: + - name: /tmp/salt-roster-{{ rand }} + - contents: + - 'switch:' + - ' host: {{ IP_Address }}' + - " user: test" + - " passwd: {{ passwd }}" + From be84682bcb1e5ef3aba7ccc355f32f9820aebc86 Mon Sep 17 00:00:00 2001 From: Stefano Probst Date: Sat, 24 Oct 2020 10:24:13 +0200 Subject: [PATCH 088/243] Add MATLAB syntax test file cc sharkdp/bat#1213 --- .../highlighted/MATLAB/test.matlab | 34 +++++++++++++++++++ tests/syntax-tests/source/MATLAB/LICENSE.md | 27 +++++++++++++++ tests/syntax-tests/source/MATLAB/test.matlab | 34 +++++++++++++++++++ 3 files changed, 95 insertions(+) create mode 100644 tests/syntax-tests/highlighted/MATLAB/test.matlab create mode 100644 tests/syntax-tests/source/MATLAB/LICENSE.md create mode 100644 tests/syntax-tests/source/MATLAB/test.matlab diff --git a/tests/syntax-tests/highlighted/MATLAB/test.matlab b/tests/syntax-tests/highlighted/MATLAB/test.matlab new file mode 100644 index 00000000..51c37f76 --- /dev/null +++ b/tests/syntax-tests/highlighted/MATLAB/test.matlab @@ -0,0 +1,34 @@ +function zz=sample(aa) +%%%%%%%%%%%%%%%%%% +% some comments +%%%%%%%%%%%%%%%%%% + +x = 'a string'; % some 'ticks' in a comment +y = 'a string with ''interal'' quotes'; + +for i=1:20 + disp(i); +end + +a = rand(30); +b = rand(30); + +c = a .* b ./ a \ ... comment at end of line and continuation + (b .* a + b - a); + +c = a' * b'; % note: these ticks are for transpose, not quotes. + +disp('a comment symbol, %, in a string'); + +!echo abc % this isn't a comment - it's passed to system command + +function y=myfunc(x) +y = exp(x); + +%{ + a block comment +%} + +function no_arg_func +fprintf('%s\n', 'function with no args') +end diff --git a/tests/syntax-tests/source/MATLAB/LICENSE.md b/tests/syntax-tests/source/MATLAB/LICENSE.md new file mode 100644 index 00000000..be753683 --- /dev/null +++ b/tests/syntax-tests/source/MATLAB/LICENSE.md @@ -0,0 +1,27 @@ +The `test.matlab` file is a modified version of https://github.com/pygments/pygments/blob/3e1b79c82d2df318f63f24984d875fd2a3400808/tests/test_matlab.py under the following license: + +Copyright (c) 2006-2020 by the respective authors (see AUTHORS file). +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tests/syntax-tests/source/MATLAB/test.matlab b/tests/syntax-tests/source/MATLAB/test.matlab new file mode 100644 index 00000000..f27cde62 --- /dev/null +++ b/tests/syntax-tests/source/MATLAB/test.matlab @@ -0,0 +1,34 @@ +function zz=sample(aa) +%%%%%%%%%%%%%%%%%% +% some comments +%%%%%%%%%%%%%%%%%% + +x = 'a string'; % some 'ticks' in a comment +y = 'a string with ''interal'' quotes'; + +for i=1:20 + disp(i); +end + +a = rand(30); +b = rand(30); + +c = a .* b ./ a \ ... comment at end of line and continuation + (b .* a + b - a); + +c = a' * b'; % note: these ticks are for transpose, not quotes. + +disp('a comment symbol, %, in a string'); + +!echo abc % this isn't a comment - it's passed to system command + +function y=myfunc(x) +y = exp(x); + +%{ + a block comment +%} + +function no_arg_func +fprintf('%s\n', 'function with no args') +end From 5ec4936a4f60f604436a32995b4d9995cecbbf15 Mon Sep 17 00:00:00 2001 From: Stefano Probst Date: Sat, 24 Oct 2020 11:20:09 +0200 Subject: [PATCH 089/243] Add Graphviz DOT example files cc sharkdp/bat#1213 --- .../highlighted/Graphviz DOT/test_digraph.dot | 41 +++++++++++++++++++ .../highlighted/Graphviz DOT/test_graph.dot | 3 ++ .../source/Graphviz DOT/LICENSE.md | 22 ++++++++++ .../source/Graphviz DOT/test_digraph.dot | 41 +++++++++++++++++++ .../source/Graphviz DOT/test_graph.dot | 3 ++ 5 files changed, 110 insertions(+) create mode 100644 tests/syntax-tests/highlighted/Graphviz DOT/test_digraph.dot create mode 100644 tests/syntax-tests/highlighted/Graphviz DOT/test_graph.dot create mode 100644 tests/syntax-tests/source/Graphviz DOT/LICENSE.md create mode 100644 tests/syntax-tests/source/Graphviz DOT/test_digraph.dot create mode 100644 tests/syntax-tests/source/Graphviz DOT/test_graph.dot diff --git a/tests/syntax-tests/highlighted/Graphviz DOT/test_digraph.dot b/tests/syntax-tests/highlighted/Graphviz DOT/test_digraph.dot new file mode 100644 index 00000000..dddc1366 --- /dev/null +++ b/tests/syntax-tests/highlighted/Graphviz DOT/test_digraph.dot @@ -0,0 +1,41 @@ +digraph { + label = <Label <font color='red'><b>formating,<br/> test <font point-size='20'>is done<br/> here <i>now.>; + + node [shape=box] + rankdir=LR + margin=0.1 + a->b + + // http://www.graphviz.org/doc/info/colors.html + // note: style=filled! + node [shape=box colorscheme=paired12 style=filled] + margin=0.1 + a2[fillcolor=1] + b2[fillcolor=3] + a2->b2->x2 + + // http://www.graphviz.org/doc/info/colors.html + // note: style=filled! + node [shape=box colorscheme=paired12 style=filled] + rankdir=LR + margin=0.1 + c1[fillcolor=1] + c2[fillcolor=2] + c3[fillcolor=3] + c4[fillcolor=4] + c5[fillcolor=5] + c6[fillcolor=6] + c7[fillcolor=7] + c8[fillcolor=8] + c9[fillcolor=9] + c10[fillcolor=10] + c11[fillcolor=11] + c12[fillcolor=12] + c->{c1 c3 c5 c7 c9 c11} + c1->c2 + c3->c4 + c5->c6 + c7->c8 + c9->c10 + c11->c12 +} diff --git a/tests/syntax-tests/highlighted/Graphviz DOT/test_graph.dot b/tests/syntax-tests/highlighted/Graphviz DOT/test_graph.dot new file mode 100644 index 00000000..205c2981 --- /dev/null +++ b/tests/syntax-tests/highlighted/Graphviz DOT/test_graph.dot @@ -0,0 +1,3 @@ +graph { + a--b +} diff --git a/tests/syntax-tests/source/Graphviz DOT/LICENSE.md b/tests/syntax-tests/source/Graphviz DOT/LICENSE.md new file mode 100644 index 00000000..3f166cbe --- /dev/null +++ b/tests/syntax-tests/source/Graphviz DOT/LICENSE.md @@ -0,0 +1,22 @@ +The files `test_digraph.dot` and `test_graph.dot` are modified versions the files from https://github.com/scriptum/graphviz-examples/tree/a7762875efa32f90f6f1a37d866b2c26d362202a under the following license: + +The MIT License (MIT) + +Copyright (c) 2014 Pavel Roschin + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/tests/syntax-tests/source/Graphviz DOT/test_digraph.dot b/tests/syntax-tests/source/Graphviz DOT/test_digraph.dot new file mode 100644 index 00000000..11e383b4 --- /dev/null +++ b/tests/syntax-tests/source/Graphviz DOT/test_digraph.dot @@ -0,0 +1,41 @@ +digraph { + label =